/*Google maps / traffic feed */
//VARS


// global "map" variable
var mapGoogle;
var gMarkers = [];
var placeElements = [];	
var htmlMarkers = [];
var routeOverlay;
var gdir;

//gaz search vars
var ajaxRequest = getXMLHttpRequest();
var output = new Array();
var error;
var containsError = false;
var database="B"; //default to UK
var errorCol = "#fe8600";
var isNewSearchValue=false;

//traffic vars
var delayZoomThreshold=7; //inclusive
var delayZoomThresholdMin=12; //inclusive
var delayValueThreshold=15; //mins
var delayValueThresholdMin=10; //mins
var delayValueAbsoluteMin=2; //mins
var minLaneClosureLevel=5;
var AATraffic="/aaservlet/traffic";
var errorDivID="#errorMsg";
var trafficDateDivID="#dateTraffic";
var aaMapPage='trafficnews';
var alertCallTimer=0;
var ttTileLayerOverlay;

var metresToKilometres = 1000;
var metresToMiles = 1609.344;
var distanceConversion = metresToKilometres;	// Default to km
var loadingImageURI = "/images/routes/ajax-loader.gif";

var latlngScrollRequests=true;


// ====== Array for decoding the Google failure codes ======
var reasons=[];
reasons[G_GEO_SUCCESS]            = "Success";
reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
reasons[G_GEO_UNKNOWN_DIRECTIONS] = "Unable to generate route between specified locations.";



//FUNCTIONS

	
$(document).ready(function() {				   

	$("#searchPlace").keypress(searchFieldKeypress);
			
	$("#searchPlace").click(function () { 
		$(this).removeAttr("style").removeClass("inputSpinner").removeClass("alertError"); 
	});
		
		
  //capture onchange input events
	$("#searchPlace").bind( "change keyup", function(event) {
		var $tgt=$(event.target);
		if($tgt.is('input')&&($tgt.hasClass("routeText")))
		{
			var keycode=event.which;
			//not for return, tab or shift
			if(keycode!=undefined && keycode!=13 && keycode!=9 && keycode!=16)
			{
				setWhiteBG($tgt[0]);
				isNewSearchValue=true;
			}
				
		}
	});
	

var ttMapType;
var mapProjection;

if (GBrowserIsCompatible()) { 


    // TTLayer[1] = new GTileLayer(new GCopyrightCollection('') , 5, 17);
	//TTLayer[1].getCopyright = function(a,b) { return "&#169; Copyright TomTom HD";}; 
	var ttCopyright=new GCopyrightCollection("&#169; ");
	ttCopyright.addCopyright(new GCopyright('TomTomCopyright',new GLatLngBounds(new GLatLng(-90,-180), new GLatLng(90,180)),
  5,'Copyright TomTom HD'));

	
	ttTileLayerOverlay = new GTileLayerOverlay(
		  new GTileLayer(ttCopyright, 5, 17, {
			tileUrlTemplate: 'http://lbs.tomtom.com/lbs/map/1/traffic/{Z}/{X}/{Y}/ecc48791-db52-4ab1-84bb-f183037a1fbb;s=s2;',
			isPng:true,
			opacity:1.0
		  })
		);

	// Display the map, with our selection of map types
	mapGoogle = new GMap2(document.getElementById("map"), {mapTypes:[G_NORMAL_MAP,G_SATELLITE_MAP,G_PHYSICAL_MAP]});
	mapGoogle.addControl(new GLargeMapControl3D());
	mapGoogle.addControl(new GScaleControl());

	mapGoogle.addControl(new GMapTypeControl());
	
	mapGoogle.setCenter(new GLatLng(54.522005, -3.083582), 5);
	mapGoogle.addOverlay(ttTileLayerOverlay);
	mapGoogle.enableScrollWheelZoom();

		var overlayMapAd= document.getElementById("overlayMapAd");
		if (overlayMapAd != null) {
			var pos = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(0,0));
			pos.apply(overlayMapAd);
			mapGoogle.getContainer().appendChild(overlayMapAd); 
			overlayMapAd.style.display='block';
		}	  
		
		var overlayMapMessage= document.getElementById("overlayMapMessage");
		if (overlayMapMessage != null) {
			var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0,0));
			pos.apply(overlayMapMessage);
			mapGoogle.getContainer().appendChild(overlayMapMessage); 
		}	 
		
		var sidebarSlider=document.getElementById("sidebarSlider");
		if(sidebarSlider!=null)
		{

			var pos=new GControlPosition(G_ANCHOR_BOTTOM_LEFT,new GSize(0,40));
			pos.apply(sidebarSlider);
			mapGoogle.getContainer().appendChild(sidebarSlider);
			sidebarSlider.style.display='block';
		}

	
	//initialize
	clearAndReloadTraffic(AATraffic,mapGoogle);

	GEvent.addListener(mapGoogle,"zoomend",zoomTraffic);
	GEvent.addListener(mapGoogle,"dragend",moveTraffic);
    }
    // display a warning if the browser was not compatible with GMAPS
    else {
      
    }
	
	$("#toggleKey").bind("click",function(){
			var isKeyVisible=$(".toggleKeyOff").css("display");
			if(isKeyVisible=="block")
			{
				$(".toggleKeyOff").slideUp('fast',function(){
					$("#toggleKey span").text("Show more");
					$("#toggleKey a").css("background-image","url(/images/traffic/yellow-square-arrow-down.gif)");
				});
			}
			else {
				$(".toggleKeyOff").slideDown('fast',function(){
					$("#toggleKey span").text("Hide");
					$("#toggleKey a").css("background-image","url(/images/traffic/yellow-square-arrow-up.gif)");
				});
			}

	});
	
	/*header footer*/
	initHeaderFooter();
	
}); //end document ready


