﻿//127.0.0.1
//var GMAPSKey = "ABQIAAAAgHd2jW6OSo4bQTo7Uu81yhS4qwPmpfNZFQ0JrBppLSF0GGwjMBSJngzZZjX3eaKQlAN1k5rM6etrMQ";

//www.littlefishtravel.com
var GMAPSKey = "ABQIAAAAgHd2jW6OSo4bQTo7Uu81yhQPnR3D_EsiDz5vpOJfQ0qTK5lMEhTwAO3r1zkZ9wm_rNQiI0jzz2d6dA";

var initLoaderOK = false;
var mapAPILoaded = false;
var markerManagerLoaded = false;
var delim = "~$$~";

function setInitLoaderOK(){
    initLoaderOK = true;
    //Now load the map API
    loadMapAPI();
}

function setMapAPILoaded(){
    mapAPILoaded = true;
    //A map should be able to load once initLoaderOK and mapAPILoaded are true.
    
    //load extra utils
    loadMarkerManager();
}

function setMarkerManagerLoaded(){
    //Just give a little more time to actually load the manger
    //before we mark it as loaded.
    window.setTimeout('markerManagerLoaded = true',1000);
}

//STEP 1 - Load this on the body loading
function initLoader() {
    if(!initLoaderOK){
        var script = document.createElement("script");
        //NB: Once loaded this calls setInitLoaderOK, see end of query string
        script.src = "http://www.google.com/jsapi?key=" +GMAPSKey +"&callback=setInitLoaderOK"; 
        script.type = "text/javascript"; 
        document.getElementsByTagName("head")[0].appendChild(script);
    }
}

//STEP 2 - Load the MAP API once initLoaderOK
function loadMapAPI(){
    if(initLoaderOK){
       //google.load("maps", "2.s", {"callback" : setMapAPILoaded});
       google.load("maps", "2.128e", {"callback" : setMapAPILoaded});
        
    }        
}

//STEP 3 - Load Marker Manager (if required)
function loadMarkerManager() {
    if(!markerManagerLoaded){
        var scriptMM = document.createElement("script");
        //scriptMM.src = "http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"; 
        scriptMM.src = "../../JS/GMapsMarkerManager.js"; 
        scriptMM.type = "text/javascript"; 
        document.getElementsByTagName("head")[0].appendChild(scriptMM);
        setMarkerManagerLoaded();
    }
}

//FINAL STEP - Check and load the map, called indpendently, not a call back function
function CheckAndLoadMap(mapObjID,mapCanvasID,defaultPlace,mapZoom,infoWindowText){
    if(initLoaderOK && mapAPILoaded){
        //Got what we need, so go load a map.
        eval("LoadMap('" + mapObjID + "','" + mapCanvasID + "','" + defaultPlace +"'," + mapZoom +",'" + infoWindowText +"')");
    }else{
        //Not got what we need, so try again in moment
         window.setTimeout("CheckAndLoadMap('"+mapObjID +"','" + mapCanvasID +"','" + defaultPlace +"'," + mapZoom + ",'" + infoWindowText + "');", 5)
    }
}  

//FINAL FINAL STEP - Check and load markers on a map
function CheckAndLoadMarkers(callBackFunction){
    if(initLoaderOK && mapAPILoaded && markerManagerLoaded){
        //Got what we need, so load a markers.
        eval(callBackFunction);
    }else{
        //Not got what we need, so try again in moment
         window.setTimeout("CheckAndLoadMarkers('" +callBackFunction +"')", 5);
    }
}  




//All rquirements loaded, so Load a map
function LoadMap(mapObjID,mapCanvasID,defaultPlace, mapZoom, infoWindowText) {
    if (mapAPILoaded && GBrowserIsCompatible()) {
          eval(mapObjID + " = new GMap2(document.getElementById(mapCanvasID));")
 	      eval(mapObjID).addControl(new GSmallMapControl());
          eval(mapObjID).addControl(new GMapTypeControl());
          eval(mapObjID).setCenter(new GLatLng(28.0, 14.0), 2);
          
          if(defaultPlace=='center'){
              var center = eval(mapObjID).getCenter();
              var marker = new GMarker(center);
              eval(mapObjID).addOverlay(marker);
          }else if(defaultPlace !=''){
            AddMarkerToMap(mapObjID, null , defaultPlace, mapZoom,infoWindowText)
          }else{
            eval(mapObjID).setZoom(mapZoom);
          }
   }
}


