﻿// JScript File
//google.load("maps", "2.x");  
// Call this function when the page has been loaded  
var map = null;        
var geocoder = null;
var baseIcon = null;
var mgr = null;
var bounds;
var showLocationWhere = null;
var showLocationPage = null;
var showLocationSetBounds = null;
var showLocationFired = false;
var pageSetCountryCode = "";
var destinationFlagZoomLevel = 4; // The minimum zoom to display destination flags
var defaultZoom = 5; // Default zoom for the map
var searchZoom = 7; // Default zoom after a search
var tabWidth = 450; // width in pixels of google Info window. Overridden in code.
var mapTypeButtonLocation = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(70, 8)); // Position of map type selector buttons
var searchResultMarkerDistance = 25000; //If a marker is found within this distance (in meters) from the searched point, it's window will appear
var markerList = [];

function initialize() {    
    if (!GBrowserIsCompatible()) 
    { 
        alert("Sorry, the Google Maps API is not compatible with this browser");
        return;
    }
    map = new GMap2(document.getElementById("map")); 
    // UK - zoom level is last param
    map.setCenter(new GLatLng(52.980, -1.680), defaultZoom);    
    map.addControl(new GLargeMapControl());

    // Buttons for type of map moved to bottom right to allow space for pop ups.
    map.addControl(new GMapTypeControl(), mapTypeButtonLocation);
    
    map.addControl(new GOverviewMapControl()); 
    //map.enableScrollWheelZoom();
    geocoder = new GClientGeocoder(); 
    
    if(pageSetCountryCode != null && pageSetCountryCode != "") geocoder.setBaseCountryCode(pageSetCountryCode);                
    // Marker manager allows you to group markers - code.googlemaps.com - maxzoom might need to be higher to get them to appear eaiser
    var mgrOptions = {maxZoom:15, trackMarkers:false };
    mgr = new MarkerManager(map);
                
    baseIcon = new GIcon();
    baseIcon.shadow = "shadow.png";
    baseIcon.iconSize = new GSize(24, 31);
    baseIcon.shadowSize = new GSize(40, 31);
    baseIcon.iconAnchor = new GPoint(12, 15);
    baseIcon.infoWindowAnchor = new GPoint(12, 15);
    
    var info = "<div style='width:240px;' class='mapInfo'><img src='images/loading.gif' /><br /><h2>Loading</h2>";
    info += "<p>Please wait...</p></div>";
    map.openInfoWindowHtml(map.getCenter(), info);
    SetDestinationMarkers();
}  

function createDestinationMarker(point, destid, destname) 
{
        var markerIcon = new GIcon(baseIcon);
        markerIcon.image = "images/pin1.png";
        markerOptions = { icon:markerIcon, title:destname}; 
        var marker = new GMarker(point, markerOptions);
        
       GEvent.addListener(marker, "click", function() {
                                                        createClimateGuideDetails(destid, marker, destname, point);
                                                    }
                            );

         /*GEvent.addListener(marker, "click", function() {setTimeout("map.setCenter(point)",1250);setTimeout("map.panBy(new GSize(0, 150))",1250);setTimeout("createClimateGuideDetails(destid, marker, destname, point)",1250);});
        //map.setCenter(point);}); */
        
        var markerInfo = marker;
        markerInfo.destid = destid; 
        markerInfo.destname = destname;
        markerInfo.point = point;
        markerList.push(markerInfo);
        return marker;
       
}

