﻿var rendererOptions = {
    draggable: true,
    suppressMarkers: true
  };

function calcRoute(mapObject) {
    var request = {
        origin:mapObject.startMarker.position, 
        destination:mapObject.endMarker.position,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    mapObject.directionsService.route(request, function(response, status) {
      if (status != google.maps.DirectionsStatus.OK) {
        alert("Directions have not found");        
      }
      mapObject.directionsDisplay.setDirections(response);});
  }
  
function getDirections(mapObject) {
if ((mapObject.startMarker) && (mapObject.endMarker)) {
    mapObject.directionsDisplay.setMap(mapObject.map);
    mapObject.directionsDisplay.setPanel(document.getElementById("directionsPanel"+mapObject.mapSettings.Id));
    calcRoute(mapObject);
} else { alert("Click map to end Start and End markers"); }

}

var markersArray = [];

function deleteOverlays(marker) {
  if (markersArray) {
    for (i in markersArray) {
        if(markersArray[i] = marker)
            markersArray[i].setMap(null);
    }
  }
}

function makeDirectionsMarkers(event,mapObject)
{
    if(!mapObject.startMarker)
    {
		var startIcon = new google.maps.MarkerImage('http://www.google.com/mapfiles/icon_greenA.png',
			  new google.maps.Size(22, 34),
			  new google.maps.Point(0,0),
			  new google.maps.Point(9, 34));

        mapObject.startMarker = new google.maps.Marker({
            position: event.latLng,
            draggable:true,
            animation: google.maps.Animation.DROP,
            map: mapObject.map,
            icon: startIcon });
            
        markersArray.push(mapObject.startMarker);
   
        google.maps.event.addListener(mapObject.startMarker, 'click', function() {
        deleteOverlays(mapObject.startMarker);
        mapObject.startMarker = null;
        mapObject.directionsDisplay.setPanel(null);  
        mapObject.directionsDisplay.setMap(null);
            });
    }
    else if(!mapObject.endMarker)
    {
		var endIcon = new google.maps.MarkerImage('http://www.google.com/mapfiles/icon_greenB.png',
			  new google.maps.Size(22, 34),
			  new google.maps.Point(0,0),
			  new google.maps.Point(9, 34));
        mapObject.endMarker = new google.maps.Marker({
            position: event.latLng,
            draggable:true,
            animation: google.maps.Animation.DROP,
            map: mapObject.map,
            icon: endIcon });
            
        markersArray.push(mapObject.endMarker);
   
        google.maps.event.addListener(mapObject.endMarker, 'click', function() {
        deleteOverlays(mapObject.endMarker);
        mapObject.endMarker = null;
        mapObject.directionsDisplay.setPanel(null);  
        mapObject.directionsDisplay.setMap(null);         
            });
    }
    else { alert("Start and End points both defined, click on one to delete it."); }

}


function LoadSettingsMap(mapObject){ 
    var mapDiv = jQueryCS("#theMap");
    
    mapObject.map = new google.maps.Map(mapDiv[0], setManageMapSettings(mapObject));
    google.maps.event.addListener(mapObject.map, "click", function(event) {
 getAddress(event)});
     for(var i in mapObject.locations)
    {
       createMarker(mapObject, i);
    }
                    
    return mapObject.map;
} 
    
function getAddress(event) {
  if (event.latLng != null) {
   jQueryCS("#lt").children().val(event.latLng.lat() % 360);  
   jQueryCS("#lg").children().val(event.latLng.lng() % 360);  
  }
}   
function getMarkerAddress(location) {
  if (location!= null) {
   jQueryCS("#lt").children().val(location.lat() % 360);  
   jQueryCS("#lg").children().val(location.lng() % 360);  
  }
} 

function LoadMap(mapObject){    

    var mapDiv = jQueryCS("#theMap" + mapObject.mapSettings.Id);
    mapDiv.width(mapObject.mapSettings.Width);
    mapDiv.height(mapObject.mapSettings.Height); 
    
    mapObject.map = new google.maps.Map(mapDiv[0], setMapSettings(mapObject));
                    
    configureMapLocations(mapObject);
    if(mapObject.mapSettings.EnableDirections)
    {
        google.maps.event.addListener(mapObject.map, "click", function(event) {
            makeDirectionsMarkers(event,mapObject)});
    }
    
    mapObject.directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
       
    
    return mapObject.map;
}




function setManageMapSettings(mapObject)
{
    var myOptions = {
      zoom: 10,
      center: new google.maps.LatLng(mapObject.mapSettings.Latitude, mapObject.mapSettings.Longitude),
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      mapTypeControl: true,
      streetViewControl: true,
      scaleControl:true ,
      navigationControl: true,
      navigationControlOptions: {style: google.maps.NavigationControlStyle.DEFAULT}
      
    };    
    return myOptions
}
 
function setMapSettings(mapObject)
{
    var mapType;
    switch(mapObject.mapSettings.MapType)
    {
        case 0: mapType = google.maps.MapTypeId.ROADMAP; break;
        case 1: mapType = google.maps.MapTypeId.SATELLITE; break;
        case 2: mapType = google.maps.MapTypeId.HYBRID; break;
        case 3: mapType = google.maps.MapTypeId.TERRAIN; break;
    }
    var myOptions = {
      zoom: mapObject.mapSettings.Zoom,
      center: new google.maps.LatLng(mapObject.mapSettings.Latitude, mapObject.mapSettings.Longitude),
      mapTypeId: mapType,
      streetViewControl: mapObject.mapSettings.StreetView,
      mapTypeControl: !mapObject.mapSettings.DisableMapType,
      scaleControl: mapObject.mapSettings.ShowScale,
      scrollwheel: mapObject.mapSettings.ScrollZoom,
      navigationControl: !mapObject.mapSettings.DisableDragging,
      navigationControlOptions: {style: mapObject.mapSettings.ZoomButton ? google.maps.NavigationControlStyle.SMALL:google.maps.NavigationControlStyle.DEFAULT}
      
    };    
    var searchDiv = jQueryCS("#showSearch" + mapObject.mapSettings.Id);
        if(!mapObject.mapSettings.ShowSearch)
        {
            searchDiv.hide();
        }  
    
    return myOptions
}

 function codeAddress(map,id,message) {
    var address = document.getElementById("address"+id).value;
    new google.maps.Geocoder().geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        map.setZoom(15);
        var newMarker = new google.maps.Marker({
            position: results[0].geometry.location,
            map: map 
            
        });
        
        google.maps.event.addListener(newMarker, "click", function() {
            getMarkerAddress(results[0].geometry.location)});
        
      } else {
        alert(message);
      }
    });
  }
   
