﻿
//        var localPort = 3204;
        var localPort = 0;    remote website
        var startPin = "http://maps.google.com/mapfiles/ms/micons/rangerstation.png"
        var endPin = "http://maps.google.com/mapfiles/ms/micons/cycling.png"
        var mapName = 'TGOC2009';
        var startDate = '2009/05/08';      //Y/M/D format
        var endDate = '2009/05/22';
//        var mapName = 'TGOC2010';
//        var startDate = '2010/04/08';      //Y/M/D format
//        var endDate = '2010/05/22';
        var endreplayDate = new Date(endDate);
        var startD;  //yyy-mm-dd
        var endD;  //yyy-mm-dd
        var delayDays = 0;
        var startLat = 57.5 // 11.178402  // 4.565474     //11.178402; normal world
        var startLon = -4  //10.898438  // -163.125     //10.898438;
        var startZoom = 7;
        var midZoom = 10;
        var endZoom = 14;
        var wiggle = 1.175;
        var mileAdj=0;
        var units = "miles" //"kms" ; //not "miles" // 1.609344000000865
        var optPhoto = "false";
        var optMiles = "false";
        var optText = "false";
        var timeLapse = "false";
        var legs = 1;
        var Pin = new GIcon();
        var quit = false;
                        
//        Pin.iconSize = new GSize(20, 20);
//        Pin.iconAnchor = new GPoint(10, 10);
//        Pin.infoWindowAnchor = new GPoint(10, 10);
        
        Pin.iconSize = new GSize(10, 10);
        Pin.iconAnchor = new GPoint(5, 5);
        Pin.infoWindowAnchor = new GPoint(5, 5);
          
        var xmlDoc;
        var IE;
        var count;
        var map;
        var pollCount = 0;
        var dateAdjust = 0;
        var zoom = startZoom;
        var uri;
        var marker;
        var htmls  = new Array();
        var centre = new Array();
        var dir = "in";
        var startJsD; //full java date
        var endJsD; //full java date
        var today; //full java date
        var rrFlag = false;
        var int;
        var side_bar_html;
        var side;
        var lastZoomI = 99;
        var firstClick = true;
        var lastColour;
                       
        ///////////////////////////////////////////////////////////////////////////////////
        function init() {

            if (GBrowserIsCompatible()) {

                map = new GMap2(document.getElementById("map"));
                
                map.addMapType(G_PHYSICAL_MAP);
                map.addControl(new GSmallMapControl());
                map.addControl(new GMenuMapTypeControl());
                map.addControl(new GScaleControl());
                map.addControl(new GHierarchicalMapTypeControl());
                map.setCenter(new GLatLng(startLat,startLon), startZoom);
                map.setMapType(G_PHYSICAL_MAP);
                              
//                var mgr = new MarkerManager(map);
//                var polylineEncoder = new PolylineEncoder();
                
                readMap();

//                }      // end of days for loop
                

            } else {

                alert("Sorry, the Google Maps API is not compatible with this browser");

            }

        }  
        
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////

        function readMap() {   //1

            if (quit == true) {

            } else {

                var clockTime = getClockTime();
                
                startJsD = new Date(startDate); //full java date
                today = new Date(); //full java date

                if (rrFlag == true) {

                    if (endreplayDate < endJsD) {

                        document.getElementById("clock").style.backgroundColor = "transparent";
                        rrFlag = false;
                        document.getElementById("clock").innerHTML = "<b>" + clockTime + "<b> GMT updated every 15 mins by Adventure Trading Ltd.";
  
                    } else {

                        document.getElementById("clock").style.backgroundColor = "Red";
                        endJsD.setDate(endJsD.getDate() + 1);
                        document.getElementById("clock").innerHTML = "<b>Last positions before " + endJsD.getDate() + "/" + (endJsD.getMonth() + 1) + "/" + endJsD.getFullYear() + "<b>";

                    }

                } else {

                    endJsD = new Date(endDate);     //full java date

                    if (today < startJsD) {

                        document.getElementById("clock").style.backgroundColor = "Red";
                        document.getElementById("clock").innerHTML = "<b>Trip due to start " + startJsD.getDate() + "/" + (startJsD.getMonth() + 1) + "/" + startJsD.getFullYear() + "<b>";

                    } else if (today > endJsD) {

                        document.getElementById("clock").style.backgroundColor = "Red";
                        document.getElementById("clock").innerHTML = "<b>Trip finished " + endJsD.getDate() + "/" + (endJsD.getMonth() + 1) + "/" + endJsD.getFullYear() + "<b>";

                    } else if (today > startJsD) {

                        document.getElementById("clock").innerHTML = "<b>" + clockTime + "<b> GMT updated every 15 mins by Adventure Trading Ltd.";

                    }

                }        //end of rrFlag

                endD = "'" + endJsD.getFullYear() + "-" + (endJsD.getMonth() + 1) + "-" + endJsD.getDate() + "'";
                startD = "'" + startJsD.getFullYear() + "-" + (startJsD.getMonth() + 1) + "-" + startJsD.getDate() + "'";

                if (localPort == 0) {

                    uri = "http://www.adventuretradingpost.co.uk/MapData-new.aspx?map=" + mapName + "&start=" + startD + "&end=" + endD + "&photo=" + optPhoto + "&miles=" + optMiles + "&text=" + optText + "&units=" + units;

                } else {

                    uri = "http://localhost:" + localPort + "/adventuretradingpost/MapData-new.aspx?map=" + mapName + "&start=" + startD + "&end=" + endD + "&photo=" + optPhoto + "&miles=" + optMiles + "&text=" + optText + "&units=" + units;
                
                    }

                    GDownloadUrl(uri, function(data, responseCode) {    //3
                        xmlDoc = GXml.parse(data);

                        map.clearOverlays();

                        var bounds = new GLatLngBounds(new GLatLng(58.3, -7), new GLatLng(58.5, -1));
                        var title = new GGroundOverlay("http://www.adventuretradingpost.co.uk/images/TGOC2009.PNG", bounds);
                        map.addOverlay(title);

                        var Map1 = xmlDoc.documentElement     // the root element can't be accessed via //.getElementsByTagName("map");
                        var esns = xmlDoc.documentElement.getElementsByTagName("esn");
//                        bounds = new GLatLngBounds();

                        var col0;
                        var col1;
                        var point;
                        var lastPoint;
                        var esnName = new Array();
                        var time;
                        var miles;
                        var cumMiles;
                        var days;
                        var icon;
                        side_bar_html = "CLICK NAMES BELOW TO ZOOM IN & OUT OF THEIR LAST POSITIONS<br><br>";
                        var start = "<div style='margin: 0px; background-color: transparent; text-align:left; font-family: Arial; color:" + col0 + "; font-style:  normal; font-weight: normal; font-size: xx-small;'>";
                        var end = "</div>";
                        var html = "<br><br>";

                        var darkColours = new Array("black", "blue", "fuchsia", "green", "maroon", "navy", "olive", "purple", "red", "teal");
                        var lightColours = new Array("aqua", "gray", "lime", "silver", "yellow", "white");

                        if (esns.length == 0) {  //4

                            document.getElementById("clock").style.backgroundColor = "red";
                            document.getElementById("clock").innerHTML = "No signals received yet.";

                        } else {    //4

                            for (var i = 0; i < esns.length; i++) {   //5

                                var gmarkers = new Array();

                                esnName[i] = esns[i].getAttribute("name");

                                if (esnName[i] == "Jane") { esnName[i] = "Alan" }

                                //                            col0 = darkColours[i+1];
                                //                            col1 = lightColours[i];
                                //                            col1 = esns[i].getAttribute("colour1");

                                col0 = esns[i].getAttribute("colour0");
                                col1 = "white";
                                
                                startPin = "http://www.adventuretradingpost.co.uk/images/" + esns[i].getAttribute("icon");
                                endPin = "http://www.adventuretradingpost.co.uk/images/" + esns[i].getAttribute("icon");
                                
                                cumMiles = 0;

                                var line1 = [];
                                var line2 = [];

                                Pin.image = endPin;
                                markerOptions = { icon: Pin };

                                if (esns[i].childNodes.length > 0) {  //6

                                    for (var j = 0; j < esns[i].childNodes.length; j++) { //7

                                        var child = esns[i].childNodes[j];

                                        if (child.nodeName == 'marker') { //8

                                            text = esnName[i] + "<br>" + child.getAttribute("time") + " GMT.<br>" + "Lat: " + child.getAttribute("lat") + ",  Lon: " + child.getAttribute("lng")
                                            if (optMiles == "true") {

                                                miles = parseFloat(child.getAttribute("miles"));

                                                if (miles == "3873.60") {

                                                    mileAdj = mileAdj - 3873.60
                                                    cumMiles = cumMiles + miles + mileAdj;

                                                } else {

                                                    cumMiles = cumMiles + miles;

                                                }

                                                text = text + "<br>Approx " + parseInt(cumMiles * wiggle) + " " + units + " so far.";

                                            }

                                            if (optText == "true") {

                                                text = text + "<br>" + child.getAttribute("description");

                                            }

                                            if (optPhoto == "true") {

                                                text = text + "<br>" + child.getAttribute("Photo");

                                            }

                                            point = new GLatLng(parseFloat(child.getAttribute("lat")), parseFloat(child.getAttribute("lng")));
//                                            bounds.extend(point);

                                            line1.push(point);
                                            line2.push(point);
                                            gmarkers.push({ latlng: point, text: text, colour: col0 });

                                        }  // end of child1 nodename = marker     //8//

                                    }   // end of if child nodes for loop    //7//

                                }   //end of childnodeslength>0   //6//

                                for (var k in gmarkers) { //10

                                    if (j == 1) { //11

                                        Pin.image = startPin;

                                    } else if (k == j - 1) {

                                        Pin.image = endPin;

                                    } else {

                                        Pin.image = "";
                                        //                                       Pin.image = endPin; 

                                    } //11//

                                    map.addOverlay(create_gmarker(gmarkers[k], markerOptions, mapName));


                                }   //10//

                                map.addOverlay(new GPolyline(line2, col1, 5, .5));
                                map.addOverlay(new GPolyline(line1, col0, 1, 1));

                                //                            map.setCenter(bounds.getCenter());
                                //                            map.setZoom(map.getBoundsZoomLevel(bounds));

                                centre[i] = point;
                                
                                if (rrFlag == true && firstClick == false &&  lastZoomI == i) {

                                    map.setCenter(point);

                                }

                                htmls[i] = start + esnName[i] + html + end;
                                side_bar_html += "<a style='font-family: Arial; color: " + col0 + "; font-style:  normal; font-weight: bold; font-size: medium;' href='javascript: myclick(" + i + ")'>" + esnName[i] + "</a><br><br>";


                            }       // end of for i loop thro all esns    //5//

                            side = side_bar_html;

                        }       // end of test for no of ESNs     //4
                        
                         if (rrFlag == true) {

                            int = 2 * 1000;

//                            document.getElementById("side_bar").innerHTML = side + "HOVER MOUSE OVER LINE BENDS & ICONS TO SEE INFO BALLOONS<br><br>CLICK PAUSE OR STOP BELOW<br><br><a style='font-family: Arial; color: " + "red" + "; font-style:  normal; font-weight: bold; font-size: medium;' href='javascript:pause()'>Pause</a>" + "              " + "<a style='font-family: Arial; color: " + "red" + "; font-style:  normal; font-weight: bold; font-size: medium;' href='javascript:stop()'>Stop</a>";


                        } else {

                            int = 15 * 60 * 1000;

                            document.getElementById("side_bar").innerHTML = side + "HOVER MOUSE OVER LINE BENDS & ICONS TO SEE INFO BALLOONS<br><br>CLICK START BELOW TO REPLAY ROUTES<br><br><a style='font-family: Arial; color: red; font-style:  normal; font-weight: bold; font-size: medium;' href='javascript:start()'>Start</a>";

                        }

                        setTimeout("readMap()", int);

                    });                        //end of //3//      

            }    //end quit
                

}    //end of readMap function   //1//