// Gets markers for a country when that country is clicked.
function SetDestinationMarkers()
{
// intiialise current marker list 
    markerList = [];
    GDownloadUrl("GoogleDestinationMarkers.aspx", function(data, responseCode) 
                                                               {  
                                                                var xml = GXml.parse(data);  
                                                                var destinations = xml.documentElement.getElementsByTagName("DestinationSummary");         
                                                                var batch = [];
                                                                var i = 0;
                                                                var tabContent = "";
                                                                var tabTitle = "";
                                                                var point;
                                                                for (i = 0; i < destinations.length; i++)
                                                                 {   
                                                                //get values
                                                                var destNode = destinations[i];
                                                                var destid = getContent(destNode.getElementsByTagName("destid")[0]);
                                                                var destName = trim10(getContent(destNode.getElementsByTagName("destname")[0]));
                                                                var Longitude = getContent(destNode.getElementsByTagName("longitude")[0]);
                                                                var Latitude = getContent(destNode.getElementsByTagName("latitude")[0]);

                                                                batch.push(createDestinationMarker(new GLatLng(Latitude, Longitude), destid, destName));
                                                                
                                                                }
                                                                
        if(batch.length > 0)
        {
        mgr.addMarkers(batch, destinationFlagZoomLevel);
        mgr.refresh();
        }
      
        map.closeInfoWindow();
            var addr = getParameter ("loc");
    if (trim10(addr) != "" && addr != null && addr != "null")
    {
    showLocationFromUrl(1, true, true, addr) 
    }

    }
  )
}

function wait(msecs)
{
var start = new Date().getTime();
var cur = start
while(cur - start < msecs)
{
cur = new Date().getTime();
} 
} 

function mapReCentreForInfoWindow(point)
{
   map.setCenter(point);
   map.panBy(new GSize(0, 150));
}

// Call the page to gt the climate guide info to display when the marker is clicked.
//function createClimateGuideDetails(destid, marker, destname, point)
//{
//        mapReCentreForInfoWindow(point);
////open tabs
//var tabs = [];
//GDownloadUrl("GoogleDestinationClimateGuide.aspx?destid=" + destid, 
//                function(data, responseCode) {  
//                                                var xml = GXml.parse(data); 
//                                                //var destinations = xml.documentElement.getElementsByTagName("Destinations"); 
//                                                var destNode = xml.documentElement; 
//                                                var batch = [];
//                                                var i = 0;
//                                                var tabArray = [];
//                                                var tabContent = "";
//                                                var tabTitle = "";
//                                                
//                                                var tabWidth = "600px";
//                                                var infoLink = "<input id='hfSelectedAlready"  + destid +  "' style='display:none;'></input>";
//                                                infoLink += "<div class='climateLinks' id='linkDiv" + destid + "'>";
//                                                infoLink += "<a class='selected' id='climateLink" + destid + "' onclick='viewClimate(" + destid + ")'>Climate</a>&nbsp;";
//                                                infoLink += "<a class='deselected' id='weatherLink" + destid + "' onclick='viewWeather(" + destid + ")'>Weather</a></div>";
//                                                
//                                                // Get the climate guide for that destination and apply it to the appropriate tab.
//                                                destname = trim10 (getContent(destNode.getElementsByTagName("destname")[0]));
//                                                var weatherGuide = getContent(destNode.getElementsByTagName("fullClimateGuide")[0]);
//                                                
//                                                // temp div for weather
//                                                var infoStart = "<div class='mapInfo'><h2>" + destname + "</h2>";
//                                                var infoEnd = "</div>";
//                                                var weatherTemp = "<div id='weatherDiv" + destid + "' style='display:none;' class='mapInfo'><img src='images/loading.gif' alt='loading' /><br /><h2>Loading</h2>";
//                                                  weatherTemp += "<p>Please wait...</p></div>";
//                                                
//                                                // Climate guide
//                                                tabArray.push(infoStart + weatherGuide + infoEnd);
//                                                // Weather forecast
//                                                tabArray.push(weatherTemp);
//                                                htmls = tabArray;
//                                                
//                                                if(htmls != null)
//                                                {
//                                                        htmls[0] = "<div id='climateDiv" + destid + "' style='width:" + tabWidth + "'>" + htmls[0] + '</div>';
//                                                        marker.openInfoWindowHtml(infoLink + htmls[0] + htmls[1]);
//                                                }
//                                          }
//            );

