﻿// JScript File
var map;
var offices;
var geocoder;

var defaultlat = 36 //52.09629672596285;
var defaultlon = 0; //4.405442476272583

var mapzoom = 1; // default zoomlevel
var firstLoad = true;
var isLoading = false;

var initialZoomlevel = 3;
var initialBounds;
var initialCenter;

var bounds;
var doMapUpdate = true;
var isMapBound = false;

function initMap() {

    if (GBrowserIsCompatible()) {
        
        
		geocoder = new GClientGeocoder();
        // create new map and add zoom control and type of map control
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        
        //map.enableScrollWheelZoom(); 
        map.setCenter(new GLatLng(defaultlat, defaultlon), mapzoom);
        
       
        resetBounds();
        doMapUpdate = true;
        //closeDetailsView();
       
     }
}

function initEventListeners() {
     GEvent.addListener(map, "moveend", function(){ downloadCurrentViewOfficeData(); });
}


// findLocation() is used to enter the sample addresses into the form.
function findLocation(location, zoomlevel) {
   
     if (doMapUpdate) {
     
          resetBounds();
          var oldzoom = map.getZoom();
          map.setZoom(3);  
          map.clearOverlays(); 
          
          geocoder.getLatLng(location, function(point) { 
             doMapUpdate = false; 
             window.setTimeout(function() {  map.panTo(point); }, 100);  
             }); 
          
          if (location.indexOf(',') < 0) { 
             
            downloadOfficeData('','', location);
             
          } else {
             downloadCurrentViewOfficeData();
             map.setZoom(13);
          }
          
          doMapUpdate = true;
     }
}

function resetBounds() {
    bounds = null;
    bounds = new GLatLngBounds();
}
function storeMapSettings() {

    initialZoomlevel = map.getBoundsZoomLevel(bounds);
    initialCenter = map.getCenter();
    
}
function zoomToBounds() {
     if (bounds != null) {
        var zoom = map.getBoundsZoomLevel(bounds);
        map.setZoom(((zoom > 13) ? 13 : zoom));
        map.setCenter(bounds.getCenter());
     }
}

function setSwitchView() {
     map.setCenter(initialCenter);
     map.setZoom(initialZoomlevel);
}
// addAddressToMap() is called when the geocoder returns an
// answer.  It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.
function addAddressToMap(response) {
     
      
      if (!response || response.Status.code != 200) {
        alert("Sorry, we were unable to geocode that address");
      } else {
        place = response.Placemark[0];
        
    
   
        //addIndicationMarker(place.Point.coordinates[1], place.Point.coordinates[0]);
    
      }
      
      
      
}

function addIndicationMarker(point) {
    
    var icon = new GIcon();
    icon.image = "grfx/marker.png";
    icon.shadow = "grfx/marker_shadow.png";
	
	icon.iconSize = new GSize(25, 27);
	icon.iconAnchor = new GPoint(11, 0);
	icon.shadowSize = new GSize(40, 27);
	icon.infoWindowAnchor = new GPoint(11, 0);
	
    marker = new GMarker(point, icon);
	map.addOverlay(marker);
    
    window.setTimeout(function() {  map.panTo(point); }, 100);
	
	 
}

function showCompanyOnMap(latitude, longitude, markerid, mapzoom) {

    doMapUpdate = false;
    addOfficeMarker(latitude, longitude, markerid);
    moveToPoint(point, mapzoom);
    var timeout = setTimeout("doMapUpdate = true", 1500);

}

function moveToPoint(mappoint, mapzoom) {
     window.setTimeout(function() {  map.panTo(mappoint); }, 100);
     window.setTimeout(function() {  map.setCenter(new GLatLng(mappoint.y, mappoint.x), mapzoom); }, 750 );
}

function addOfficeMarker(latitude, longitude, markerid) {
    
    
     var icon = new GIcon();
     icon.image = "grfx/marker_fugro.gif";
     icon.shadow = "grfx/marker_fugro_gif_shadow.png";
     icon.shadowSize = new GSize(29, 22);
	icon.iconSize = new GSize(19, 22);
	icon.iconAnchor = new GPoint(3, 22);
	icon.infoWindowAnchor = new GPoint(19, 0);


	if (longitude != null) {
	    point = new GLatLng(latitude, longitude);
	} else {
	    point = new GLatLng(0, 0);
	}
	
     marker = new GMarker(point, icon);
	GEvent.addListener(  marker, "click", function() { GetLocationDetails(longitude, latitude); } ); // ShowCompanyInfo(markerid); });
    
    map.addOverlay(marker);
    bounds.extend(point);
    
}

var nodeval;
function GetNodeValue(doc, tag) {
    nodeval = '';
    FindNodeValue(doc, tag);
    return nodeval;
}

function FindNodeValue(doc, tag) {
    
    if (doc.tagName == tag) {
        if (doc.firstChild != null) 
              nodeval = doc.firstChild.nodeValue;
    } else {
        if (doc.hasChildNodes) {
             for (var n = 0; n < doc.childNodes.length; n++) {
                FindNodeValue(doc.childNodes[n], tag);
               
             }
        }  
    }
 
}