////////////////////////////////////////////////////////////////////////////

function start() {

    map.clearOverlays();
    map.setCenter(new GLatLng(startLat, startLon), startZoom);
    map.setMapType(G_PHYSICAL_MAP);
    rrFlag = true;
    endJsD.setDate(startJsD.getDate());
    quit = false;
//   firstClick = false;

    document.getElementById("side_bar").innerHTML = side + "HOVER MOUSE OVER LINE BENDS & ICONS TO SEE INFO BALLOONS<br><br>CLICK PAUSE OR STOP BELOW<br><br><a style='font-family: Arial; color: " + "red" + "; font-style:  normal; font-weight: bold; font-size: medium;' href='javascript:pause()'>Pause</a>" + "              " + "<a style='font-family: Arial; color: " + "red" + "; font-style:  normal; font-weight: bold; font-size: medium;' href='javascript:stop()'>Stop</a>";
    
    
    readMap();

}

////////////////////////////////////////////////////////////////////////////

function reStart() {

    if (lastZoomI == 99) {

        map.setCenter(new GLatLng(startLat, startLon), startZoom);
        map.setMapType(G_PHYSICAL_MAP);

    }

    document.getElementById("side_bar").innerHTML = side + "HOVER MOUSE OVER LINE BENDS & ICONS TO SEE INFO BALLOONS<br><br>CLICK PAUSE OR STOP BELOW<br><br><a style='font-family: Arial; color: " + "red" + "; font-style:  normal; font-weight: bold; font-size: medium;' href='javascript:pause()'>Pause</a>" + "              " + "<a style='font-family: Arial; color: " + "red" + "; font-style:  normal; font-weight: bold; font-size: medium;' href='javascript:stop()'>Stop</a>";
    
    rrFlag = true;
    quit = false;
//    firstClick = false;
    readMap();

}

