/*
'============================================================================
' NAME: DEALER JAVASCRIPT
' DESCRIPTION:
'   Scripts for Google maps
' UPDATES
'   2009-05-04 Ola Ljungars: Added method largeMap() for enlarge of the maps
'   2009-04-04 Ola Ljungars: Added support for adding a regular location (normal marker, no scania logo)
'   2009-03-16 David Schulz: Updated toggleSearchForm to handle class instead of style attributes of li:s
'   2008-10-01 Ola Ljungars: Fixed numeric err message
'   2008-09-16 Ola Ljungars: Added function toggeleSearchForm
'   2008-09-11 Ola Ljungars: Added function setBoundaries instead of handling this in template code
'   2008-09-11 Ola Ljungars: Changed link from map to get dealer
'============================================================================
*/

var geocoder, gmap;
var aDealers = new Array(0);
var blueIcon;
var gLtLgBounds;

// Map boundaries (set in CT)
var mapCenterLat, mapCenterLng;
var mapPosMinLat, mapPosMinLng;
var mapPosMaxLat, mapPosMaxLng;

// Constants that can be overridden in CT code
var zoomVal = 6;
var zoomValOnePointOnly = 6;  // can be overridden from component data
var zoomValDealerPage = 14;   // can be overridden from component data
var bIsDealerPrimaryPage = false; // set by PCT Full_Dealer
var bIsRegularLocationMap = false; // set in GoogleMaps.ascx


var strScaniaIconURL    = "http://toolkitstatic.scania.com/static_images/dealer_locator/marker_scania20x19.png";
var strScaniaIconURLGIF = "http://toolkitstatic.scania.com/static_images/dealer_locator/marker_scania20x19.gif";
var strGetDealerURL  = "/_inc/GetDealer.aspx"

var objMapDoc;

var bEnableGeoAddressLocationInfo = false;

function DL_changeCountry(strCountryCode){
  if(strCountryCode!=""){   // in case of .com
    location = "?actionID=showSearchForm&countryCode=" + strCountryCode
  }
}

function DL_changeQuickSearch(strDealerID, strCountryCode){
  openDealerPopUp(strCountryCode + strDealerID)
}

function debug(dStr){
  debugdiv.innerHTML += (dStr + "<br>")
}

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

function setBoundaries(){
  mapPosMinLat = 3000;
  mapPosMaxLat = -3000;

  mapPosMinLng = 3000;
  mapPosMaxLng = -3000;
      
  var i;
  
  for(i=0;i<aDealers.length;i++){
    if(aDealers[i].lat>mapPosMaxLat) mapPosMaxLat=aDealers[i].lat;
    if(aDealers[i].lat<mapPosMinLat) mapPosMinLat=aDealers[i].lat;

    if(aDealers[i].lng>mapPosMaxLng) mapPosMaxLng=aDealers[i].lng;
    if(aDealers[i].lng<mapPosMinLng) mapPosMinLng=aDealers[i].lng;
  }
  mapCenterLat = (mapPosMaxLat + mapPosMinLat)/2;
  mapCenterLng = (mapPosMaxLng + mapPosMinLng)/2;
}