//       createWeatherReport (destid, marker, destname, point);
//     }


function createClimateGuideDetails(destid, marker, destname, point)
{
    //    mapReCentreForInfoWindow(point);
//open tabs
var tabs = [];
GDownloadUrl("GoogleDestinationClimateGuide.aspx?destid=" + destid, 
                function(data, responseCode) {  
                                                
                                                var tabs = data.split("¬")
                                                var xml = GXml.parse(tabs[0]); 
                                                //var destinations = xml.documentElement.getElementsByTagName("Destinations"); 
                                                var destNode = xml.documentElement; 
                                                var batch = [];
                                                var i = 0;
                                                var tabArray = [];
                                                var tabContent = "";
                                                var tabTitle = "";
                                                
                                                var tabWidth = "600px";
                                                var infoLink = "<input id='hfSelectedAlready"  + destid +  "' style='display:none;'></input>";
                                                infoLink += "<div class='climateLinks' id='linkDiv" + destid + "'>";
                                                infoLink += "<a class='selected' id='climateLink" + destid + "' onclick='viewClimate(" + destid + ")'>Climate guide</a>&nbsp;";
                                                infoLink += "<a class='deselected' id='weatherLink" + destid + "' onclick='viewWeather(" + destid + ")'>Current weather</a></div>";
                                                
                                                // Get the climate guide for that destination and apply it to the appropriate tab.
                                                destname = trim10 (getContent(destNode.getElementsByTagName("destname")[0]));
                                                var weatherGuide = getContent(destNode.getElementsByTagName("fullClimateGuide")[0]);
                                                
                                                // temp div for weather
                                                var infoStart = "<div class='mapInfo'><h2>" + destname + "</h2>";
                                                var infoEnd = "</div>";
                                                                                            
                                                var weatherNow = "<div id='weatherDiv" + destid + "' style='display:none;' class='mapInfo'>";
                                                weatherNow += "<div style='width:" + tabWidth + "px;' class='mapInfo'><h2>" + destname + "</h2>";
                                                weatherNow += tabs[1] + "</div></div>";
                                                
                                                // Climate guide
                                                tabArray.push(infoStart + weatherGuide + infoEnd);
                                                // Weather forecast
                                                tabArray.push(weatherNow);
                                                htmls = tabArray;
                                                
                                                if(htmls != null)
                                                {
                                                        htmls[0] = "<div id='climateDiv" + destid + "' style='width:" + tabWidth + "'>" + htmls[0] + '</div>';
                                                        marker.openInfoWindowHtml(infoLink + htmls[0] + htmls[1]);
                                                }
                                          }
            );

       //createWeatherReport (destid, marker, destname, point);
     }

function createWeatherReport (destid, marker, destName, point)
{
GDownloadUrl("DestinationWeatherReport.aspx?destid=" + destid, 
            function(data, responseCode) {  
                                            var infoStart = "<div style='width:" + tabWidth + "px;' class='mapInfo'><h2>" + destName + "</h2>";
                                            var html = infoStart + data + "</div>";
                                            var tabDiv = document.getElementById("weatherDiv" + destid);
                                            if (tabDiv != null)
                                            {
                                            tabDiv.innerHTML = html;
                                            }
                                           }
             );
}

// Call log when the current weather report is clicked if it hasn't already been logged.
function viewWeather(destid)
{   // Check whether it's the first time the tab has been selected.
    // If so, log the click to the database and update the hidden field to say that that tab has already been clicked on.
    var weatherDiv = document.getElementById("weatherDiv" + destid);
    var climateDiv = document.getElementById("climateDiv" + destid);
    climateDiv.style.display="none";
    weatherDiv.style.display="inline";
    
    // Set the links classes
    var climateLink = document.getElementById("climateLink" + destid);
    var weatherLink = document.getElementById("weatherLink" + destid);
    climateLink.className = "deselected";
    weatherLink.className = "selected";
    
    var logged = document.getElementById("hfSelectedAlready" + destid);
    
    if (logged.value != "true")
    {
    GDownloadUrl("CurrentWeatherClickLog.aspx?destid=" + destid, null);
    // Set flag to indicate this is already logged.
    logged.value = "true";
    }
 
    climateDiv.style.display="none";
    weatherDiv.style.display="inline";
}