////////////////////////////////////////////////////////////////////////////

function pause() {

//    int = 15 * 60 * 1000;
    rrFlag = true;

    document.getElementById("side_bar").innerHTML = side + "HOVER MOUSE OVER LINE BENDS & ICONS TO SEE INFO BALLOONS<br><br>CLICK RESTART OR STOP BELOW<br><br><a style='font-family: Arial; color: " + "red" + "; font-style:  normal; font-weight: bold; font-size: medium;' href='javascript:reStart()'>Restart</a>" + "              " +  "<a style='font-family: Arial; color: " + "red" + "; font-style:  normal; font-weight: bold; font-size: medium;' href='javascript:stop1()'>Stop</a>";

    quit = true;
//   firstClick = false;

}

////////////////////////////////////////////////////////////////////////////

function stop1() {

    //    int = 15 * 60 * 1000;
    rrFlag = false;

    document.getElementById("side_bar").innerHTML = side + "HOVER MOUSE OVER LINE BENDS & ICONS TO SEE INFO BALLOONS<br><br>CLICK START BELOW TO REPLAY ROUTES<br><br><a style='font-family: Arial; color: red; font-style:  normal; font-weight: bold; font-size: medium;' href='javascript:start()'>Start</a>";

    quit = false;
    //    firstClick = false;

    map.clearOverlays();
    map.setCenter(new GLatLng(startLat, startLon), startZoom);
    map.setMapType(G_PHYSICAL_MAP);

    lastZoomI = 99;

    readMap();

}