//Find a location on the map and mark it.
function findLocation(mapObjID, searchTextBoxID, resultTextBoxID, googleAdBoxID, mapZoom, infoWindowText) {
        var searchText = document.getElementById(searchTextBoxID).value;
        var geocoder = new GClientGeocoder();
        geocoder.getLocations(searchText,
            function addAddressToMap(response) {
              eval(mapObjID + ".clearOverlays();");
              if (!response || response.Status.code != 200) {
                alert("Sorry, we were unable to find that location.");
              } else {
                place = response.Placemark[0];
                point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
                //Save
                savePlaceString(place.Point.coordinates[1], place.Point.coordinates[0], place.address, resultTextBoxID, googleAdBoxID)
                // Add Marker
                AddMarkerToMap(mapObjID, place, "", mapZoom,infoWindowText)
              }
            }
        );//Get Locations //return function
}//function

function extractLatFromPlaceString(placeString){
    var arrPlaceString = placeString.split(delim);
    var arrLatLng = arrPlaceString[0].split(",");
    return trim(arrLatLng[0]);
}

function extractLngFromPlaceString(placeString){
    var arrPlaceString = placeString.split(delim)
    var arrLatLng = arrPlaceString[0].split(",");
    return trim(arrLatLng[1]);
}

function getAdFromPlace(placeString){
       var arrPlaceString;

       if(placeString.indexOf(delim) == -1 || placeString.lastIndexOf(delim) == placeString.length){ //ie no delimiter found or last char in string
            return "";
        }else{
             arrPlaceString = placeString.split(delim)
             return trim(arrPlaceString[1])
        }
    ;
}

function getPtFromPlace(placeString){
        var point = new GLatLng(extractLatFromPlaceString(placeString),extractLngFromPlaceString(placeString));            
        return point;
}

function AddMarkerToMap(mapObjID, place, placeString, mapZoom, infoWindowText){
    //MUST pass either a place (object) OR placeString (string)

    var address = "";
    var point = null;
    var windowHTML = infoWindowText;
     
    if (place != null){
        address = place.address;
        point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);//
    }else{
        point = getPtFromPlace(placeString);
        address = getAdFromPlace(placeString)
    }

  
    
    if(point != null){
        eval(mapObjID).clearOverlays();

        if(address.length > 0){
            windowHTML = infoWindowText + "<br/><b>" + formatAddress(address) +"</b>";
        }
        
        marker = new GMarker(point);
        eval(mapObjID).addOverlay(marker);
        marker.openInfoWindowHtml(windowHTML);
        
        GEvent.addListener(eval(mapObjID).getInfoWindow(),"closeclick", function() {
                if(!confirm("The location willl remain selected with the window closed.\n\nAre you sure want to close the window?"))
                    {marker.openInfoWindowHtml(infoWindowText + "<br/><b>" + formatAddress(address) +"</b>");
                };
        });
        
        if (mapZoom != ''){
            eval(mapObjID).setZoom(" + mapZoom +");
        }
        eval(mapObjID).panTo(point); 
    }
}


function formatAddress(address){
    var formatedAddress = "";
    
    if(address != null){
        address = trim(address);
        if(address.length > 0){
           var addressArray = address.split(",");
           formatedAddress = trim(addressArray[0]);
           
           for (var i=1, len=addressArray.length; i<len; i++ )
           {
                addressArray[i] = trim(addressArray[i])
                
                if (addressArray[i] != addressArray[i-1]){
                   if(i!=addressArray.length){
                        formatedAddress += ', ';
                    }
                
                    formatedAddress += addressArray[i];
                }
           }
    }
    }

   return formatedAddress;
}

function savePlaceString(latCoord, lngCoord, address, latLngBoxID, googleAdBoxID) {
  document.getElementById(latLngBoxID).value = latCoord + "," + lngCoord;
  document.getElementById(googleAdBoxID).value = address;
}

 function getIcon(imagePath){
        var icon = new GIcon();
        icon.image = imagePath;
        icon.iconAnchor = new GPoint(16, 16);
        icon.infoWindowAnchor = new GPoint(16, 0);
        icon.iconSize = new GSize(32, 32);
        icon.shadow = imagePath.replace(".png",".shadow.png");
        icon.shadowSize = new GSize(59, 32);
        return icon;
    }
    
    
 function getAvatar(imagePath){
        var icon = new GIcon();
        icon.image = imagePath;
        icon.iconAnchor = new GPoint(16, 16);
        icon.infoWindowAnchor = new GPoint(25, 5);
        return icon;
 }

function GMapsUnload(){
    try{
        GUnload();    
    }
    catch(e){}
}    
 