function viewClimate(destid)
{
    var weatherDiv = document.getElementById("weatherDiv" + destid);
    var climateDiv = document.getElementById("climateDiv" + destid);
    
    climateDiv.style.display="inline";
    weatherDiv.style.display="none";
        
        // Set the links classes
    var climateLink = document.getElementById("climateLink" + destid);
    var weatherLink = document.getElementById("weatherLink" + destid);
    climateLink.className = "selected";
    weatherLink.className = "deselected";
}


function getContent(xmlNode)
{
    if(!xmlNode) return '';
    if(typeof(xmlNode.textContent) != "undefined") return xmlNode.textContent;
    return xmlNode.firstChild.nodeValue;
}


function trim10 (str) {
	var whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
	for (var i = 0; i < str.length; i++) {
		if (whitespace.indexOf(str.charAt(i)) === -1) {
			str = str.substring(i);
			break;
		}
	}
	for (i = str.length - 1; i >= 0; i--) {
		if (whitespace.indexOf(str.charAt(i)) === -1) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

//Added by PETE

// 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) 
{         
    // Close the currently open info window
    map.closeInfoWindow();

  if (!response || response.Status.code != 200) {
    map.openInfoWindow(map.getCenter(), document.createTextNode("Sorry, we were unable to geocode that address"));
  } else 
    {
    place = response.Placemark[0];
    var level = 8 + place.AddressDetails.Accuracy;
    if(level > 16) level = 16;
    
    point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
    map.setCenter(point, level);
    map.setZoom(searchZoom);

    var found = false;        
    // If a marker already exists at that point, display its bubble.
    for (var j=0; j<markerList.length; j++) 
        {
        var mkr = markerList[j];
        var markerPoint = mkr.point;
    
        if (markerPoint.distanceFrom(point) <=  searchResultMarkerDistance)
            {
            createClimateGuideDetails(mkr.destid, mkr, mkr.destname, markerPoint)
            found = true;
            break;
            }
        }
        if (!found) {alert("No information found for this location. Please click the nearby pins to retrieve climate information."); }
    }
}

// showLocation() is called when you click on the Search button
// in the form.  It geocodes the address entered into the form
// and adds a marker to the map at that location.
function showLocation(page, map, setBounds) 
{        
    var address = document.getElementById("txtSearch").value;
    if(map && trim10(address) != "") geocoder.getLocations(address, addAddressToMap);
}


function showLocationFromUrl(page, map, setBounds, addr) 
{        
    if(map && trim10(addr) != "") geocoder.getLocations(addr, addAddressToMap);
}



// findLocation() is used to enter the sample addresses into the form.
function findLocation(address) {
  document.forms[0].q.value = address;
  showLocation(1, true, true);
}

// Get query string values
function getParameter( parameterName ) {
  var queryString = window.location.search.substring(1).toLowerCase();
  //alert(queryString);
  //if (queryString.length==0) {return "null";}
  var parameters = new Array();
  parameters = queryString.split('&');
  for(var i = 0; i < parameters.length; i++) {
    //alert(parameters[i]);
    //alert(parameters[i].indexOf(parameterName));
    if (parameters[i].indexOf(parameterName.toLowerCase())>=0) {
      //alert(parameters[i]);
      var parameterValue = new Array();
      parameterValue = parameters[i].split('=');
      return parameterValue[1];
    }
  }
  return "null";
}

var ModuleId = getParameter('ModuleId');