function configureMapLocations(mapObject)
{
    for(var i in mapObject.locations)
    {
       createMarker(mapObject, i);
    }
    //if(mapObject.locations.length == 1)
      //  showInfo(mapObject, 0);
}

function createMarker(mapObject, number)
{
    var location = mapObject.locations[number];
    if(location.HasImageMarker)
    {
        var image = new google.maps.MarkerImage(mapObject.imageHandler + '?imgid=' + location.Id  + '&imgMarker=true',
            new google.maps.Size(location.ImageMarkerWidth,location.ImageMarkerHeight),
            new google.maps.Point(0,0),
            new google.maps.Point(0, location.ImageMarkerHeight));
        
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(location.Latitude,location.Longitude),
            map: mapObject.map,
            icon: image });

    }
    else
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(location.Latitude,location.Longitude),
            map: mapObject.map});
    marker.value = number;

    google.maps.event.addListener(marker, 'click', function() {
      showInfo(mapObject, number);
    });

    return marker;
}

function escapeHTML (str)
{
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;

};

function isEncHTML(str) {
    if (str.search(/&amp;/g) != -1 || str.search(/&lt;/g) != -1 || str.search(/&gt;/g) != -1)
        return true;
    else
        return false;
}; 

function decHTMLifEnc(str) {
    if (isEncHTML(str))
        return str.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '\'');
    return str;
}

