/** 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 currentZoom = 11; //Holds the current zoom level, default is 11.

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 userInfo ={
    locSearch : 0,
    journeySearch : 0
}

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());
    },

    addTrafficStuff : function(){
        var mapOptions = {
        googleBarOptions : {
            style : "new",
            adsOptions: {
                client: "partner-google-maps-api",
                channel: "AdSense for Search channel",
                adsafe: "high",
                language: "en"
                }
            }
        }

        map.addControl(new ExtMapTypeControl({
                            showTraffic: true,
                            showTrafficKey: true}
                       ));
       
    }
}

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;
        }
    }
   
    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 && document.location.href.indexOf('premier-inn-hotels') == -1){
        getLocation("London",true);
    }

    else{
        //we have parameters or friendly urls - chk which condition and act accodingly

        //friendly urls eg Cornwall-premier-inn-hotels.php
        if( document.location.href.indexOf('premier-inn-hotels') > 0){
            getLocation($j('.areaName').html(),false )
        }

        //old style location jump
        if(GetParameterFromURL("place") ){
            getLocation(GetParameterFromURL("place"),false);
        }


        //area search from homepage
        if(GetParameterFromURL("locSearch") ){
            getLocation(GetParameterFromURL("locSearch"),false);
        }

        // journey plan 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( depart,to,0 )
            
            //we need to increment here to allow for them coming in as a journey planner search
            //else the first search wont be logged into the db
            userInfo.locSearch = userInfo.locSearch + 1;
        }

        
    }//end of url manipulation of map stuff
   
    //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);

    //mapHelper.addTrafficStuff();
}

function customWindow(hotel){
/*-------------------------------------
Description: 
Shows a floating window on the google map to show the hotel information.

Updates: 
- 20 Jul(JL) - applied new styling
- 19 Mar'10(CD) - applied new styling from new skin

TODO:
- add closing button
-------------------------------------*/

    //create template for window template
        var winTpl = [
        '<div id="theWrapper"><div id="locationCardWrapper">',
        '    <div id="locationCardHead">xyzHotelName',
        '        <a class="closeBtn" href="#" onClick="popup_window_hide()"> </a>',
        '    </div>',
        '    <div id="locationLogo"> </div>',
        '    <div id="locationTextWrap">',
        '        <p id="address">',
        '            xyzAddr1<br />',
        '        </p>',
        '        <p id="pricing">',
        '            Midweek <span>&pound;xyzMidP</span> | Weekend <span>&pound;xyzWkendP</span>',
        '        </p>',
        '    </div>',
        '    <div id="btnWrap">',
        '        <a class="locationDirections" href="#"' + "onclick='setDestinationFromLocation(\"" + hotel.lat + '","' + hotel.lng + '","' + hotel.name + '","' + hotel.link+ '","' + $('origin').value + '","' + hotel.postcode + "\"),select(\"route\")\'>",
        'Get Directions</a>',
        '        <a target="_blank" class="locationBook trackingNeeded" rel="NoFollow" href="xyzLink"> </a>',
        '    </div>',
        '<div class="clearer"></div></div><div id="bottom"></div></div>'].join(" ");

        winTpl = winTpl.replace("xyzHotelName",hotel.name);


        var fullAddress ='';
        if (hotel.address1){
            fullAddress += hotel.address1 + '<br>';
	}
/*
        if (hotel.address2){
            fullAddress += hotel.address2 + ', ';
	}
*/
	if (hotel.address3){
            fullAddress += hotel.address3 + '<br> ';
	}
        if (hotel.postcode){
            fullAddress += hotel.postcode;
        }

        winTpl = winTpl.replace("xyzAddr1", fullAddress);

        winTpl = winTpl.replace("xyzMidP",hotel.mprice);
        winTpl = winTpl.replace("xyzWkendP",hotel.wprice);
        winTpl = winTpl.replace("xyzLat",hotel.lat);
        winTpl = winTpl.replace("xyzLong",hotel.lng);
        winTpl = winTpl.replace("xyzLink",'headto/headto.php?page='+hotel.linkId);       
        winTpl = winTpl.replace("xyzPostCode",hotel.postcode);
        winTpl = winTpl.replace("xyzOrigin",jQuery('#origin').val());

        //var test = '<div style="width :50px;height:50px;background:#fff; margin-left: 500px">test</div>'
	return winTpl;
}

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
 */
        map.closeExtInfoWindow();
	$j('#theWrapper').remove();
        $j('#locationCardWrapper').remove();
}