////////////////////////////////////////////////////////////////////////////
function stop() {

//    int = 15 * 60 * 1000;
    rrFlag = false;

    document.getElementById("side_bar").innerHTML = side + "HOVER MOUSE OVER LINE BENDS & ICONS TO SEE INFO BALLOONS<br><br>CLICK START BELOW TO REPLAY ROUTES<br><br><a style='font-family: Arial; color: red; font-style:  normal; font-weight: bold; font-size: medium;' href='javascript:start()'>Start</a>";

    quit = false;
//    firstClick = false;

    map.clearOverlays();
    map.setCenter(new GLatLng(startLat, startLon), startZoom);
    map.setMapType(G_PHYSICAL_MAP);

    lastZoomI = 99;
    
//    readMap();

}

  ////////////////////////////////////////////////////////////////////////////

  function create_gmarker(marker, markerOptions, mapName) {

      var gmarker = new GMarker(marker.latlng, markerOptions);

    //      GEvent.addListener(gmarker, 'click', function() {
    //      gmarker.openInfoWindowHtml("<span style='font-family: Arial; color:" + marker.colour + "; font-style:  normal; font-weight: bold; font-size: xx-small'>" + marker.text + "</span>");
    //      }
    //    );

              GEvent.addListener(gmarker, 'mouseover', function() {
                  gmarker.openInfoWindowHtml("<span style='font-family: Arial; color:" + marker.colour + "; font-style:  normal; font-weight: bold; font-size: xx-small'>" + marker.text + "</span>");
              }
          );

            GEvent.addListener(gmarker, 'mouseout', function() {
                gmarker.closeInfoWindow();

            }
          );
    
      //      GEvent.addListener(gmarker, 'click', function() {
      //      window.open("http://www.adventuretradingpost.co.uk/images/" + mapName + "/" + marker.photo);
      //      }
      //    );
      
        return gmarker;
  }      
                
        
        ///////////////////////////////////////////////////////////////////////////////


  function myclick(i) {

      if (lastZoomI == 99) {
//      if (firstClick == true && lastZoomI == 99) {

          zzoomm(i);

      } else if (firstClick == true && lastZoomI == i) { 

          zzoomm(i);

      } else if (lastZoomI == i) {

          zzoomm(i);

      } else {

          map.setCenter(centre[i]);

      }

      lastZoomI = i;
//      lastColour = col0;
      firstClick = false;
       
//       gmarkers[i].openInfoWindowHtml;
       
        }

        ///////////////////////////////////////////////////////////////////////////////////

        function zzoomm(i) {

            Zoom = map.getZoom();

            if (Zoom > midZoom) {
                dir = "out";
                Zoom = midZoom;
                map.setCenter(centre[i], Zoom, G_NORMAL_MAP);

            } else if (Zoom < midZoom) {
                dir = "in";
                Zoom = midZoom;
                map.setCenter(centre[i], Zoom, G_NORMAL_MAP);

            }else if (dir == "in") {
                Zoom = endZoom;
                map.setCenter(centre[i], Zoom, G_SATELLITE_MAP);
                dir = "out";

            } else {
                Zoom = startZoom;
                map.setCenter(centre[i], Zoom, G_PHYSICAL_MAP);
                dir = "in";

            }

        }

        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        function getClockTime() {
        
             dateAdjust=0;
           
            var now = new Date();
            var hour = now.getHours()// + 8;      //HongKong time adj

//            if (hour > 15) {

//                dateAdjust = 1;
//                hour = hour - 8;

//            }
            
            var minute = now.getMinutes();
            var second = now.getSeconds();
            
            var ap = "";    //"AM";
//            if (hour > 11) { ap = "PM"; }
//            if (hour > 12) { hour = hour - 12; }
//            if (hour == 0) { hour = 12; }
            //            if (hour < 10) { hour = "0" + hour; }

            if (minute < 10) { minute = "0" + minute; }
            if (second < 10) { second = "0" + second; }
            
            var timeString = hour + ':' + minute + ':' + second// + " " + ap;
            
            return timeString;
        } // function getClockTime()

        /////////////////////////////////////////////////////////////////////////////////////////

        function getCalendarDate() {
        
            var monthAdjust=0;
        
            var months = new Array(13);
            months[0] = "Jan";
            months[1] = "Feb";
            months[2] = "Mar";
            months[3] = "Apr";
            months[4] = "May";
            months[5] = "Jun";
            months[6] = "Jul";
            months[7] = "Aug";
            months[8] = "Sep";
            months[9] = "Oct";
            months[10] = "Nov";
            months[11] = "Dec";
            var now = new Date();
            var monthnumber = now.getMonth();
            var monthname = months[monthnumber];
            var monthday = now.getDate() + dateAdjust;
            var year = now.getYear();
            if (year < 2000) { year = year + 1900; }
            var dateString = monthday + ' ' + monthname + ' ' + year;
            return dateString;
        } // function getCalendarDate()
        