$(document).unload(GUnload);

function initHeaderFooter()
{
	var mouse_is_inside = false;
	 /**********************************
	 ** TEXT INPUTS FOCUS IN AND OUT
	 *********************************/
	 $("#footer input[type=text]").each(function(){
		var textBoxTitle = $(this).attr("value");
		$(this).focus(function(){
			if(textBoxTitle == $(this).attr("value"))
			{
				
				if(! mouse_is_inside){
				$(this).attr("value", "");
				mouse_is_inside = true;
				}
			}
		});
		
		$(this).blur(function(){
			mouse_is_inside = false;
			if($(this).attr("value") == "")
			{
				$(this).attr("value", "");
			}
		});
	});
}

function clearAndReloadTraffic(url,map)
{
	//default to alerts only
	var isAlertTicked=false;
	if($("#dispTrafficAlert").is(':checked')) {isAlertTicked=true;}
	var isRoadworkTicked=false;
	if($("#dispRoadworks").is(':checked')) {isRoadworkTicked=true;}
	
	var alertType='';
	
	//select alert type from customer inputs
	if(!isRoadworkTicked && !isAlertTicked)
	{
		return;
	}
	if (isRoadworkTicked && !isAlertTicked)
	{
		alertType='roadworks';
	}
	else if(isAlertTicked && !isRoadworkTicked)
	{
		alertType='delays';
	}
	

	
	displayTrafficAlertOverlay(map,true,'overlayMapMessage',alertType);
}
	


//set zoom and extents
function setMapExtentsByRegion(lat,lon,zoom)
{
	 mapGoogle.setCenter(new GLatLng(lat, lon), zoom);
}

function setMapLocation(area)
{
	
  //clear overlays
	$searchPlace=$("#searchPlace");
	$confirmPlace=$("#confirmPlace");
	resetMap();
	doGazSearch();
	fetchDestinationSensitiveAds(false);

}




//gaz search functions