function createMarker(point, hotel){
/*-------------------------------------
Description: 
Adds a hotel marker to the map

Author: DH
Updates:
23-Mar'10 Changed markers to fire popup card on hover, added mouseout event listener to popup card to close it - CD
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, 'mouseover',
      function(){
         marker.openExtInfoWindow(
             map,
             "locationCardWrapper",
             customWindow(hotel),
             {}
         );

         GEvent.addDomListener(document.getElementById('theWrapper'), 'mouseout', function(e){
            if (!e) var e = window.event;
            var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
            while (reltg.tagName != 'BODY')
            {
                if (reltg.id == this.id){return;}
                reltg = reltg.parentNode;
            }
            marker.closeExtInfoWindow(map);
         });
  
      }
   );

   GEvent.addListener(marker, 'mouseout', function(e){
        

        //popup_window_hide();
   });

   return marker;
}

/** unused ???
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:
-------------------------------------*/
    userInfo.journeySearch = userInfo.journeySearch + 1;
    logJourneySearch(from, destination, userInfo.journeySearch);
    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 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++){
        //Set icon
        var icon;
        if( i > 19 )
            icon = 'moon_small';
        else
            icon = (i+1);

        text +='<div class="hotel_name">';
        text +='	<table>';
		text +='		<tr>';
      text +='			<td><img src="images/mapMarkers/'+icon+'.png"/></td><td class="hotel_name">'+ 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="headto/headto.php?page='+ hotels[i].linkId +'" 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){
        //get rid of the popup card
        popup_window_hide();
        userInfo.locSearch = userInfo.locSearch + 1;
        if(userInfo.locSearch > 1){
            //dont log anything on the first search ie when we land on the map page and it auto searches.
                //we need to decreament the locSearch to capture the true number of times a person has searched
            logLocSearch(loc,userInfo.locSearch-1);
        }
        
	//empty out the area info and directions before showing 
	if (clearDescription){
            document.getElementById("area_info").innerHTML ="";
            $j("#new_directions").html("");
            $j('.interact').html('Find a Premier Inn using the map below');
	}
	//$('map_container').style.display = "block";	
	
	map.clearOverlays();
            //devon hack - JL
        if( loc == 'devon' || loc == 'Devon' ){
            loc = 'Devonshire';
        }
        if( loc =='MEN arena'){
            loc = 'M3 1AR';
        }

	address = loc + ',UK';
	var geocoder = new GClientGeocoder();
	geocoder.setBaseCountryCode('UK');

	geocoder.getLatLng(
		address,
		function(point){
			if (!point) {
				$j.prompt(address + " not found");
			} else {
				map.setCenter(point,currentZoom);
				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(currentZoom);
                        //mapHelper.fitMap(map, allMapPoints);
                }
        }
        xmlHttp.open("POST","/scripts/hotel_data.php?&radius=15",true);
        xmlHttp.send(request);
        mapHelper.addTrafficStuff();

}

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 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 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:
23-Mar'10 Added remove popup card function - causes bugs.
TODO:

-------------------------------------*/
   if (typeof debug == undefined){
      var debug = true; //set to 1 to debug
      alert (debug);
   }
   //get rid of the popup card
   popup_window_hide();

   //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 refreshMap(map){
/*-------------------------------------
Description: 
Refreshes the map with the hotels in the area

Author: JL
Updates:
23-Mar'10 Added popup_window_hide function to remove popup card when refresh is done - was causing probs.
Dependencies: 
-------------------------------------*/
        currentZoom = map.getZoom();
	popup_window_hide();
        map.clearOverlays();
        
        var mapPoint = map.getCenter();
	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
-------------------------------------*/
   
   //Set the zoom level if zoom is specified
   if(GetParameterFromURL("zoom")){
        currentZoom = parseInt(GetParameterFromURL("zoom"));
   }
   var debug = 0;
   initialize();
});