/** global variables **/
DcStormCookie = '_#clkid';
var trackingCodeParam= 'A8ID';
var map;
var directionsPanel;
var directions; // GDirections obj defined in initialize()
var hotels = new Array();
var intervalId = new Array();
var frequency = 1; //value to thin out the number of points that get picked up on the polyline
var from = '';
var to = '';
var interest = '';
var urllink = '';
var testob = new Object();

var Url = {
 
	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},
 
	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
};

var mapHelper ={
    fitMap : function(map,points){
    /**
    * @desc sets the zoom level automatically of the map container to show all the points
    * @author JL
    * @param map = the dom map
    * @param points = array of GLatLng points added to the map
    * @return none
    **/

        var bounds = new GLatLngBounds();
        for (var i=0; i< points.length; i++) {
          bounds.extend(points[i]);
        }
        map.setZoom(map.getBoundsZoomLevel(bounds));
        map.setCenter(bounds.getCenter());
    }
}

function initialize() {
/*-------------------------------------
Description: 
Inserts a google map into the map_canvas and initialise the associated objects

Updates: 

-------------------------------------*/

   map = new GMap2(document.getElementById("map_canvas"));
   textdiv = document.getElementById('directions');
	
   //modify the zoom navigation slider to max/min of the following zoom levels
   var mapTypes = map.getMapTypes();
   for(var i=0; i<mapTypes.length; i++)
   {
     mapTypes[i].getMinimumResolution=function(){return 7;}
     mapTypes[i].getMaximumResolution=function() {return 16;}
   }
   
   //center map to london
   map.setCenter(new GLatLng(51.5007286626542, -0.133209228515625), 13);   
   
   largeContol = new GLargeMapControl();        
   map.addControl(largeContol);   
   
   map.disableScrollWheelZoom(); 
   directions = new GDirections(map,textdiv);
   directions.locale = "UK";
   GEvent.addListener(directions, "error", handleErrors);
   GEvent.addListener(directions, "load", getHotels);
   
   //chk if we hava any parameters in the map url, if no then we assume we show hotels in london as starting point 
   if(document.location.href.indexOf('?') == -1){	   
      getLocation("London",true);
   }
   
   //add map refresh button
   var r = [
     '<a onclick="refreshMap(map); return false" href="#"',
     '   <img alt="Refresh Map" title="Refresh Map" src="/images/refresh_icon2.png" id="mapRefreshButton"/>',
     '</a>'].join("\n");
   $j('#map_canvas').prepend(r);
}

function customWindow(hotel){
/*-------------------------------------
Description: 
Shows a floating window on the google map to show the hotel information.

Updates: 
- 20 Jul(JL) - applied new styling

TODO:
- add closing button
-------------------------------------*/

	var markUpTxt = '<div class="hotelInfoPanel">'; 
    
   markUpTxt = markUpTxt +"<div id=\"closeButton\"><a href=\"#\" onClick=\"popup_window_hide()\"><img src=\"images/closeCard.jpg\" width=\"22\" height=\"22\" border=\"0\" /></a></div>";
	markUpTxt = markUpTxt + '<div id="addressHolder">';
	markUpTxt = markUpTxt + "   <div class=\"hotelInfoName\">" + hotel.name + "<br />";
    markUpTxt = markUpTxt + "   <span class=\"hotelInfoText\">";
	
	if (hotel.address1){
		markUpTxt = markUpTxt + "Address: "  + hotel.address1;
	}
	if (hotel.address2){
		markUpTxt = markUpTxt + " <br>"+ hotel.address2;
	}
	if (hotel.address3){
		markUpTxt = markUpTxt + " <br>"  + hotel.address3;	
	}
	
   markUpTxt = markUpTxt + " <br>" + hotel.postcode;
   markUpTxt = markUpTxt + '   </span><br />';
   markUpTxt = markUpTxt + '   <span class="hotelInfoText">Mid Week</span> <span class="hotelInfoTextHighlight">Price From &pound</span> '
	markUpTxt = markUpTxt + '<span class="hotelInfoText">' + hotel.mprice + '</span><br />';
	markUpTxt = markUpTxt + '<span class="hotelInfoText">Weekend</span> <span class="hotelInfoTextHighlight">Price From &pound</span> <span class="hotelInfoText">' + hotel.wprice + '</span></div>';
	markUpTxt = markUpTxt + '</div>'; //close addressHolder
	markUpTxt = markUpTxt + '<div id="hotspots">';
	
  //build the "directions to here" button
	markUpTxt = markUpTxt + '<a href="#"' + "onclick='setDestinationFromLocation(\"" + hotel.lat + '","' + hotel.lng + '","' + hotel.name + '","' + hotel.link+ '","' + $('origin').value + '","' + hotel.postcode + "\"),select(\"route\")\'>";
	markUpTxt = markUpTxt + '<img  class="hotspotsImg" src="images/directbtn.png" width="140px" height="26px"/></a>';
  
  //build the "book now button"
	//markUpTxt = markUpTxt + '<a href="'+ hotel.link + buildParameterList('LID',$j.cookie("A8ID"),'a08_preminn','~~',$j.cookie('_#clkid')) +'" rel="NoFollow" target="_blank"><img  class="hotspotsImg " src="images/bookbtn.png" width="123" height="26"/></a></div>';
        markUpTxt = markUpTxt + '<a href="'+ trk.linkWithTracking(hotel.link) +'" class="trackingNeeded" rel="NoFollow" target="_blank"><img  class="hotspotsImg" src="images/bookbtn.png" width="123" height="26"/></a></div>';
	markUpTxt = markUpTxt +'</div>';
	
	return markUpTxt;
}