function getNewValues(thePlace) {
  output.length = 0;
  params = "place="+escape(thePlace)+"&amp;database="+database;
  var ie7 = (document.all && !window.opera && window.XMLHttpRequest) ? true : false;
  if (ajaxRequest!=null){
	ajaxRequest.open("POST", "/aaservlet/PopulateGazList", false);
	ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	ajaxRequest.setRequestHeader("Content-length", params.length);
	ajaxRequest.setRequestHeader("Connection", "close");
	if (window.XMLHttpRequest){
	   if(ie7)
	   {
		  ajaxRequest.onreadystatechange= function(){updateValues();};
		  ajaxRequest.send(params);
	   }
	   else
	   {
		  ajaxRequest.send(params);
		  ajaxRequest.onreadystatechange= updateValues();
	   }
	} else {
	   ajaxRequest.onreadystatechange= function(){updateValues();};
	   ajaxRequest.send(params);
	}
 }

}

function updateValues() {

		containsError = false;
		error="";

		if (ajaxRequest!=null && ajaxRequest.readyState==4)
		{
			if (ajaxRequest.status == 200){
				
				var result = eval("("+ajaxRequest.responseText+")");
				if(result.errors.length > 0)
				{
					error = result.errors;
					containsError = true;
				}
				else
				{
					for (i=0; i < result.placeResults.length; i++)
					{
						var entry = new Array();
						//each entry as a display and value
						entry[0] = result.placeResults[i][0];
						entry[1] = result.placeResults[i][1];
						output[i] = entry;
					}
				}
			}
			if(ajaxRequest.status!=200)
			{
				//error getting reponse	
				
				$(errorDivID).html("<p class='error'>Sorry, there was a problem finding your location. Please try again later.</p>");
				hideLoading();
			}
		}
}

function setDatabase(db){ database=db; }
function getDatabase(){ return database }
function getResults(){ return output; }
function hasError(){
	return containsError;
}

function getError(){
	if(error=="findSearchResult Gazetteeer service is disabled")
	{
		error="Search currently unavailable";
	}
return error;
}



//taken from route-gaz.js
function doGazSearch()
{

	processingError=false; // reset

	$("#" + $confirmPlace.attr("id") + "Matches").html(); //hide matches
	
	//display loading gif
	showLoading();
	
	// search from and to
	if(isNewSearchValue&&searchPlace($searchPlace))
	{
		//update values
		populateField($confirmPlace,$searchPlace);
	}
	goToGazResult();
	hideLoading();
}


function goToAndShowMarker()
{
//check for float
  var inpLat=parseFloat($("#inpLat").val()) || null;
  var inpLon=parseFloat($("#inpLon").val()) || 13;
  var inpZoom=parseInt($("#inpZoom").val()) || null;
  var inpPOIid=parseInt($("#inpPOIid").val()) || null;
  var inpPOIType=$("#inpPOIType").val()||null;
  var inpPOIName=$("#inpPoiName").val()||'';
  
  if(inpZoom>17||inpZoom<0) inpZoom=13;
  //if got a POIID then do lookup and show on map
    
    if(inpLat!=null&&inpLon!=null)
    {

      if(inpPOIid!=null&&inpPOIType!=null)
      {
        var poiTypeID=getPOIIDFromType(inpPOIType);
        //get poitype and name
       showSinglePOI(mapGoogle,inpLat,inpLon,inpPOIid,poiTypeID,true,true,inpPOIName);

      }
      else {
          var newGLocation=new GLatLng(inpLat, inpLon);
          mapGoogle.setCenter(newGLocation, inpZoom);
          addLocationMarker(mapGoogle,newGLocation,'');
        }
    }
  
  //now clear inputs
  $("inpLat").attr("value",'');
  $("inpLon").attr("value",'');
  
  //reloadTraffic
  setTimerClearAndReloadTraffic(AATraffic,mapGoogle);
}


function searchPlace($searchField)
{
	//set background spinner
	//$searchField.css({'background-image':'url(/images/routes/ajax-spinner-white-16.gif)','background-repeat':'no-repeat','background-position':'98% 50%'});
	
	$("#confirmPlaceMatches").html("").hide();

	getNewValues($searchField.val());

	if(hasError())
	{
		$searchField.val(getError()).focus();
		setErrorBG($searchField[0]);
		hideLoading();
		processingError=true;
		return false;
	} else {
		// clear any error colours
		setWhiteBG($searchField[0]);
		hideLoading();
	}
	//return boolean if search ok
	return true;
}