function GMInit(strMapID, bIsPrintable){

  if(typeof(GBrowserIsCompatible) == "undefined")
  	return;
  	
  
  
  if (GBrowserIsCompatible()) {
  	
    if(document.getElementById(strMapID)){
    	
    	
    	
      if(document.body.onunload){
        document.body.onunload = GUnload
      }
      gmap = new GMap2(document.getElementById(strMapID));
      gmap.setCenter(new GLatLng(55, -4), 5);
      if(strMapID!="GoogleMapRC") gmap.addControl(new GSmallMapControl());

      //G_DEFAULT_ICON.shadow = ""
      blueIcon = new GIcon(G_DEFAULT_ICON);
      if(!bIsRegularLocationMap){ // use default if regular location, else use scania logo (dealer location)
        blueIcon.image = strScaniaIconURL;
        blueIcon.iconSize = new GSize(20, 19); 
        blueIcon.shadowSize = new GSize(0, 0);
        blueIcon.shadow = "";
        blueIcon.iconAnchor = new GPoint(10, 10);
        // iconAnchor GPoint The pixel coordinate relative to the top left corner of the icon image at which this icon is anchored to the map. 
        blueIcon.printImage      = strScaniaIconURLGIF;
        blueIcon.mozPrintImage   = strScaniaIconURLGIF;
        blueIcon.printShadow     = ""
      }


      if(!bIsDealerPrimaryPage){
        setBoundaries();
        if(bEnableGeoAddressLocationInfo){
          if(document.forms["RequestForm"]){
            var objForm = document.forms["RequestForm"]
            if(objForm["address"]){
              if(objForm["address"].value!=""){
                getLocation(objForm["address"].value, objForm["countryCode"].value);
              }
            }
          }
        }
        placeLocations();
        
        // Calculate Zoom and Center (for search the postcode point is the center)
        gLtLgBounds = new GLatLngBounds(new GLatLng(mapPosMinLat, mapPosMinLng), new GLatLng(mapPosMaxLat, mapPosMaxLng));
        //debug("setting new viewport: " + mapPosMinLat + " " + mapPosMinLng + " " + mapPosMaxLat + " " + mapPosMaxLng)
        if(aDealers.length !=1){
          zoomVal = gmap.getBoundsZoomLevel(gLtLgBounds)
        }
        else{
          zoomVal = zoomValOnePointOnly;
        }

        //debug("zoomval is:" + zoomVal)
        gmap.setCenter(new GLatLng(mapCenterLat, mapCenterLng), zoomVal);
        gmap.setMapType(G_NORMAL_MAP);
      }
      else{
        if(aDealers.length == 1){  // only one dealer point on dealer primary/micro dealer page
          if(document.body.onunload){
            document.body.onunload = GUnload
          }
          zoomVal = zoomValDealerPage;
          gmap.setCenter(new GLatLng(aDealers[0].lat, aDealers[0].lng), zoomVal);
          gmap.setMapType(G_NORMAL_MAP);
          var markerOptions = {icon:blueIcon};
          var objMarker = new GMarker(new GLatLng(aDealers[0].lat, aDealers[0].lng), markerOptions);
          gmap.addOverlay(objMarker);
        }
      }
    }
    else{
      //window.status ="No gmap layer found"
    }
  }
  
  // restore user panning/zooming
  if(bIsPrintable){
    if(window.opener){
      if(window.opener.gmap){
        gmap.setCenter(window.opener.gmap.getCenter())
        gmap.setZoom(window.opener.gmap.getZoom())
      }
    }
  }
}

function callBackGetLocation(response){
  var point, place
  if(!response || response.Status.code != 200){
    var objSearchForm = document.forms["dealerSearchForm"]
    //alert("Sorry, we were unable to geocode that address");
    objSearchForm["postalCoordLat"].value="N/A";
    objSearchForm["postalCoordLng"].value="N/A";
    objSearchForm.submit();
    
    return;
  } 
  else{
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
    
    if(document.forms["dealerSearchForm"]){
      var objSearchForm = document.forms["dealerSearchForm"]
      objSearchForm["postalCoordLat"].value=point.lat();
      objSearchForm["postalCoordLng"].value=point.lng();
      objSearchForm.submit();
    }
    else{
      var bIcon = new GIcon(G_DEFAULT_ICON);
      bIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";                
      var markerOptions = { icon:bIcon};      
      var objMarker = new GMarker(point, markerOptions);
      gmap.addOverlay(objMarker);
      objMarker.openInfoWindowHtml(place.address + '<br>' + '<b></b> ' + place.AddressDetails.Country.CountryNameCode);
    }
  }
}

function getLocation(strPostCodeAndOrCity, strCountryCode){
  //alert(strPostCodeAndOrCity + " " + strCountryCode)
  /*
  This method performs a geocode, the conversion of a human-readable address into a latitude/longitude pair. 
  getLocations() sends a request to the Google geocoding service, asking it to parse the given address and 
  handle the response in the given callback.

  As this method requires a call to a Google server, you must also pass a callback method to handle the response. 
  This response will contain a Status code, and if successful, one or more Placemark objects.   
  */
  geocoder = new GClientGeocoder();
  geocoder.getLocations(strPostCodeAndOrCity + "," + strCountryCode , callBackGetLocation);
}