function popup_window_hide(){
/**
 * Description:
 * 	Hides the floating window to show the hotel info with the booking button/directions to
 * Author:
 * 	DH
 * Dependencies
 * Changelog: 
 * 	sept 09 - JL - Had to hide then remove as google map bug causes the thing to show again when changing zoom
 */	
	$j('#simple_example_window').css('display','none');
	$j('.hotelInfoPanel').remove()
}

function createMarker(point, hotel){
/*-------------------------------------
Description: 
Adds a hotel marker to the map

Author: DH
Updates: 
26-May removed bloody big if-else statements. Hopefully wont break anything else - JL
22-Jul09 - modified the count when choosing marker to match up side panel
-------------------------------------*/

	//create path to the marker graphic	
	if  (hotel.number >= 0 && hotel.number <= 20){
		//use the numbered icon 1-20
      var iconNumber = hotel.number + 1
		var imagePath = '/images/mapMarkers/'+ iconNumber +'.png';
		var baseIcon = new GIcon(G_DEFAULT_ICON,imagePath);
	} else {
		//use the default icon for any marker numbered 20+
		var baseIcon = new GIcon(G_DEFAULT_ICON,'/images/mapMarkers/moon_small.png');
	}

	//var baseIcon = new GIcon(G_DEFAULT_ICON,'/images/moon_bubble.png');		
	baseIcon.iconSize = new GSize(24, 19);
	//baseIcon.iconAnchor = new GPoint(90, 90);
	//baseIcon.infoWindowAnchor = new GPoint(90, 90);
	baseIcon.shadow = ''
	var numIcon = new GIcon(baseIcon);        
	markerOptions = {icon:numIcon};	
	var marker = new GMarker(point, markerOptions);        
   GEvent.addListener(marker, 'click', 
      function(){
         marker.openExtInfoWindow(
         map,
         "simple_example_window",
         customWindow(hotel),
         {}
         );
      }
   );
   return marker;
}

function getDirections(){	
	//empty out the area info before
	document.getElementById("area_info").innerHTML ="";	
	$('welcome_box').style.display = 'none';
	
	from = document.getElementById("origin").value;
	to = document.getElementById("destination").value;	
	map.clearOverlays();      
	directions.load("from: "+ from +" to: " + to );
    //check status 
    //intervalId.push(window.setInterval( getHotels, 1000 ));   
}