function goToGazResult()
{
	if(!processingError)
	{
		if(isNewSearchValue)
		{
			var res = getResults();
			var resOutput=res[0][1];
			var gazOutput=resOutput.split("|");
		}
		else {
			var gazOutput=$("#confirmPlace").val().split("|");
		}
		var placeName=gazOutput[1];
		var placeEasting=gazOutput[3];
		var placeNorthing=gazOutput[4];
	
		var geo=ConvertBNGtoWGS84(placeEasting,placeNorthing);
		var newGLocation=new GLatLng(geo.latitude, geo.longitude)
		mapGoogle.setCenter(newGLocation, 13);
		 
		//and zoom to...
		addLocationMarker(mapGoogle,newGLocation,placeName);
		
		setTimerClearAndReloadTraffic(AATraffic,mapGoogle);
	}
}


function populateField($resField,$inpField)
{
	//set background color of inputs to white
	
	//setWhiteBG($("#" + inpField.id);

	var res = getResults();
	
	
	var strMatchSummary="";
	var strSelectHTML="";
	var strPlace="";
	var $tmpMatchElem=$("#" + $resField.attr("id") + "Matches");
	$tmpMatchElem.html("").hide();
	
	
	var strHTMLPlace="";
	for(cnt = 0; cnt < res.length; cnt++)
	{
		//var optn = new Option();
		//optn.text = res[cnt][0];
		//optn.value = res[cnt][1];
		
		//set display and hidden input
		if(cnt==0) {
			$inpField.val(res[cnt][0]);
			$resField.val(res[cnt][1]);
		}
		
		strPlace=new String(res[cnt][0]);
		if(strPlace.length>34)
		{
			strPlace=strPlace.slice(0,31) + "...";
		}
		
		strHTMLPlace=res[cnt][1].replace(/'/g,'&#8217;');
		strSelectHTML+="\n<div class='matchplace' node='" + strHTMLPlace + "'><a href='#' onclick=" + '"selectNodeMatch(' + "'" + strHTMLPlace + "','" + $resField.attr("id") + "','" + $inpField.attr("id") + "');return false;" + '">' + strPlace + "</a></div>";

	}

	//show if more than 1 match
	if(cnt>1) {
    strMatchSummary=cnt + " matches";
    strMatchSummary+=" found -  <a href='#' id='linkToggle" + $resField.attr("id") + "' onclick=" + '"toggleMatchList(this,' + "'" + $resField.attr("id") + "-list');return false;" + '"' + ">select from list</a>";
    strSelectHTML="<div id='" + $resField.attr("id") + "-list' class='matchWrapper'>" + strSelectHTML + "</div>";
	$tmpMatchElem.html(strMatchSummary + strSelectHTML).show();
	}	
	
	//set true/false value for ID to prevent redundant lookup
	resetInputNewValue($inpField.attr("id"),false);
}


function goToDropDown()
{
	//currently assuming only one pair EN
	var selectedOption=$("#confirmPlace").val().split("|");
	var placeName=selectedOption[1];
	var placeEasting=selectedOption[3];
	var placeNorthing=selectedOption[4];
	
	var geo=ConvertBNGtoWGS84(placeEasting,placeNorthing);
	var newGLocation=new GLatLng(geo.latitude, geo.longitude)
	mapGoogle.setCenter(newGLocation, 13);
	
	populateHotelsBarGaz();
	
}

/** convenience function for setting the background to errorCol on the given widget **/
function setErrorBG(widget) {
	$(widget).addClass("alertError");
	$(widget).removeClass("inputSpinner");
	/*widget.style.backgroundImage = "url(/resources/images/maps/search-alert.gif)";*/
	/*widget.style.backgroundPosition = "95% 7px";*/
	/*widget.style.backgroundRepeat="no-repeat";*/
}

/** convenience function for setting the background white on the given widget **/
function setWhiteBG(widget) {
	$(widget).removeAttr("style").removeClass("alertError").removeClass("inputSpinner");
}


/** Keypress event handler for map search */
function searchFieldKeypress(e) {
 if(e.which == 13) {
	$searchPlace=$("#searchPlace");
	$confirmPlace=$("#confirmPlace");
	 //clear overlays
  	resetMap();
 	doGazSearch();
	fetchDestinationSensitiveAds(false);
 }
}



function resetInputFields()
{
	 // Delete the place text
	$("#searchPlace").css("background-color","#FFFFFF");
	$("#searchPlace").val("");
}


function resetInputNewValue(inputID,blnValue)
{
	if(inputID=="searchPlace")
	{
		isNewSearchValue=blnValue;
	}  
}




function toggleSideBar()
{
	var $route=$("#route");
	if($route.css("display")=="none")
	{
		//show 
		$route.show();
		var center = mapGoogle.getCenter();
		$('#map').css('margin-left','');
		mapGoogle.checkResize();
		mapGoogle.setCenter(center);
		$("#sidebarSlider img").attr("src","/resources/images/maps/toggle-panel-left.png");
	}
	else {
		$route.hide();
		var center = mapGoogle.getCenter();
		$('#map').css('margin-left','0');
		mapGoogle.checkResize();
		mapGoogle.setCenter(center);
		$("#sidebarSlider img").attr("src","/resources/images/maps/toggle-panel-right.png");
	}
}



/** hide the "Get route" button and show the swirl image **/
function showLoading() {
	$('.searchPlaceBtn','#findPlaceWrapper').css({"background-position": '0 top'});
	$('.searchPlaceBtn span','#findPlaceWrapper').css({"background-position": '100% top'});
}

/** hide the swirl image and show the Get Route button **/
function hideLoading() {
	$('.searchPlaceBtn','#findPlaceWrapper').css({"background-position": '0 -32px'});
	$('.searchPlaceBtn span','#findPlaceWrapper').css({"background-position": '100% -32px'});
}



function toggleMatchList(obj,id)
{
  //set all to hidden
  var $elem=$("#" + id);
  
  var tmpDisplayValue=$elem.css("display");

  //hide all
  $(".matchWrapper").hide().css("position","static");
  
  //if originally hidden, then display
  if(tmpDisplayValue=="none") {
    $elem.show();
	
	//set page absolute position...
	var pos=$elem.position();
	$elem.css({ position: "absolute",
				marginLeft: 0, marginTop: 0,
				top: pos.top+2, left: pos.left });

    //change link text
    obj.innerHTML="hide list";
  }
  else {
    obj.innerHTML="select from list";
  }
  
  //set focus and blur
  
  return false;
}


function selectNodeMatch(gazstring,id,inputid)
{
  $("#" + id).val(gazstring);
  $("#" + inputid).val(getPlaceFromGazString(gazstring));
  $("#" + id + "-list").hide();
  $("#linkToggle" + id).text("select from list");
  //go to location
  resetMap();

  isNewSearchValue=false;
  goToGazResult();
  return false;
}

function resetMap()
{
  mapGoogle.clearOverlays();
 // mapGoogle.addOverlay(ttTileLayerOverlay);

}

function getPlaceFromGazString(gazstring)
{
  if(gazstring!=""&&gazstring!=null)
  {
    var arrGazString=gazstring.split("|");
    var placeName=unescape(arrGazString[1]);
    return placeName;
  }
  return "";
}


function showAADataLayer(checked,cbName)
{
    
  if (cbName=='dispRoadworks')
  {
	if (checked){ 
		displayTrafficAlertOverlay(mapGoogle,true,'overlayMapMessage','roadworks');
	}
	else {
		displayTrafficAlertOverlay(mapGoogle,false,'overlayMapMessage','roadworks');
	}
  }
  else if (cbName=='dispTrafficAlert')
  {
	if (checked){ 
		displayTrafficAlertOverlay(mapGoogle,true,'overlayMapMessage','delays');
	}
	else {
		displayTrafficAlertOverlay(mapGoogle,false,'overlayMapMessage','delays');
	}
  }
}

function getGazPlaceFromString(str)
{
	strOut="";
	try {
		var arrStr=str.split("|");
		strOut=arrStr[1];
	}
	catch(e) {
	}
	return strOut;
} 


/*
function goToAndShowMarker(map,inpLat,inpLon,inpZoom,inpPOIid,inpPOIType,inpPOIName)
{
//check for float
  inpLat=parseFloat(inpLat) || null;
  inpLon=parseFloat(inpLon) || null;
  inpZoom=parseInt(inpZoom) || 13;
  inpPOIid=parseInt(inpPOIid) || null;
  inpPOIType=inpPOIType||null;
  inpPOIName=inpPOIName||'';
  
  if(inpZoom>17||inpZoom<0) inpZoom=13;
  //if got a POIID then do lookup and show on map
    
    if(inpLat!=null&&inpLon!=null)
    {

      if(inpPOIid!=null&&inpPOIType!=null)
      {
        var poiTypeID=getPOIIDFromType(inpPOIType);
        //get poitype and name
        showSinglePOI(map,inpLat,inpLon,inpPOIid,poiTypeID,true,true,inpPOIName);

      }
      else if(inpPOIName!=''){
			var newGLocation=new GLatLng(inpLat, inpLon);
          map.setCenter(newGLocation, inpZoom);
          addLocationMarker(map,newGLocation,inpPOIName);
		}
	else {
          var newGLocation=new GLatLng(inpLat, inpLon);
          map.setCenter(newGLocation, inpZoom);
          addLocationMarker(map,newGLocation,'' + inpLat + ', ' + inpLon);
        }
    }
}
*/


function addLocationMarker(map,point,loctitle)
{
 var locMarker=new GMarker(point,{title:loctitle});
 if(loctitle!='')
 {
  GEvent.addListener(locMarker, 'click', function() {  
            // When clicked, open an Info Window  
            locMarker.openInfoWindowHtml(loctitle); 
          });       
  }
  map.addOverlay(locMarker);
} 


function zoomTraffic(a,b)
{

	//hide/show flow
	if((b<=5 || b>17) && !ttTileLayerOverlay.isHidden()) ttTileLayerOverlay.hide();
	if(b>5 && ttTileLayerOverlay.isHidden()) ttTileLayerOverlay.show();
	
	
	//toggle input for roadworks
	//a=old,b=new

	if(b>delayZoomThreshold)
	{
		$("#pRoadworks").css("opacity","1");
		$("#dispRoadworks").attr("disabled","false");
		document.getElementById("dispRoadworks").disabled=false;
	}
	else if(b<=delayZoomThreshold)
	{
		$("#pRoadworks").css("opacity","0.5");
		$("#dispRoadworks").attr("disabled","disabled").removeAttr('checked');
		clearMgrMarkers(trafficRoadworksMgr);
	}
	
	
	//if a and b in between same thresholds, and zooming in then don't reload
	//reload when zooming out at low zoom levels as will have new boundaries
		
	if(a < delayZoomThreshold && b < delayZoomThreshold )
	{
		return;
	}
	if(b > a && a > delayZoomThresholdMin && b >= delayZoomThresholdMin)
	{
		return;
	}
	if(b > a && a >= delayZoomThreshold && a < delayZoomThresholdMin && b >= delayZoomThreshold && b < delayZoomThresholdMin)
	{
		return;
	}
	

	//TBD - check at UK zoom levels.. what if cleared?
	//reload traffic
	setTimerClearAndReloadTraffic(AATraffic,mapGoogle);

}

function moveTraffic()
{
	//TBD - check at UK zoom levels.. what if cleared?
	if(mapGoogle.getZoom()>=delayZoomThreshold && latlngScrollRequests)
	{
		//reload traffic
		setTimerClearAndReloadTraffic(AATraffic,mapGoogle);
	}
}

function setTimerClearAndReloadTraffic(AATraffic,mapGoogle)
{
	//set timeout to reduce calls
	if(alertCallTimer!=0) clearTimeout(alertCallTimer); 
	if(trafficXHR!=null)
	{
		trafficXHR.abort();
	}
	alertCallTimer=setTimeout(function(){clearAndReloadTraffic(AATraffic,mapGoogle);AATraffic=null,mapGoogle=null},800);
}