function DealerInfo(id, name, city, lat, lng){
  this.id = id;
  this.name = name;
  this.city = city;
  this.lng = lng;  
  this.lat = lat;
}

function addDealerToList(id, name, city, lat, lng){
  aDealers[aDealers.length] = new DealerInfo(id, name, city, lat, lng)
}

/*

*/
function placeLocations(){
  var i;
  var point;  
  for(i=0;i<aDealers.length;i++){
    var strTitle = aDealers[i].name + " (" + aDealers[i].city  + ")"
    var strID = aDealers[i].id
    var markerOptions = { title:strTitle,icon:blueIcon, id:strID};
    var objMarker = new GMarker(new GLatLng(aDealers[i].lat, aDealers[i].lng), markerOptions);
    GEvent.addListener(objMarker, "click", markerClick);
    gmap.addOverlay(objMarker);
  }
}

/*
  2008-02-26 Ola Ljungars: Added refocus of the popUp
*/
var gObjDealerPopUp = null;
function openDealerPopUp(strID){
  var url = strGetDealerURL + "?dealerid=" + strID;
  
  if(gObjDealerPopUp!=null){  // the window is previously created
    if(!gObjDealerPopUp.closed){
      gObjDealerPopUp.focus();
      gObjDealerPopUp.location = url;
    }
    else{
      gObjDealerPopUp = window.open(url,'DotComRedirectPopUp','width=544,height=600,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes');
    }
  }
  else{
    gObjDealerPopUp = window.open(url,'DotComRedirectPopUp','width=544,height=600,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes');
  }
}
function markerClick(){
  //openDealerPopUp(this.id)
  location.href = strGetDealerURL + "?actionID=GetDealer&CountryDealerID=" + this.id;
}

function placeLocation(){
  return;
}

function GM_submitSearchForm(objForm){
  var bReturn;

  objForm["GEOErrorMessage"].value = "";
  objForm["postalCoordLat"].value = "";
  objForm["postalCoordLng"].value = "";
  objForm["countryName"].value = objForm["countryCode"].options[objForm["countryCode"].options.selectedIndex].text;
  
  // GM Geo Support is enabled
  if(!objForm["city"]!= ""){
    var objAddress = objForm["address"];
    var objDistance = objForm["distance"];
    
    if(objAddress.value !=""){
      var objErrNumericDiv = document.getElementById("errNumericValue");
      var objDistanceInput = document.getElementById("distance");
      var objDistanceLabel = document.getElementById("lblDistance");
    
      if(isNaN(objDistance.value) || objDistance.value == ""){
        objErrNumericDiv.style.display = "block";
        objDistanceLabel.className = "error";
        objDistanceInput.className = "text error";
        return false;
      }
      else{
        if(objErrNumericDiv!=null) objErrNumericDiv.style.display = "none";
        objDistanceLabel.className = "";
        objDistanceInput.className = "text";
      }
      getLocation(objForm.address.value, objForm.countryCode.value); // form is submitted in callback function
    }
    else{
      objForm.submit();
      return true;
    }

  }
  else{
    objForm.submit();
    return true;
  }
}

function submitOnEnter(e, objForm){
  var evt = e || event;
  if(event.keyCode == "13") GM_submitSearchForm(objForm);
}

/*
  This function is here to avoid js errors 
  (since it is called on every page for some unknown reason), 
*/
function CMap24RenderMap(mid,sid,imgid){
  ; // do Nothing
}

function toggleDealerServicesTable(){
  var objTable = document.getElementById("dealerServicesTable")
  if(objTable.style.display=="none"){
    objTable.style.display = "block"
  }
  else{
    objTable.style.display = "none"
  }
}

/******************************************************************************
  NAME:
    expandInfo(strDivName)
  DESCRIPTION:
    Shows/hides the div (used vehicles details)
******************************************************************************/
function expandInfo(strDivName, strArrowDown, strArrowRight){
  var iLayerIndex = strDivName.substr(strDivName.length-1, strDivName.length);
  var objDiv = document.getElementById(strDivName)
  var objExpanderImg = document.getElementById("expander" + iLayerIndex )

  if(objDiv.style.display == "block"){
    objDiv.style.display = "none"
    objExpanderImg.src = strArrowRight;
  }
  else{
    objDiv.style.display = "block"
    objExpanderImg.src = strArrowDown;
  }
}