function RoutePlannerGoButton(from, destination,debug){
/*-------------------------------------
Description: 
behaviour attached to the Go button the route planner

Author: JL
Updates: 
TODO:
-------------------------------------*/
   if(!debug){
      var debug = 0;
   }
   	$j('#origin').css('border','1px solid black');
	if (destination == "Arrival"){
		$j.prompt("Please select a destination");
	}
   else if(from == "Departure") {
	   $j.prompt("Please select a departure");
   }
	else
	{
		// clear out the display items before creating route
		map.clearOverlays();      
		//$('map_container').style.display = "block";	
		$('welcome_box').style.display = 'none';
		
		document.getElementById("area_info").innerHTML ="";		
		   
		getDirections(from, destination);
	}
}
		
	
function getDirections(from, destination){	
/*-------------------------------------
Description: 
calls the gdirections.load method with the route paramters so that map us updated with the route

Author: JL
Updates: 
TODO:
Moved the page clear actions out of the function - JL
-------------------------------------*/
	
	directions.load("from: "+ from +",UK to: " + destination + ",UK");
    //check status 
    //intervalId.push(window.setInterval( getHotels, 1000 ));   
}

function getHotels(){
	var routes;
	
   var offset = 0;
   var route = new Array();
   var steps = new Array();
   var poly = directions.getPolyline();
	if (poly){
		routes = poly.getVertexCount();
		if (routes > 200){
			frequency = parseInt(routes / 200);
		} 		
		if (routes)
		
		if (directions.getStatus().code == 500){
			return;
		}
		else {
			for(var  i = 0; i < intervalId.length; i++ ){
				window.clearInterval(intervalId[i]);
			}
			for ( var i = 0 ; i < routes; i++){
				steps.push(poly.getVertex(i));
				
				if (offset++ > frequency){ //thin out their numbers
					 offset = 0;                
				} else {
					steps.pop();               
				}            
			}
		}
		
		var request = '';
		
		for (var i = 0; i < steps.length; i++){			
			request += steps[i].lat();
			if (i > 0 && i < steps.length - 1){
				request += "|";
			}
		}
		
		request += "&";
		
		for (var i = 0; i < steps.length; i++){			
			request += steps[i].lng();
			if (i > 0 && i < steps.length - 1){
				request += "|";
			}
			
		}
		
		
		var xmlHttp;
		try {
		// Firefox, Opera 8.0+, Safari
			xmlHttp=new XMLHttpRequest();
		} catch (e) {
		// Internet Explorer
			try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {
					$j.prompt("Your browser does not support AJAX!");
				return;
				}
			}
		}
		
		xmlHttp.onreadystatechange=function(){
			if(xmlHttp.readyState==4){
			// Get the data from the server's response
			eval(xmlHttp.responseText);
			addMarkers();
			showHotels();
			drawDirections();
			//document.getElementById("my_textual_div").style.display = 'block';
			}
		}				
		xmlHttp.open("POST","/scripts/hotel_data.php" ,true);
		xmlHttp.setRequestHeader("Content-Type","text/html; charset=UTF-8")
		xmlHttp.send(request);   		
	}
	//trk.addTrackingToDeepLink(".trackingNeeded", "LID", $j.cookie("A8ID"),$j.cookie(DcStormCookie));
}

function addMarkers(){
	var poly = directions.getPolyline();
	bounds = poly.getBounds();
	map.setCenter(bounds.getCenter()); //set map to show poly line
	map.setZoom(map.getBoundsZoomLevel(bounds)); //zoom to show poly linhotel_data.phpe
    map.addOverlay(poly);
	createPolyMarkers();
    for (var i = 0; i < hotels.length ; i++){ // add hotel markers to the map
    var point = new GLatLng(hotels[i].lat,hotels[i].lng);
			hotels[i].number = i;
            map.addOverlay(createMarker(point, hotels[i]));
    }   
}

function createPolyMarkers(){
	var baseIcon = new GIcon(G_DEFAULT_ICON,'/images/icon_from.png');
	baseIcon.iconSize = new GSize(27, 38);
	markerOptions = {icon:baseIcon};	
	var marker = new GMarker(directions.getMarker(0).getLatLng(), markerOptions);
	map.addOverlay(marker);
	baseIcon = new GIcon(G_DEFAULT_ICON,'/images/icon_to.png');
	baseIcon.iconSize = new GSize(27, 38);
	markerOptions = {icon:baseIcon};	
	marker = new GMarker(directions.getMarker(1).getLatLng(), markerOptions);
	map.addOverlay(marker);
}