function showInfo(mapObject, index)
{
    var location = mapObject.locations[index];
    var point = new google.maps.LatLng(location.Latitude,location.Longitude);
   

    var t;
    if (location.UseWysiwyg) {
        t ='<div style="max-width:400px;max-height:200px;overflow:auto;"><div style="">' + decHTMLifEnc(location.WysiwygData) + '</div></div>';
    }
    else {
        t = (location.HasImage ? '<img align="left" src="' + mapObject.imageHandler + '?imgid=' + location.Id + '" style="padding-right:7px;padding-bottom:5px;"/>' : '');
        t = t + '<div class="infoHeader" align="left">' + location.LocationName + '</div><div  class="info">';
        if (location.Address != '')
            t = t + mapObject.locationDictionary.Address + ' : ' + location.Address + '<br/>';
        if (location.Zip != '')
            t = t + mapObject.locationDictionary.Zip + ' : ' + location.Zip + '<br/>';
        if (location.City != '')
            t = t + mapObject.locationDictionary.City + ' : ' + location.City + '<br/>';
        if (location.Country != '')
            t = t + mapObject.locationDictionary.Country + ' : ' + location.Country + '<br/>';
        if (location.PhoneNumber != '')
            t = t + mapObject.locationDictionary.PhoneNumber + ' : ' + location.PhoneNumber;
        t = t + '</div>';
    }
    
    mapObject.infowindow.content = t;
    mapObject.infowindow.position = point;
    mapObject.infowindow.open(mapObject.map);
    
//     var infowindow = new google.maps.InfoWindow(
//    { content: t,
//        position: point
//    });
  //infowindow.open(mapObject.map);
}  
    
function centerLocation(map, location, settings)
{
    map.setCenter(new google.maps.LatLng(location.Latitude, location.Longitude));
}

function SetUniqueRadioButton(current)
{
    for(i = 0; i < document.forms[0].elements.length; i++)
    {
        elm = document.forms[0].elements[i]
        if (elm.type == 'radio')
        {
           elm.checked = false;
        }
    }
    current.checked = true;
}


function getScrollXY() { 
    var scrOfX = 0, scrOfY = 0; 
    if( typeof( window.pageYOffset ) == 'number' ) { 
      //Netscape compliant 
      scrOfY = window.pageYOffset; 
      scrOfX = window.pageXOffset; 
    } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) { 
      //DOM compliant 
      scrOfY = document.body.scrollTop; 
      scrOfX = document.body.scrollLeft; 
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) { 
      //IE6 standards compliant mode 
      scrOfY = document.documentElement.scrollTop; 
      scrOfX = document.documentElement.scrollLeft; 
    } 
    return {X:scrOfX, Y:scrOfY}; 
} 

function getWindowSize() { 
     var myWidth = 0, myHeight = 0; 
     if( typeof( window.innerWidth ) == 'number' ) { 
       //Non-IE 
       myWidth = window.innerWidth; 
       myHeight = window.innerHeight; 
     } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { 
       //IE 6+ in 'standards compliant mode' 
       myWidth = document.documentElement.clientWidth; 
       myHeight = document.documentElement.clientHeight; 
     } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) { 
       //IE 4 compatible 
       myWidth = document.body.clientWidth; 
       myHeight = document.body.clientHeight; 
     } 
     return{X:myWidth, Y:myHeight} 
} 

function centerPopup(id){ 
    var windowDim = getWindowSize(); 
    var popupHeight = jQueryCS("#popupMap"+id).height(); 
    var popupWidth = jQueryCS("#popupMap"+id).width(); 
    var scroll = getScrollXY(); 
    
    jQueryCS("#popupMap"+id).css({ 
        "position": "absolute", 
        "top": windowDim.Y/2-popupHeight/2 + scroll.Y-15, 
        "left": windowDim.X/2-popupWidth/2 + scroll.X-15 
    });

    jQueryCS("#backgroundPopup").css({ 
    "height": windowDim.Y 
    });  
}