////////////////////////////////////////////////////////////////////////////////////////////////////


function IEVersion() {

    var _n = navigator, _w = window, _d = document;
    var na = _n.userAgent;
    
//    var version = "NA";
//    var ieDocMode = "NA";
//    var ie8BrowserMode = "NA";

//    // Look for msie and make sure its not opera in disguise

//    if (/msie/i.test(na) && (!_w.opera)) {
//        // also check for spoofers by checking known IE objects
//        if (_w.attachEvent && _w.ActiveXObject) {
//            // Get version displayed in UA although if its IE 8 running in 7 or compat mode it will appear as 7
//            version = (na.match(/.+ie\s([\d.]+)/i) || [])[1];

//            // Its IE 8 pretending to be IE 7 or in compat mode		
//            if (parseInt(version) == 7) {

//                // documentMode is only supported in IE 8 so we know if its here its really IE 8
//                if (_d.documentMode) {
//                    version = 8; //reset? change if you need to

//                    // IE in Compat mode will mention Trident in the useragent
//                    if (/trident\/\d/i.test(na)) {
//                        ie8BrowserMode = "Compat Mode";

//                        // if it doesn't then its running in IE 7 mode
//                    } else {
//                        ie8BrowserMode = "IE 7 Mode";
//                    }
//                }
//            } else if (parseInt(version) == 8) {

//                // IE 8 will always have documentMode available
//                if (_d.documentMode) { ie8BrowserMode = "IE 8 Mode"; }
//            }
//            // If we are in IE 8 (any mode) or previous versions of IE we check for the documentMode or compatMode for pre 8 versions			
//            ieDocMode = (_d.documentMode) ? _d.documentMode : (_d.compatMode && _d.compatMode == "CSS1Compat") ? 7 : 5; //default to quirks mode IE5				   			
//        }
//    }

    if (na.indexOf("MSIE") == -1) { return false } else { return true }

    //    return {
    //        "UserAgent": na
    //        "Version": version,
    //        "BrowserMode": ie8BrowserMode,
    //        "DocMode": ieDocMode
    //    }

}   //end function


////////////////////////////////////////////////////////////////////////////////////////////////////

//function pause(millis) {
//    var date = new Date();
//    var curDate = null;

//    do { curDate = new Date(); }
//    while (curDate - date < millis);

//}


/////////////////////////////////////////////////////////////////////////////

function lineWrite() {   //1


    map.getInfoWindow().hide();
    map.clearOverlays();
    pollCount = pollCount + 1;


    if (j > 0) {

        line1.push(lastPoint);
        //                                            gmarkers[0].hide;

    }

    line1.push(point);
    //                                        gmarkers.push({ latlng: point, text: text, colour: col0 });

    if (j > 0) {

        map.addOverlay(new GPolyline(line1, col0, 1, 1));
        //                                            map.addOverlay(create_gmarker(gmarkers[0], markerOptions, mapName));


    } else {

        line1.push(point);
        //                                        line2.push(point);
        //                                        gmarkers.push({ latlng: point, text: text, colour: col0 });

    }

    lastPoint = point;

    pause(2000);

}

/////////////////////////////////////////////////////////////////////////////