function select(panel){
	if ( panel == 'route'){
		show_route_planner()
	}
	if ( panel == 'location'){
		show_location_search()
	}
}

function show_route_planner(){
  $j('#side_panel').css('backgroundImage','url("images/routePlanner.jpg")');
	document.getElementById('search_bottom').style.display = 'none';
	document.getElementById('panel_bottom').style.display = 'block';
	
}

function drawDirections(){
/*-------------------------------------
Description: 
This shows in id text block "new directions" the route craeated by google.
Also shows the email button

Updates: 
TODO:
- possibly link back the directions back to a point on the google map?
- link back the email button?
-------------------------------------*/
	var text = '<div id="directions_head" ><a onclick="show(this);" >Show directions to destination (Click Here) </a> </div>';
   //text += '<div id="directionsArea">';	
   text += '<table id="directions_table">';
   
   var printCmd = 'onclick=\'PrintDirections("#directions_table",".PrintButton",0)\'/>'
   text += '<input class="PrintButton" type="button" value="Print" onclick=\'PrintDirections("#directions_table")\'/>';
	for(var i = 0; i < directions.getRoute(0).getNumSteps(); i++){		
		text += '<tr><td style="text-align:right">' + (i + 1) + '.</td><td style="width:630px">' + directions.getRoute(0).getStep(i).getDescriptionHtml() + '</td><td style="text-align:right">' + directions.getRoute(0).getStep(i).getDistance().html + '</td></tr>';
		text += '<tr><td colspan="3"><hr /></td></tr>';
	}
   //text += '</div>';
   text += '<tr><td><input class="PrintButton" type="button" value="Print" onclick=\'PrintDirections("#directions_table")\'/></tr></td>';
   text += '</table>';
	//text += '<tr><td colspan="3" class="EmailDirections"><input onclick="showMailForm()" type="button" value="Email These Directions"/></td></tr></table>';
	document.getElementById("new_directions").innerHTML = text;
}

function PrintDirections(elementToPrint,elementToRemove,debug){
/*-------------------------------------
Description: 
Prints the element using jquery lib, can also remove certain elements before printing.

Updates: 
   rev 1 - 22 July(JL)
   
@Parameter - elementToPrint - The string css element we are selecting to print eg table of data
@Parameter - elementToRemove - The string css element we are selecting to hide during printing eg buttons or certain headers
@Parameter - debug - boolean value to indicate if we are going to debug
   
Depdendency:
   jq.jqprint.0.3.js
-------------------------------------*/
   if(debug){
      $j.prompt(elementToPrint);
      $j.prompt($j(elementToPrint));
   }
   
   if(elementToRemove){
      $j(elementToRemove).css("display","none");
   }
   $j(elementToPrint).jqprint();
   
   if(elementToRemove){
      $j(elementToRemove).css("display","block");
   }
}

function showMailForm(){
	$('mail_form').style.display = 'block';
}

function hide_form(){
	$('mail_form').style.display = 'none';
}

function show(){
	$('directions_table').style.display = 'block';
	$('directions_head').innerHTML = "<a onclick='hide(this);' >Hide directions to destination (Click here) </a>";
	//$('directions_head a').onclick = hide;
}

function hide(){
	$('directions_table').style.display = 'none';
	$('directions_head').innerHTML = "<a onclick='show(this);' >Show directions to destination (Click Here)</a>";
	//$('directions_head a').onclick = show;
}

function drawAreaInfo(area, info, image){ //todo not used? - done backend
/*-------------------------------------
Name: drawAreaInfo
Description: 
Show city description and image in the div "area_info".
Function is dynimcally created on page load in areas.php

Updates: 
20-May(JL) added extra parameter 'image' as optional parameter
-------------------------------------*/
   if ( image === undefined ) {
      image = 'NoImage.gif';
   }

	var text = '<h4>Local Area Information - ' + area + '</h4>';
	text += '<img class="areaPhoto" src="' + image + '" height="125">';
	text += '<p class="areaText">' + info + '</p>';
	document.getElementById("area_info").innerHTML = text;
}