/*
  Submit and optional to change a value in the form
  strFieldName is the name of the value to change, strFieldValue is.. go figure..
*/
function submitForm(strFormName, strFieldName, strFieldValue){
  //alert(strFormName + " " + strFieldName + " " + strFieldValue);
  if(strFieldName!="") {
    document.forms[strFormName][strFieldName].value = strFieldValue;
  }
  document.forms[strFormName].submit();
}

function submitMapOfAll(strFormName){
  var objForm = document.forms[strFormName];
  if(objForm["searchresoption"]) objForm["searchresoption"].value="map";
  if(objForm["postalCoordLat"]) objForm["postalCoordLat"].value="";
  if(objForm["postalCoordLng"]) objForm["postalCoordLng"].value="";
  if(objForm["service"]) objForm["service"].value="";
  if(objForm["dealername"]) objForm["dealername"].value="";
  if(objForm["city"]) objForm["city"].value="";
  if(objForm["address"]) objForm["address"].value="";
  
  objForm.submit();
}

function setMapMode(MapMode){
  gmap.setMapType(MapMode);

  if(MapMode == G_HYBRID_MAP){
    document.getElementById("mapModeNormal").style.display = "none"
    document.getElementById("mapModeSatelite").style.display = "block"
  }
  else{
    document.getElementById("mapModeNormal").style.display = "block"
    document.getElementById("mapModeSatelite").style.display = "none"
  }
}

function pan(){
  gmap.panBy(new GSize(0, 10));
}


function openPrintVersion(){
  window.open("/inc/printVersion.asp","printversion","width=700,height=550,scrollbars=yes");
}

function printMapResults(strURL){
  window.open(strURL,"mapprintversion","width=700,height=550,scrollbars=yes");
}

function toggleSearchForm(objHref, isMaximized){
  
  var objShowSearchForm = document.getElementById("dealerShowSearchForm");
  var objSearchFormLI = document.getElementById("dealerSearchFormLI");
  
  if(isMaximized){
 
    objShowSearchForm.className = objShowSearchForm.className.replace("hidden", "visible_block");
    objSearchFormLI.className = objSearchFormLI.className.replace("visible_block", "hidden");
      
  }
  else{
 
    objShowSearchForm.className = objShowSearchForm.className.replace("visible_block", "hidden");
    objSearchFormLI.className = objSearchFormLI.className.replace("hidden", "visible_block");
    
  }
  
}


function findChildNode(objParent, strChildClassName){
	for(i=0;i<objParent.childNodes.length;i++){
		if(objParent.childNodes[i].className == strChildClassName) return objParent.childNodes[i];
	}
	return null;
}

/*
	

*/

function largeMap(){
	
	// ctl00_ctl05_lblPrint
	
	showL("downloadImages");
	var objDownloadImages = document.getElementById("downloadImages");
	var objIFrameHolder = findChildNode(objDownloadImages, "iframholder");
	var strPrintLayer = "<div id=\"layer-print\"><a href=\"#\" onclick=\"window.print();return false;\"><span class=\"icon-print\"></span>"+document.getElementById("ctl00_ctl05_lblPrint").innerHTML.toLocaleUpperCase()+"</a></div>";
	objIFrameHolder.innerHTML = strPrintLayer + objIFrameHolder.innerHTML;

	
	var objDownloadImages2 = findChildNode(objIFrameHolder, "downloadImages");
	objDownloadImages2.innerHTML = "";
	var objDivDisclaimer = document.getElementById("divDisclaimer");
	objDivDisclaimer.innerHTML = "";
	
	objDownloadImages2.id = "GoogleMapLarge";
	
	objDownloadImages2.style.width = "580px";	
	objDownloadImages2.style.height = "700px";
	objDownloadImages2.style.top="33px";
	
	
	objIFrameHolder.style.width="580px";				
	objIFrameHolder.style.height="763px";				

	objDownloadImages.style.paddingTop = 0;
	objIFrameHolder.style.top = "40px"
	
	GMInit("GoogleMapLarge", false);
	window.scrollTo(0,0);
}