function gotoLocation(latitude, longitude) {
    point = new GLatLng(latitude,longitude);
    map.panTo(point);
  
}

function showOffice(longitude, latitude, officeid) {
     //zoomToBounds();
    doMapUpdate = false;
    map.clearOverlays();
    if (longitude != null && longitude != "0") {
        addOfficeMarker(latitude, longitude, officeid);
        gotoLocation(latitude, longitude);
        GetLocationDetails(longitude, latitude);
    }
     GetOfficeDetails(officeid);
     var timeout = setTimeout("doMapUpdate = true", 1000);
}

function downloadCurrentViewOfficeData() {
 
    
    if ( map.getZoom() >= 4 && 
         doMapUpdate) {
        //map.clearOverlays();
        downloadMapAreaCompanyData();
        var bnds = map.getBounds();
        GetOfficeListByArea(bnds.getSouthWest().lng(), bnds.getSouthWest().lat(),
                            bnds.getNorthEast().lng(), bnds.getNorthEast().lat());
        
    } else {
        
    }
}

/* process markers XML */
function downloadOfficeData(mapBounds, officeid, country) {
    
    if (doMapUpdate) {
         doMapUpdate = false;
         SetLoading();
         
         var parms;
         if (mapBounds != '') {
         
             isMapBound = true;
             parms = "?sw=" + mapBounds.getSouthWest().lat() + "," + mapBounds.getSouthWest().lng() +
             "&ne=" + mapBounds.getNorthEast().lat() + "," + mapBounds.getNorthEast().lng() + "&";
             
         } else if (officeid != '') {
             isMapBound = false;
             parms = "?id=" + officeid;
         } else if (country != '') {
         
             isMapBound = false;
             parms = "?country=" + country;
         }
         
         if (parms.length > 0) {
           //alert('new load');
          
          isLoading = true; // loading new data
          GDownloadUrl('data/getMarkers.aspx' + parms , loadMarkerData);
          
         } 
    }
    
}

function loadMarkerData(data) {

	if (GBrowserIsCompatible()) {
          doMapUpdate = false;
		fillOfficesFromXMLData(data);
		
 	    if (data.length == 0) {
            //alert('No office data to display.');
            isLoading = false; 
            doMapUpdate = true;
        }  else {
            //document.getElementById('testtest').innerHTML += 'Plotting ' + offices.length + ' office locations.<br>----<br/>';
            //done loading
            isLoading = false; 
            placeMarkers();
           
        }
        
        
    } else {
        alert('Browser not compatible');
    }
    isLoading = false; //done loading
}

function placeMarkers() {

   // map.clearOverlays();
    
    for (var n = 0; n < offices.length; n++) {
        
        if (isLoading == true) break;
            
           addOfficeMarker(
            parseFloat(offices[n].getAttribute("Latitude")), 
            parseFloat(offices[n].getAttribute("Longitude")),
            n
         );
    }
    
   if (!isMapBound && !isLoading) setTimeout('zoomToBounds();', 1000);
   var doupdatetimer = setTimeout('doMapUpdate = true;', 1000);
   RemoveLoading();
   

}

function fillOfficesFromXMLData(data) {
	// create list of GPS data locations from our XML
	
	var xml = GXml.parse(data);	
	// markers that we will display on Google map
	offices = xml.getElementsByTagName("Office");
}


function downloadMapAreaCompanyData() {
   isMapBound = true;
   if (map.getZoom() >= 4 && doMapUpdate == true) {
   
    map.clearOverlays();
    downloadOfficeData(map.getBounds(), '','');
   }

}

var xmlDoc; 
function importXML(file) { 
 var xmlDoc; 
 var moz = (typeof document.implementation != 'undefined') && (typeof 
document.implementation.createDocument != 'undefined'); 
 var ie = (typeof window.ActiveXObject != 'undefined'); 

 if (moz) { 
   xmlDoc = document.implementation.createDocument("", "", null) 
   xmlDoc.onload = readXML; 
 } else if (ie) { 
   xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); 
   xmlDoc.async = false; 
   while(xmlDoc.readyState != 4) {}; 
 } 
 xmlDoc.load(file); 
}


function SetLoading() {
    
    var overlay = document.getElementById("loading");
    overlay.style.display = 'block'; 
    
    var gmap = document.getElementById("map");
    var offsets = findPos(gmap);
    
    //overlay.style.display = 'none';
    overlay.style.left = (offsets[0] + (gmap.offsetWidth/2) - 16) + "px"; 
    overlay.style.top  = Math.round((offsets[1] + (gmap.offsetHeight/2) - 16) ) + "px";
    
    
}

function RemoveLoading() {
   document.getElementById("loading").style.display = 'none';
}

function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
	    do {
		    curleft += obj.offsetLeft;
		    curtop += obj.offsetTop;
	    } while (obj = obj.offsetParent);
    }
    return [curleft,curtop];
}