function show_location_search(){
   
	//panel_top = document.getElementById('side_panel'); //stoopid ie8
   $j('#side_panel').css('backgroundImage','url("images/locationSearch.jpg")');
   
	//panel_top.style.backgroundImage = "url('images/locationSearch.jpg')";
	document.getElementById('panel_bottom').style.display = 'none';
	document.getElementById('search_bottom').style.display = 'block';	
}

function showHotels(){
    //creates the hotels nearby on the side bar
	var text = '';
	document.getElementById('nearby').style.display = 'block';
	display = document.getElementById('nearby_hotels');
   
   var newHotels = hotels; 
   
	for (var i = 0; i < hotels.length; i++){   
      text +='<div class="hotel_name">';
		text +='	<table>';
		text +='		<tr>';
      text +='			<td><img src="images/moon_small.png"/></td><td class="hotel_name">' + ( i + 1 ) + ': ' + hotels[i].name + '</td>';
		text +='		</tr>';
		text +='	</table>';
		text +='</div>';
		text +='<div class="hotel_description">';
		text +='	<table style="width:100%">';
		text +='		<tr>';
		text +='			<td>Mon - Thurs : From &pound;' + hotels[i].mprice + '</td><td></td><td rowspan="2" class="book_now"><a class="trackingNeeded" href="'+ hotels[i].link +'" rel="nofollow" target="_blank"><img src="../images/book_purple.png"></a></td>';
		text +='		</tr>';
		text +='		<tr>';
		text +='			<td>Fri - Sun : From &pound;' + hotels[i].wprice + '</td><td></td>';
		text +='		</tr>';
		text +='	</table>';
		text +='</div>';
	}
	display.innerHTML = text;
	//addTrackingToDeepLink(".trackingNeeded", "LID", $j.cookie("A8ID"),'a08_preminn','~~',$j.cookie('_#clkid'));
        trk.addTrackingToDeepLink(".trackingNeeded", "LID", $j.cookie("A8ID"),$j.cookie('_#clkid'));

}

function getLocation(loc,clearDescription){		
	//empty out the area info and directions before showing 
	if (clearDescription){
            document.getElementById("area_info").innerHTML ="";
            $j("#new_directions").html("");
	}
	//$('map_container').style.display = "block";	
	
	map.clearOverlays();
	address = loc;
	var geocoder = new GClientGeocoder();
	geocoder.setBaseCountryCode('UK');

	geocoder.getLatLng(
		address + ", uk",
		function(point){
			if (!point) {
				$j.prompt(address + " not found");
			} else {
				map.setCenter(point);
				getHotelsByLocation(point);
			}
		}
	);

	
}

function getHotelsByLocation(point){
	request = point.lat() + '&' + point.lng();
	var xmlHttp;
        try {
        // Firefox, Opera 8.0+, Safari
                xmlHttp=new XMLHttpRequest();
        } catch (e) {
        // Internet Explorer
                try {
                xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                        try {
                                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e) {
                                $j.prompt("Your browser does not support AJAX!");
                        return;
                        }
                }
        }

        xmlHttp.onreadystatechange=function(){
                if(xmlHttp.readyState==4){
                // Get the data from the server's response
                        eval(xmlHttp.responseText);
                //addMarkers();
                        showHotels();
                        var allMapPoints =[];//array of all points on map
                        for (var i = 0; i < hotels.length ; i++){ // add hotel markers to the map
                                point = new GLatLng(hotels[i].lat,hotels[i].lng);
                                //add number in list
                                hotels[i].number = i;
                                map.addOverlay(createMarker(point, hotels[i]));
                                allMapPoints.push(point);
                        }
                        map.setZoom(11);
                        //mapHelper.fitMap(map, allMapPoints);
                }
        }
        xmlHttp.open("POST","/scripts/hotel_data.php?&radius=15",true);
        xmlHttp.send(request);

}

function set_destination(lat,lng,name,hotel_url){
	interest = name;
	urllink = Url.encode(hotel_url);
	geocoder = new GClientGeocoder;
	geocoder.getLocations(new GLatLng(lat,lng),handler);	
	map.clearOverlays();
	initialize();
    directions.load("from: "+ from +" to: " + to);
    //check status 
    //intervalId.push(window.setInterval( getHotels, 1000 )); 
}

function handler(){ 
//this functions gets called to handle what get's returned from the reverse geocode function set_destination()
	object = arguments[0];
	to = object.Placemark[0].address
	$('destination').value = object.Placemark[0].address;
	getDirections();
}

function $(element){
	return document.getElementById(element);
}

function send_mail(){	
	var sender = $('sender_field').value;
	var from_address = $('from_address').value;
	var to_address = $('to_address').value;
	var body = Url.encode("<table>" + $('directions_table').innerHTML + "</table>");
	var location = to;	
	var xmlHttp;
		try {
		// Firefox, Opera 8.0+, Safari
			xmlHttp=new XMLHttpRequest();
		} catch (e) {
		// Internet Explorer
			try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {
					$j.prompt("Your browser does not support AJAX!");
				return;
				}
			}
		}
	xmlHttp.onreadystatechange=function(){
		
		if(xmlHttp.readyState==4){
			hide_form();
		}
	}
	xmlHttp.open("GET","/scripts/mail.php?sender=" + sender + "&from=" + from_address + "&to=" + to_address + "&body=" + body + "&location=" + location + "&interest=" + interest + "&link=" + urllink,true);
	xmlHttp.send('');	
	$j.prompt('Email sent to '+to_address);
}

function changeob(ob){	
	if (ob.value == 'Departure' || ob.value == 'Arrival'){
		ob.value = '';
	}
}

function fillob(ob){	
	if (ob.id == 'origin' && ob.value == ''){
	ob.value = 'Departure';
	}
	if (ob.id == 'destination' && ob.value == ''){
		ob.value = 'Arrival';
	}	
}

function handleErrors(){
	if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS){
		$j.prompt("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + directions.getStatus().code);
	}
	else if (directions.getStatus().code == G_GEO_SERVER_ERROR){
		$j.prompt("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + directions.getStatus().code);
	}
	else if (directions.getStatus().code == G_GEO_MISSING_QUERY){
		$j.prompt("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + directions.getStatus().code);
	}
	//   else if (directions.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     $j.prompt("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + directions.getStatus().code);
	else if (directions.getStatus().code == G_GEO_BAD_KEY){
		$j.prompt("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + directions.getStatus().code);
	}
	else if (directions.getStatus().code == G_GEO_BAD_REQUEST){
		$j.prompt("A directions request could not be successfully parsed.\n Error code: " + directions.getStatus().code);
	}
	else {
		$j.prompt("An unknown error occurred.");
	}
   
}

function clearField(fieldRef, defaultValue){	
/*-------------------------------------
Description: 
passes in the element id and clears the field if it contains the defaultValue.
Used to clear textfields

Author: JL
Updates: 
-------------------------------------*/
	if (document.getElementById(fieldRef).value == defaultValue){
		document.getElementById(fieldRef).value = '';
	}
}


function ExtractParametersFromUrl(debug) {
/*-------------------------------------
Description:
Extracts the complete paramter string from a URL.
eg "xyx.com?param1=AAA&param2=BBB" will return "?param1=AAA&param2"

Author: JL May '09
Dependencies:
Updates:
-------------------------------------*/
	var theUrl = window.location.href;
	var paramStart = theUrl.indexOf("?");
	
	// if no parameter string then exit
	if(paramStart == -1){
		return -1;
	}

	var paramString = theUrl.substring(paramStart, theUrl.length);
	if (debug) {$j.prompt('ExtractParametersFromUrl.paramString = ' + paramString);}
	
	return paramString;
}


function z_showIntroOrMap(){// DEPRCATED ???
/*-------------------------------------
Description: 
This function either shows the map 

Author JL Jul'09

t0do:
- add check to see if user chooses to hide or show cookie
-------------------------------------*/
	//var paramString = ExtractParametersFromUrl();
	var showMap = GetParameterFromURL('map');

	
	//if url to show map straight off
	if (showMap){
		initialize();
	}
	else{
		var temp = 'http://'+window.location.hostname+'/'+'template'+'/'+'welcome.html';
		$j.prompt(temp);
		$j("#map_canvas").html(temp) ;
		//inject welcome.html into div tag
	}
}

function doPopUpIntroduction(){
 /*-------------------------------------
Description:
Does the floating pop up introduction

Author: JL Jul '09
Dependencies: popup.js
Updates:
Parameters: None
-------------------------------------*/
   //SETTING UP OUR POPUP
   //0 means disabled; 1 means enabled;
   var popupStatus = 0;

	//centering with css
	centerPopup();
	//load popup
	popupStatus = loadPopup(popupStatus);	
   
	//LOADING POPUP
	//Click the button event!   
	$j("#button").click(function(){
      //centering with css
      centerPopup();
      //load popup
      popupStatus = loadPopup(popupStatus);	
	});

	//CLOSING POPUP
	//Click the x event!
	$j("#popupContactClose").click(function(){
		popupStatus = disablePopup(popupStatus);
	});
	//Click out event!
	$j("#backgroundPopup").click(function(){
		popupStatus = disablePopup(popupStatus);
	});
	//Press Escape event!
	$j(document).keypress(function(e){
		if(e.keyCode==27 & popupStatus==1){
			popupStatus = disablePopup(popupStatus);}
	});
   /* end oof pop code */
}

function GetParameterFromURL(name){
/*-------------------------------------
Description:
Extracts a parameter from the url. eg xyz.com/test.php?msg=hello
GetParameterFromURL('msg') will get 'hello'

Author: http://www.netlobo.com/url_query_string_javascript.html
Dependencies:
Updates:
@Parameters: name = name of the parameter to extract
-------------------------------------*/
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function setNoShowIntroCookie(){
/*-------------------------------------
Description:
Extracts a parameter from the url. eg xyz.com/test.php?msg=hello
GetParameterFromURL('msg') will get 'hello'

Author: JL July 09
Dependencies: jquery.js, jq.cookie.js
Updates:
-------------------------------------*/	
	$j.cookie('noIntro',true);
	//alert ('$j.cookie(\'noIntro\)' is '+$j.cookie('noIntro'));
}

function showLocation(locationName,image,description){
//TODO REMOVE?

/*-------------------------------------
Description:
Calls the series of functions that draws the map and shows the text of that location
eg call showLocation('Brighton','pic URL','this is a description')

Author: Joe Lee July 09
Dependencies:
Updates:
@Parameters: locationName = name of the place
-------------------------------------*/
   // 
   if (description){
      getLocation(locationName,0);
      drawAreaInfo(locationName,description,image);
   }
   else{
      getLocation(locationName,0);
   }
}

function setDestinationFromLocation(lat,lng,name,hotel_url,from,to,debug){
/*-------------------------------------
Description: 
Takes the parameters to create a route on the map

Author: JL
Updates: 
TODO:

-------------------------------------*/
   if (typeof debug == undefined){
      var debug = true; //set to 1 to debug
      alert (debug);
   }
   
   //reset the input box
   $j('#origin').css('border','1px solid black');
   
   if($j('#origin').val() == 'London'){
	   $j('#origin').css('border','3px solid red');
	   $j.prompt('Please input the location you wish to travel from. \n E.g. Post Code or Street name');	   
	   return false;
   }
	interest = name;
	urllink = Url.encode(hotel_url);
	geocoder = new GClientGeocoder;
	
	//geoEncodeHandler is a function defined here
   $('destination').value = to

   //from = from + ", UK";		
	prepScreenForRoute();
	
	initialize();
	
	var routeInstruction = "from: "+ from +",UK to: " + to +",UK";	
    directions.load(routeInstruction);
}

function prepScreenForRoute(){
/*-------------------------------------
Description: 
shows relevant divs that relate to route display and hides certain divs

called by prepScreenForRoute and setDestinationFromLocation
Author: JL
Updates: 
-------------------------------------*/
	map.clearOverlays();      
	$('new_directions').style.display = 'block';	
	$('welcome_box').style.display = 'none';
	$('area_info').style.display = 'none';
}

function geoEncodeHandler(to){ 
/*-------------------------------------
Description: 
this functions gets called to handle what get's returned from the reverse geocode function set_destination()

Author: DH
Updates: 
TODO:
- do we need this handler? As the returning geo address causes an error
-------------------------------------*/
	object = arguments[0];
	//to = object.Placemark[0].address
	//$('destination').value = object.Placemark[0].address;	
	
	//destination.value = document.getElementById('side_panel');
	
	getDirections();
}

function returnTodaysDate(debug){
/*-------------------------------------
Description: 
Returns string of todays date as (d)d(m)myyyy eg 112009 (1st jan 2009), 25122009

Author: Jul 09 JL
Updates: 
Dependencies:    
-------------------------------------*/
   var d=new Date();
   var day=d.getDate().toString();
   var month=(d.getMonth() + 1).toString();
   var year=d.getFullYear().toString();         

   if (debug){
      $j.prompt(day + month + year);
   }   
   
   return day + month + year;
}


function settingResettingCookie(cookieName,cookieValue,currentCookie){
/*-------------------------------------
Description:
sets the cookie if it hasnt been set but also will only set if its not the same.

Author: JL
Dependencies:
	jquery.cookie lib
Updates:
@Parameters: cookieName = name of the cookie
@Parameters: cookieValue = new cookie value to set if not present
@Parameters: currentCookie = current cookie value
-------------------------------------*/
	//chk if cookie present
	if($j.cookie(cookieName) == null && cookieValue != null){
		$j.cookie(cookieName,cookieValue);
	}
	//chk if cookie the same, if not then replace with this cookieValue
	else if ($j.cookie(cookieName) != currentCookie && cookieValue != null){
		$j.cookie(cookieName,cookieValue);
	}
	
}

function zz_buildParameterList(trackingVarName,trackingCode,noTrackValue,dcsDelimiter,dcsTracker){
/*-------------------------------------
Description: 
Builds a parameter string with the tracking for a URL with no parameters

 eg ?lid=a9_test

Author: JL
Updates: 
Dependencies: 
   jq.cookie
-------------------------------------*/
	var trackParam='';
	
	if(!trackingCode){
		trackingCode = noTrackValue;
	}
	trackParam = '?' + trackingVarName + '=' + trackingCode + dcsDelimiter + dcsTracker;
	return trackParam;
}

function refreshMap(map){
/*-------------------------------------
Description: 
Refreshes the map with the hotels in the area

Author: JL
Updates: 
Dependencies: 
-------------------------------------*/
	var mapPoint = map.getCenter();
	map.clearOverlays();
	getHotelsByLocation(mapPoint);
}
//************************************************************************//

//jquery magic here we go! Run this when page dom is ready
$j(document).ready(function() {
/*-------------------------------------
Description: 
Runs when doc is ready

Author: JL
Updates: 
Dependencies: 
   jq.cookie, jquery
-------------------------------------*/
   var debug = 0;
   initialize();
      
	//check if need to update the google map to go to a specific location
   if ($j(".areaName").length > 0){
      getLocation($j('.areaName').html(),false);
   }
   
   //chk if need to set cookie a8id, see if in url params.
   if(GetParameterFromURL(trackingCodeParam)){
	   $j.cookie(trackingCodeParam,GetParameterFromURL(trackingCodeParam));	   
   }
   
   // if we are redirected from the homepage - get the locSearch parameter and update google maps
   if(GetParameterFromURL("locSearch")){
	   getLocation(GetParameterFromURL("locSearch"),true);
   }
   
   // journey plan redirect from homepage
   if(GetParameterFromURL("to")){
	   //set the journey planner form values
	   var depart = Url.decode(GetParameterFromURL("depart"));
	   var to = Url.decode(GetParameterFromURL("to"));
	   $j('#origin').val(depart);
	   $j('#destination').val(to);
	   
	   //jouurney plan google magic!
	   RoutePlannerGoButton($('origin').value,$('destination').value,0)
   }
});