/****************************************
* ** Mr & Mrs Smith - Saab Route Planner | lm-mapd.js **
*
* Created by: Chris Mullany, Alastair Brown, Rob Hayward & Chris Hardy,
* Date Created: 2008-07-03
* Copyright 2008 Lightmaker Manchester http://www.lightmaker.com/
*
****************************************/

/*
 * JSMin
 * Javascript Compressor
 * http://www.crockford.com/
 * http://www.smallsharptools.com/
*/

function checkTime(i)
{if(i<10)
{i="0"+i;}
return i;}
function toSmithTime(time)
{var ret="";time=time.toString();var ind=time.indexOf(":");if(ind>0)
{var hrs=parseInt(time.substring(0,ind));ret=hrs+((hrs==1)?"hr":"hrs")+" "+time.substring(ind+1)+"mins";}
return ret;}
function milesToKm(miles,fix)
{if(typeof(miles)=="string")miles=parseFloat(miles);var km=miles/0.621371192;if(fix!=undefined)km=Number(km.toFixed(fix));return km;}
function getDestinationValue(tDestinationValue)
{var tPlaceData=tRoutePlaces[tDestinationValue];if(tPlaceData!=undefined)
{return tPlaceData.name;}
else
{return tDestinationValue;}}
function intoUk(str){var exp=/,?\s*(?:uk|United Kingdom)$/gi;if(!exp.test(str))str+=", uk";return str;}
function notEmptyOrDefault(obj)
{var ret=false;testObj=$(obj)[0];if(testObj&&testObj.value&&testObj.defaultValue)
{var val=testObj.value;var hasNonWhiteSpace=((/\S/gi).test(val)!=null);var notDefault=(val.indexOf(testObj.defaultValue)==-1);ret=(hasNonWhiteSpace&&notDefault)?true:false;}
return ret;}
function extractKeyValue(str)
{var st=str.indexOf("{");var ed=str.indexOf("}");var ret=null;if(st>-1&&ed>-1&&st<ed)
{ret={key:str.substring(st+1,ed),value:str.substring(ed+1)};}
return ret;}
function printpage(){window.print();}
function vecMag(v)
{return Math.sqrt(v.x*v.x+v.y*v.y);}
function vecDot(u,v)
{return(u.x*v.x)+(u.y*v.y);}
function vecMult(c,v)
{return new VEPixel(c*v.x,c*v.y);}
function vecString(v)
{return"<"+v.x.toFixed(2)+","+v.y.toFixed(2)+">"}
function trace(str)
{}
var map=null;var viewTypesConfig=new Array({cssClass:"cluster",type:"Cluster",icon:"hotelIcon.png",clusterClass:"",showStatus:false,shapeLayer:null},{cssClass:"destination",type:"Destination",icon:"destinationIcon.png",clusterClass:"destinationCluster",showStatus:false,shapeLayer:null},{cssClass:"park",type:"Park",icon:"treeIcon.png",clusterClass:"treeCluster",showStatus:false,shapeLayer:null},{cssClass:"bp",type:"BP",icon:"petrolStationIcon.png",clusterClass:"petrolstationCluster",showStatus:false,shapeLayer:null},{cssClass:"saab",type:"Saab",icon:"saabIcon.png",clusterClass:"saabCluster",showStatus:false,shapeLayer:null},{cssClass:"viewpoint",type:"Viewpoint",icon:"viewpointIcon.png",clusterClass:"viewpointCluster",showStatus:false,shapeLayer:null},{cssClass:"castle",type:"Castle",icon:"castleIcon.png",clusterClass:"castleCluster",showStatus:false,shapeLayer:null},{cssClass:"statelyhome",type:"Stately home",icon:"statelyhomeIcon.png",clusterClass:"statelyhomeCluster",showStatus:false,shapeLayer:null},{cssClass:"historicalmonument",type:"Historical Monument",icon:"cameraIcon.png",clusterClass:"cameraCluster",showStatus:false,shapeLayer:null},{cssClass:"children",type:"Children",icon:"childrenIcon.png",clusterClass:"childrenCluster",showStatus:false,shapeLayer:null},{cssClass:"picnic",type:"Picnic",icon:"picnicIcon.png",clusterClass:"picnicCluster",showStatus:false,shapeLayer:null},{cssClass:"restaurant",type:"Restaurant",icon:"restaurantIcon.png",clusterClass:"restaurantCluster",showStatus:false,shapeLayer:null},{cssClass:"bar",type:"Bar",icon:"barIcon.png",clusterClass:"barCluster",showStatus:false,shapeLayer:null},{cssClass:"cafe",type:"Cafe",icon:"cafeIcon.png",clusterClass:"cafeCluster",showStatus:false,shapeLayer:null},{cssClass:"hotel",type:"Hotel",icon:"hotelIcon.png",clusterClass:"hotelCluster",showStatus:false,shapeLayer:null});function getConfigByType(type)
{var ret;$.each(viewTypesConfig,function(index,obj){if(obj.type.toLowerCase()==type.toLowerCase())
{ret=obj;return;}});return ret;}
function getConfigByClass(cssClass)
{var ret;$.each(viewTypesConfig,function(index,obj){if(obj.cssClass==cssClass)
{ret=obj;return;}});return ret;}
var NE=new VELatLong(58,2.13931);var SW=new VELatLong(50,-8.13931);var CENTRE_POINT=new VELatLong((NE.Latitude+SW.Latitude)/2,(NE.Longitude+SW.Longitude)/2);var CENTRE_ZOOM=5;var pinPoint=null;var pinPixel=null;var mapPlacesData=new Object();var routePlacesData=new Object();var allHotelData=new Object();var clusterList=new Array();var ROOT="http://www.mrandmrssmith.com";function initMap(onLoadMapFunction,token)
{map=new VEMap('smithMap');if(token!=null)
{map.AttachEvent('ontokenexpire',onHandleTokenExpire);map.AttachEvent('ontokenerror',onHandleTokenError);map.SetClientToken(token);}
map.AttachEvent("onstartzoom",showLoader);map.AttachEvent("onendzoom",onEndZoom);map.AttachEvent("onresize",onResize);map.onLoadMap=onLoadMapFunction;map.LoadMap(CENTRE_POINT,CENTRE_ZOOM,VEMapStyle.Road,false,VEMapMode.Mode2D,true,1);for(var i=0;i<viewTypesConfig.length;i++)
{var config=viewTypesConfig[i];config.showStatus=false;config.shapeLayer=new VEShapeLayer();config.shapeLayer.SetTitle(config.type+" Shape Layer");map.AddShapeLayer(config.shapeLayer);}
map.ClearInfoBoxStyles();map.HideDashboard();initVerifyQueue();checkInitalDestinations();sliderSetToZoom(CENTRE_ZOOM);}
function onHandleTokenExpire()
{alert("onHandleTokenExpire");}
function onHandleTokenError(error)
{trace("onHandleTokenError: ");for(var prop in error)
{trace(prop+" -> "+error[prop]);}}
function hidePlacePins(cssClass)
{var config=getConfigByClass(cssClass);if(config!=null)
{config.showStatus=false;clusterList=removeTypeFromClusters(clusterList,config.type);displayIcons();}}
function showPlacePins(cssClass)
{var config=getConfigByClass(cssClass);if(config!=null)
{config.showStatus=true;getMapPlaces();}}
function resetMapFeatures()
{$('#DropOffPoints a').each(function(){if($(this).parent().hasClass('live')==true)$(this).parent().removeClass('live');});}
function showItinerary()
{$("#itinerary").html(drawItinerarySummary());}
function hideItinerary()
{$("#itinerary").html("");}
function getMapPlaces()
{var tTypes=new Array();$.each(viewTypesConfig,function(key,config){if(config.showStatus)tTypes.push(config.type);});if(tTypes.length>0)loadMapPlaces(onPlacesLoad,tTypes);}
function onPlacesLoad(data)
{mapPlacesData=data;$.each(routePlacesData,function(id,item){mapPlacesData[id]=item;});onDataLoad(data);}
function onDataLoad(data)
{clusterList=clusterPins(data);displayIcons();}
function displayIcons()
{$.each(viewTypesConfig,function(index,config){if(config.shapeLayer)config.shapeLayer.DeleteAllShapes();});$.each(clusterList,function(index,cluster)
{if(cluster==null||cluster.items.length==0)
{}
else if(cluster.items.length==1)
{var key=cluster.items[0];var item=mapPlacesData[key];var shapeLayer=getConfigByType(item.type).shapeLayer;var tPinLatLong=new VELatLong(item.lat,item.lng);var tShape=createPlaceIcon(tPinLatLong,item,key);shapeLayer.AddShape(tShape);item.shape=tShape;}
else
{var shapeLayer=getConfigByType(cluster.type).shapeLayer;var tPinLatLong=cluster.LatLong;var tShape=new VEShape(VEShapeType.Pushpin,tPinLatLong);var iconHTML='<div class="placePin"><img src="_include/img/icons/clusterIcon.png" alt="Cluster" /></div>';tShape.SetCustomIcon(iconHTML);shapeLayer.AddShape(tShape);cluster.shape=tShape;var max_width=Math.ceil(Math.sqrt(cluster.typesLength));var tDesc='<div id="ClusterPopup" onclick="zoomInCluster('+index+')" class="clearfix">';tDesc+='<table cellpadding="0" cellspacing="0" border="0">';var tClasses;var ct=0;$.each(cluster.typeCount,function(type,count)
{var rowStart=(ct%max_width==0)?true:false;var rowEnd=(ct%max_width==max_width-1||ct==cluster.typesLength-1)?true:false;var typeClass=getConfigByType(type).clusterClass||"hotelCluster";if(rowStart)tDesc+='<tr>';tClasses='clusterCluster '+typeClass+((rowEnd)?' endCluster':'');tDesc+='<td><span class="'+tClasses+'">x'+count+'</span></td>';if(rowEnd)tDesc+='</tr>';ct++;});tDesc+='</table></div>';tShape.SetDescription(tDesc);}});}
function createPlaceIcon(pinLatLong,placeData,key)
{try
{var shape=new VEShape(VEShapeType.Pushpin,pinLatLong);decorateShape(shape,placeData,key);}
catch(e)
{trace("ERROR: createPlaceIcon, "+e.Message);}
return shape;}
function decorateShape(shape,placeData,key)
{var imgPng=getConfigByType(placeData.type).icon||"hotelIcon.png";var tImgPath=(map.GetZoomLevel()<9)?"_include/img/icons/small/"+imgPng:"_include/img/icons/"+imgPng;var iconHTML='<div class="placePin"><img src="'+tImgPath+'" alt="'+placeData.name+'" /></div>';shape.SetCustomIcon(iconHTML);shape.SetTitle('');var canAdd=(routePlacesData[key]==undefined)?true:false;updateDescription(shape,placeData,key,canAdd);}
function updateDescription(shape,placeData,key,canAdd)
{var tPopupHtml='<div id="HotelPopup" class="clearfix">';var description;switch(placeData.type)
{case"Hotel":description='<ul>';var i=1;while(placeData["highlight_"+i])
{description+='<li>'+placeData["highlight_"+i]+'</li>';i++;}
description+='</ul>';tPopupHtml+=createPlacePopupHtml(key,placeData.type,placeData.name,placeData.image,description,placeData.address,null,true,true);break;case"Destination":description='<h3>About</h3><p>'+placeData.desc+'</p>';description+='<p><b>'+placeData.cityscape_title+'</b> : '+placeData.cityscape+'</p>';description+='<p><b>'+placeData.citylife_title+'</b> : '+placeData.citylife+'</p>';tPopupHtml+=createPlacePopupHtml(key,placeData.type,placeData.name,placeData.image,description,null,null,true,false);break;default:tPopupHtml+=createPlacePopupHtml(key,placeData.type,placeData.name,placeData.image,placeData.description,placeData.address,null,false,false);break;}
tPopupHtml+='<div class="hotelBase clearfix">';if(canAdd==true){tPopupHtml+="<span id=\"addToRouteButton\" onclick=\"addPlaceToRoute('"+key+"')\"></span> ";}else{tPopupHtml+="<span id=\"removePlaceFromRouteButton\" onclick=\"removePlaceFromRoute('"+key+"')\"></span> ";}
tPopupHtml+="<span id=\"zoomToStreetButton\" onclick=\"zoomToStreet('"+key+"')\"></span>";tPopupHtml+='</div>';tPopupHtml+="</div>";shape.SetDescription(tPopupHtml);}
function createPlacePopupHtml(id,type,name,image,description,address,telephone,showFindMore,showBooking)
{var tPopupHtml;if(image)
{tPopupHtml='<div class="hotelLeft clearfix">';tPopupHtml+='<div class="hotelImage"><img src="'+ROOT+image+'" alt="'+name+'"/></div>';tPopupHtml+='<div class="hotelInfoButtons">';if(showFindMore)tPopupHtml+="<p class=\"button\"><span id=\"findOutMoreButton\" onclick=\"findOutMore('"+id+"','"+type+"')\"></span></p>";if(showBooking)tPopupHtml+="<p class=\"button\"><span id=\"bookNowFromRoute\" onclick=\"bookNow('"+id+"','"+type+"')\"></span></p>";tPopupHtml+='</div>';tPopupHtml+='</div>';tPopupHtml+='<div class="hotelRight hotelInfo clearfix">';tPopupHtml+='<h2>'+name+'</h2>';if(description)tPopupHtml+=description;if(address)tPopupHtml+='<h3>Address</h3><span class="hotelAddress">'+address.split(",").join('<br/>')+'</span>';if(telephone)tPopupHtml+='<h3>Telephone:</h3><span>'+telephone+'</span>';tPopupHtml+='</div>';}
else
{tPopupHtml='<div class="hotelCentre hotelInfo clearfix">';tPopupHtml+='<h2>'+name+'</h2>';if(description)tPopupHtml+=description;if(address)tPopupHtml+='<h3>Address</h3><span class="hotelAddress">'+address.split(",").join('<br/>')+'</span>';if(telephone)tPopupHtml+='<h3>Telephone:</h3><span>'+telephone+'</span>';tPopupHtml+='<br/><br/>';if(showFindMore)tPopupHtml+="<span id=\"findOutMoreButton\" onclick=\"findOutMore('"+id+"','"+type+"')\"></span> ";if(showBooking)tPopupHtml+="<span id=\"bookNowFromRoute\" onclick=\"bookNow('"+id+"','"+type+"')\"></span>";tPopupHtml+='</div>';}
return tPopupHtml;}
function addPlaceToRoute(id)
{if(destinations.length>0){addToRoutePlacesData(id,mapPlacesData[id]);var tDestinations=insertPlaceIntoRoute(mapPlacesData[id],id);drawRouteUI(tDestinations);}else{if($("#hotelListSelect0 option[@selected]").val()==0)
{setStartValue("",id);}else{setEndValue("",id);}}
updateDescription(routePlacesData[id].shape,routePlacesData[id],id,false);}
function removePlaceFromRoute(id)
{var placeData=routePlacesData[id];var shape=placeData.shape;var config=getConfigByType(placeData.type);if(config.showStatus==false){shape.Hide();}else{updateDescription(shape,placeData,id,true);}
delete routePlacesData[id];var removed_destination=null;for(var i=0;i<destinations.length;i++)
{if(destinations[i]==id)
{removed_destination=destinations.splice(i,1);break;}}
drawRouteUI(destinations);}
function findOutMore(id)
{var item=mapPlacesData[id];var uri=ROOT+item.link;window.open(uri,"_blank");}
function bookNow(id)
{var item=mapPlacesData[id];var uri=ROOT+item.booking_link;window.open(uri,"_blank");}
function zoomToStreet(id)
{var item=mapPlacesData[id];var pt=new VELatLong(item.lat,item.lng);map.SetCenterAndZoom(pt,19);}
function zoomInCluster(index)
{trace('LM-MAP: zoomInCluster('+index+')');var cluster=clusterList[index];var tLatLong=cluster.LatLong;var tZoom=Math.min(19,map.GetZoomLevel()+2);map.SetCenterAndZoom(tLatLong,tZoom);}
function getInfo()
{var info='The top edge of the map on the Web page is at pixel: '+map.GetTop()+"\n";info+='The left edge of the map on the Web page is at pixel: '+map.GetLeft()+"\n";var ct=map.GetCenter();info+='The latitude,longitude at the center of the map is: '+map.GetCenter().Latitude+'�N '+map.GetCenter().Longitude+"�E\n";info+='The current zoom level of the map is: '+map.GetZoomLevel()+"\n";info+='The map control version is: '+VEMap.GetVersion()+"\n";trace(info);}
var PAN_PIXELS=50;function mapPanLeft()
{map.Pan(-PAN_PIXELS,0);}
function mapPanRight()
{map.Pan(PAN_PIXELS,0);}
function mapPanUp()
{map.Pan(0,-PAN_PIXELS);}
function mapPanDown()
{map.Pan(0,PAN_PIXELS);}
function mapCentre()
{map.SetMapView([NE,SW]);map.AttachEvent("onchangeview",onMapCenter);}
function onMapCenter()
{showApp();}
function mapZoomIn()
{map.ZoomIn();}
function mapZoomOut()
{map.ZoomOut();}
function mapRoad()
{map.SetMapStyle(VEMapStyle.Road);}
function mapArial()
{map.SetMapStyle(VEMapStyle.Aerial);}
function mapMixed()
{map.SetMapStyle(VEMapStyle.Hybrid);}
function onEndZoom()
{hideLoader();sliderSetToZoom(map.GetZoomLevel());getMapPlaces();}
function onEndPan()
{hideLoader();getMapPlaces();}
function onResize()
{map.DetachEvent("onresize",onResize);mapCentre();}
var viaDestinations;var firstTime=true;var tokenInterval;$(document).ready(init);function init()
{hideApp();startTokenLoad();}
function startTokenLoad()
{var f=function(){loadTokenData(onLoadToken)};tokenInterval=setInterval(f,3000);f();}
function onLoadToken(data)
{if(tokenInterval!=null)
{clearInterval(tokenInterval);tokenInterval=null;trace("onLoadToken");if(data.GetClientTokenResult)
{initSmithRoutes();initInterface();initMap(onLoadMap,data.GetClientTokenResult);}
else
{startTokenLoad();}}}
function initRoute()
{initPage();var destinations=$.getURLParam("destinations");var avoidMWays=$.getURLParam("avoid_motorways")||false;parseDestinationsAndDrawRoute(destinations,avoidMWays);}
function parseDestinationsAndDrawRoute(destinations)
{trace("LM_INIT parseDestinationsAndDrawRoute ["+destinations+"]");if(destinations!=null&&destinations!=""&&destinations.length>0)
{firstTime=true;resetUI();var destinationsArray=String(destinations).split("|");var keys=new Array();viaDestinations=new Array();for(var i=0;i<destinationsArray.length;i++)
{var str=destinationsArray[i].toString();var keyPair=extractKeyValue(str);if(keyPair!=null)
{keys.push(keyPair.key);viaDestinations.push({id:keyPair.key,name:keyPair.key,data:null});}
else
{viaDestinations.push({id:null,name:unescape(destinationsArray[i]),data:null});}}
trace("viaDestinations.length = "+viaDestinations.length);if(keys.length>0)
{loadMapPlacesForKeys(onLoadMapPlacesForKeys,keys.join(","));}
else
{addDestinationsToUI();}}}
function onLoadMap(data)
{hideLoader();}
function onLoadMapPlacesForKeys(data)
{trace("onLoadMapPlacesForKeys START");$.each(data,function(key,place)
{var tPlaceIndex=getPlaceIndexByKey(key);if(tPlaceIndex!=-1)
{viaDestinations[tPlaceIndex].name=place.name;viaDestinations[tPlaceIndex].data=place;}});trace("onLoadMapPlacesForKeys END");addDestinationsToUI();}
function addDestinationsToUI()
{var tCurrentLocation;for(var i=0;i<viaDestinations.length;i++)
{tCurrentLocation=viaDestinations[i];if(i==0)
{setStartValue(tCurrentLocation.name,tCurrentLocation.id);}
else if(i==viaDestinations.length-1)
{setEndValue(tCurrentLocation.name,tCurrentLocation.id);}
else
{addDestinationToUI(tCurrentLocation.id,tCurrentLocation.name,tCurrentLocation.data,true);}}
forceViaDestinationControl(onForceViaDestinationControl);}
function onForceViaDestinationControl()
{if(firstTime)
{firstTime=false;doRouteFromUI(null,true);}}
function getPlaceIndexByKey(key)
{var index=-1;for(var i=0;i<viaDestinations.length;i++)
{if(key==viaDestinations[i].id)
{index=i;break;}}
return index;}
function initInterface()
{attachInitBehaviours();}
var isValidating=false;var isLoading=false;var validateWhenReady=false;var viaDestinationCount=0;var sliderHeight;var errors=new Array();function attachInitBehaviours()
{$('#viaDestinations span.add-destination').css({cursor:'pointer'}).click(function(){addDestination($(this));});$("#customRouteForm").submit(doRouteFromUI);$('#addNewDestinationButton').click(function(event){showViaDestinationControl();});$("span[id$='Button']").css("cursor","pointer");$("#showMapInfoButton").click(function(event){getInfo();});$("#SendToFriendButton").click(function(event){getDeepLinkURL();});getHotelsDropDown();initSlider();}
function doRouteFromUI(event,stopUIRedraw)
{$('#ShowRouteButton').attr('src','_include/img/global/forms/UpdateMyRouteButton.gif');try
{event.preventDefault();}catch(e)
{}
if(!isValidating)
{validateWhenReady=false;var form=this;var isValid=true;var destinations=new Array();$.each(routePlacesData,function(id,data){data.count=0;});isValid&=insertStartOrEndHotel(true,destinations,stopUIRedraw);$('#DestinationsList li').each(function()
{var destination=$(this)[0].className;if(destination!="")
{if(destination.indexOf('_')!=-1)addToRoutePlacesData(destination);destinations.push(destination);}});isValid&=insertStartOrEndHotel(false,destinations,stopUIRedraw);$.each(routePlacesData,function(id,data){if(data.count==0)
{delete routePlacesData[id];}});drawRouteUI(destinations,stopUIRedraw);}
else
{validateWhenReady=true;}}
function insertStartOrEndHotel(isStart,destinations,stopUIRedraw)
{var no=(isStart)?0:1;var isValid=true;var selectedId=$("#hotelListSelect"+no+" option[@selected]").val();var locationInput=$("#customRouteForm").find('input[@name=destination'+no+']');if(selectedId!=0&&selectedId!=undefined)
{addToRoutePlacesData(selectedId);destinations.push(selectedId);}
else
{isValid=(isRouteValidated(locationInput)&&notEmptyOrDefault(locationInput))?true:false;if(isValid)destinations.push($(locationInput).val());}
var ErrorMessage=(isStart)?"Please enter a valid Start Location or Hotel":"Please enter a valid Finish Location or Hotel";if(!isValid)
{errors.push(ErrorMessage);}
return isValid;}
function getHotelsDropDown()
{loadAllMapPlaces(onHotelDropDownDataLoad);}
function onHotelDropDownDataLoad(data)
{allHotelData=data;var tOptions=getSelectOptions(data,"Choose a Smith hotel ...");$("select#hotelListSelect0").html(tOptions);$("select#hotelListSelect1").html(tOptions);$("select#viaDestinationHotel").html(tOptions);initCustomSelects();initRoute();}
function getSelectOptions(data,firstOption)
{var tOptions='';tOptions='<option value="0">'+firstOption+'</option>';$.each(data,function(key,item)
{tOptions+='<option value="'+key+'">'+item.name+'</option>';});return tOptions;}
function resetUI()
{$("#DestinationsList").html("");$("#viaDestinations").removeClass('live');$("form[@id^=customRouteForm]").find("input[@name^='destination']").each(function(){this.value=this.defaultValue;setValidStatus(this)});$customSelect[0].reset();$customSelect[1].reset();$customSelect[2].reset();viaDestinationCount=0;$(".slide-trigger:first").click();}
function drawRouteUI(destinations,stopUIRedraw)
{if(errors.length!=0)
{var tErrorMessage="<p>"+errors.join("<br />")+"</p>";showInfoPopup("Error",tErrorMessage);errors=new Array();}
else
{hideInfoPopup();for(var i=0;i<destinations.length;i++)
{}
if(!stopUIRedraw)
{if(!$('#Accordian a.slide-trigger:first').hasClass('slide-selected'))$('#Accordian').accordion("activate",0);$("#DestinationsList").html("");for(var i=1;i<destinations.length-1;i++)
{var id=destinations[i];var tPlaceData=routePlacesData[id];if(tPlaceData!=undefined)
{addDestinationToUI(id,tPlaceData.name,tPlaceData);}else
{addDestinationToUI(null,id,null);}}}
showRoute(destinations);}}
function addDestination($addButton)
{var $viaDestinations=$addButton.parent();var destinationInput=$viaDestinations.find("input[@name=viaDestinationText]");var destinationName=destinationInput.val();var id=$viaDestinations.find("select option[@selected]").val();destinationInput.text("");var tCustomSelect=$customSelect[2];tCustomSelect.reset();addDestinationToUI(id,destinationName)}
function addDestinationToUI(id,destinationName,data,stopResize)
{var tViaPanel=$('#viaDestinations');var tViaPanelContent=tViaPanel.parents().find('.slide-content:first');if(id!="0"&&id!=null&&id!=undefined)
{var hotelData=(data!=undefined)?data:allHotelData[id];addToRoutePlacesData(id,data);var prefix=(hotelData.type.toLowerCase()=="hotel")?"Hotel":"Place";var newDestinationHTML='<li class=\"'+id+'"\">'+prefix+': '+hotelData.name+'<input type=\"hidden\" name=\"viaDestinationText\" value=\"'+id+'\" /><span class=\"remove-via-button\"></span></li>';$('#DestinationsList').append(newDestinationHTML).find('.remove-via-button').css({cursor:'pointer'}).click(function(){removeDestinationFromUI($(this).parent().attr("class"),$(this).parent())});}
else if(destinationName!='')
{var newDestinationHTML='<li class=\"'+destinationName+'"\">'+destinationName+'<input type=\"hidden\" name=\"viaDestinationText\" value=\"'+destinationName+'\" /><span class=\"remove-via-button\"></span></li>';$('#DestinationsList').append(newDestinationHTML).find('.remove-via-button').css({cursor:'pointer'}).click(function(){removeDestinationFromUI($(this).parent().attr("class"),$(this).parent())});tViaPanel.find("input[@name=viaDestinationText]")[0].value='';}
if(!stopResize)
{tViaPanelContent.stop().animate({height:$('#customRouteForm').height()},400,"linear");}
viaDestinationCount++;}
function removeDestinationFromUI(id,viaElement)
{viaDestinationCount--;viaElement.remove();removeFromRoutePlacesData(id);var tSlide=$('#viaDestinations').parents().find('.slide-content:first');tSlide.stop().animate({height:$('#customRouteForm').height()},400,"linear");}
function addToRoutePlacesData(id,data)
{if(!data)
{if(routePlacesData[id]!=null)
{data=routePlacesData[id];}
else if(mapPlacesData[id]!=null)
{data=mapPlacesData[id];}
else if(allHotelData[id]!=null)
{data=allHotelData[id];}
else
{}}
try
{routePlacesData[id]=data;if(routePlacesData[id].count==null)
{routePlacesData[id].count=1;}
else
{routePlacesData[id].count++;}}catch(e)
{}}
function removeFromRoutePlacesData(id)
{try
{routePlacesData[id].count--;if(routePlacesData[id].count==0)
{delete routePlacesData[id];}}catch(e)
{}}
function setStartValue(value,id)
{var input=$("#customRouteForm").find('input[@name=destination0]');if(id!=null&&id.indexOf("hotel_")==0)
{$("#hotelListSelect0 option").each(function(i){if($(this).val()==id){$(this).attr('selected','selected');}});addToRoutePlacesData(id);$("#RenderedSelect0 div input").val(routePlacesData[id].name);input.val("");}
else
{input.val(value);}
if(notEmptyOrDefault(input))
{setValidStatus(input,true);}
else
{setValidStatus(input);}}
function setEndValue(value,id)
{var input=$("#customRouteForm").find('input[@name=destination1]');if(id!=null&&id.indexOf("hotel_")==0)
{$("#hotelListSelect1 option").each(function(i){if($(this).val()==id){$(this).attr('selected','selected');}});addToRoutePlacesData(id);$("#RenderedSelect1 div input").val(routePlacesData[id].name);input.val("");}
else
{input.val(value);}
if(notEmptyOrDefault(input))
{setValidStatus(input,true);}
else
{setValidStatus(input);}}
function showViaDestinationControl()
{if(!$("#viaDestinations").hasClass("live"))
{$('#addNewDestinationButton').css({cursor:'default'}).click(function(){});$('#addNewDestinationButton').text("via");$("#viaDestinations").addClass('live');var tSlide=$("#viaDestinations").parents().find('.slide-content:first');tSlide.stop().animate({height:$('#customRouteForm').height()+(viaDestinationCount*25)+61},600,function()
{$("#viaDestinations").stop().animate({opacity:'show'},800,"linear");$('#DestinationsList').stop().show();});}}
function forceViaDestinationControl(callbackFunction)
{var $viaDestinations=$("#viaDestinations");if(!$viaDestinations.hasClass("live"))
{$('#addNewDestinationButton').css({cursor:'default'}).click(function(){});$('#addNewDestinationButton').text("Destinations");$viaDestinations.addClass('live');var tSlide=$viaDestinations.parents().find('.slide-content:first');tSlide.stop().animate({height:296+(viaDestinationCount*30)+61},1000,"linear",function()
{$viaDestinations.stop().animate({opacity:'show'},800,"linear");$('#DestinationsList').stop().show();callbackFunction();});}}
function showLoader(message)
{isLoading=true;var $Loader=$('#Loader');var w=890;var h=$(window).height();var loaderWidth=w-Config.interfaceWidth;var loaderHeight=h-Config.headerHeight;$Loader.css({width:loaderWidth,height:loaderHeight});$('.loader-background',$Loader).css({background:'#000000',opacity:'0.7',height:'100%',width:'100%'});$('.loader-content',$Loader).css({position:'absolute',top:(loaderHeight/2-60),left:(loaderWidth/2-110)});$Loader.animate({opacity:'show'},100);}
function hideLoader(message)
{isLoading=false;$("#Loader").animate({opacity:'hide'},100);}
function showInfoPopup(title,message)
{var tPopup=$('#Popup');var w=890;var h=$(window).height();var loaderWidth=w-Config.interfaceWidth;var loaderHeight=h-Config.headerHeight;tPopup.css({width:loaderWidth,height:loaderHeight});$('.loader-background',tPopup).css({background:'#000000',opacity:'0.7',height:'100%',width:'100%'});$('.popup-content',tPopup).css({color:'#b2a65f',background:"#232011",width:"400px",position:'absolute',top:(loaderHeight/2-100),left:(loaderWidth/2-200),padding:'0 20px 20px 20px',border:'1px #524c28 solid'});$('.popup-content h2').text(title);$('.popup-content h2').css({color:'#c7dc39',fontSize:'14px',fontWeight:'bold',paddingTop:'10px'});$('.popup-content #messageBody').html(message);tPopup.click(hideInfoPopup).css("cursor","pointer");tPopup.animate({opacity:'show'},100);}
function hideInfoPopup()
{$("#Popup").animate({opacity:'hide'},100);}
function checkInitalDestinations()
{enableSubmit();$("form[@id^=customRouteForm]").find("input[@name^='destination']").each(function(event){verifyLocation(this,true);});$("form[@id^=customRouteForm]").find("input[@name^='destination']").blur(function(event){if(!notEmptyOrDefault(this))
{this.value=this.defaultValue;setValidStatus(this);clearDisambigIfCurrent(this);}
else if(isRouteValidated(this))
{setValidStatus(this,true);clearDisambigIfCurrentDelayed(this);}
else if(!isRouteValidated(this))
{setValidStatus(this,false);}});$("form[@id^=customRouteForm]").find("input[@name^='destination']").focus(function(event){if(!isRouteValidated(this))setValidStatus(this);if(!notEmptyOrDefault(this))
{this.value="";}else{verifyLocation(this);}});$("form[@id^=customRouteForm]").find("input[@name^='destination']").keyup(function(event){verifyLocation(this);});$("form[@id^=customRouteForm]").find("input[@name='viaDestinationText']").keyup(function(event){verifyLocation(this);});}
function disableSubmit()
{isValidating=true;$("#customRouteForm").find("input[@type='submit']").val("Validating...");}
function enableSubmit()
{isValidating=false;$("#customRouteForm").find("input[@type='submit']").val("Submit");}
function initSlider()
{var track=$("#zoom-track");var grab=$("#zoom-pointer");sliderHeight=track.innerHeight()-grab.outerHeight();var options={axis:"y",stop:sliderDragged,containment:track};grab.draggable(options);}
function sliderDragged(e,ui)
{var zoom=19-Math.floor(19*ui.position.top/sliderHeight);map.SetZoomLevel(zoom);}
function sliderSetToZoom(zoom)
{var offset=(19-zoom)*sliderHeight/(19);$("#zoom-pointer").css("top",offset);}
function getDeepLinkURL()
{var destinations=new Array();if($("#hotelListSelect0 option[@selected]").val()!=0)
{var id=$("#hotelListSelect0 option[@selected]").val();destinations.push("{"+id+"}"+routePlacesData[id].name);}
else
{destinations.push($("#customRouteForm").find('input[@name=destination0]').val());}
if($("#viaDestinations").hasClass('live')==true)
{$('#DestinationsList li').each(function(){var destination=$(this)[0].className;destinations.push(destination);});}
if($("#hotelListSelect1 option[@selected]").val()!=0)
{var id=$("#hotelListSelect1 option[@selected]").val();destinations.push("{"+id+"}"+routePlacesData[id].name);}
else
{destinations.push($("#customRouteForm").find('input[@name=destination1]').val());}
var tResult=destinations.join("|");var tLink=window.location.protocol+"//"+window.location.host+window.location.pathname+"?destinations="+tResult;tURL="/send-to-a-friend?link="+escape(tLink);tProps='width='+400+',height='+440+',status=no,scrollbars=no,resizable=no,location=no,menubar=no,dependent=yes';var msgText="Please cut and paste the link below into your browser to upload and access your Mr & Mrs Smith route";var win=window.open(tURL,"sendFriend",tProps);try{win.document.getElementById("message").value=msgText;}
catch(err)
{}}
function showUILoader()
{}
function hideUILoader()
{}
function hideApp()
{$("#smithMap").css({display:"none"});}
function showApp()
{$("#smithMap").show();}
var destinations=new Array();var currentShowRouteControl=null;var avoidMotorWays=false;function showRoute(destinations)
{trace("showRoute destinations=["+destinations+"]");$.each(routePlacesData,function(id,data){trace("LM-MAP-ROUTE::showRoute routePlacesData id: "+id+", data: "+data);});showLoader();$('#RouteLoader').show();var tDestinations=new Array();for(var i=0;i<destinations.length;i++)
{tPlaceLocation=destinations[i];var tPlaceData=routePlacesData[tPlaceLocation];if(tPlaceData)
{tPlaceLocation=new VELatLong(tPlaceData.lat,tPlaceData.lng);}
else
{tPlaceLocation=intoUk(tPlaceLocation);}
tDestinations.push(tPlaceLocation);}
this.destinations=destinations;if(avoidMotorWays)
{getMapPointData(tDestinations);}
else
{currentShowRouteControl=new ShowRouteControl(tDestinations);}}
function ShowRouteControl(destinationsList,route)
{this.noChunks=Math.ceil(destinationsList.length/25);trace("new ShowRouteControl "+destinationsList.length+" -> "+this.noChunks);this.currentChunk=0;this.chunks=new Array(this.noChunks);this.route=(route!=undefined)?route:null;this.willDraw=(this.noChunks==1)?true:false;for(var i=0;i<this.noChunks;i++)
{var st=i*25;var ed=((i+1)*25<destinationsList.length)?(i+1)*25:destinationsList.length;var tDestList=destinationsList.slice(st,ed);this.chunks[i]=new ShowRouteChunk(tDestList,this,i);}
this.nextChunk=function()
{this.chunks[this.currentChunk++].GetDirections();};this.startShape=null;this.endShape=null;this.SetStartShape=function(latlong,text)
{this.startShape=new VEShape(VEShapeType.Pushpin,latlong);this.startShape.SetDescription(text);decorateStartShape(this.startShape);};this.SetEndShape=function(latlong,text)
{this.endShape=new VEShape(VEShapeType.Pushpin,latlong);this.endShape.SetDescription(text);decorateEndShape(this.endShape);};this.shape;this.addShapePoints=function(shapePoints)
{trace("ShowRouteControl::addShapePoints "+this.shape+" "+shapePoints.length);if(!this.shape)
{this.shape=new VEShape(VEShapeType.Polyline,shapePoints);this.shape.SetLineColor(new VEColor(119,219,57,0.7));this.shape.SetLineWidth(4);this.shape.SetCustomIcon('');}
else{this.shape.SetPoints(this.shape.GetPoints().concat(shapePoints));}
trace("ShowRouteControl::addShapePoints points =  "+this.shape.GetPoints().length);};this.drawRoute=function()
{trace("ShowRouteControl::drawRoute");var layer=map.GetShapeLayerByIndex(0);layer.DeleteAllShapes();if(!this.willDraw)
{trace(" - "+this.shape.GetPoints().length);layer.AddShape(this.shape);map.SetMapView(this.shape.GetPoints());if(this.startShape)layer.AddShape(this.startShape);if(this.endShape)layer.AddShape(this.endShape);}};this.clearRoute=function()
{var layer=map.GetShapeLayerByIndex(0);layer.DeleteAllShapes();};this.nextChunk();}
function ShowRouteChunk(destinationsList,control,index)
{trace("new ShowRouteChunk index="+index+" control="+control+" destinationsList.length"+destinationsList.length);this.destinations=destinationsList;this.control=control;this.hasStart=(index==0)?true:false;this.hasEnd=(index==this.control.noChunks-1)?true:false;this.willDraw=(this.hasStart&&this.hasEnd)?true:false;this.routeOptions=new VERouteOptions();var thisObj=this;this.routeOptions.RouteCallback=function(route)
{trace("onChunkShowRoute.onShowRoute thisObj.hasStart = "+thisObj.hasStart+" thisObj.hasEnd = "+thisObj.hasEnd);onShowRoute(route,thisObj);};this.routeOptions.DrawRoute=this.willDraw;this.routeOptions.SetBestMapView=this.willDraw;this.routeOptions.DistanceUnit=VERouteDistanceUnit.Mile;this.routeOptions.ShowDisambiguation=false;this.routeOptions.RouteColor=new VEColor(119,219,57,0.7);this.routeOptions.RouteWeight=4;this.GetDirections=function()
{map.GetDirections(thisObj.destinations,thisObj.routeOptions);};}
function onShowRoute(route,obj)
{trace("onShowRoute "+route+" "+obj+" - "+obj.control+" "+obj.hasStart+" "+obj.hasEnd);var leg;var shape;var item;if(route!=undefined)
{for(var i=0;i<route.RouteLegs.length;i++)
{leg=route.RouteLegs[i];for(var j=0;j<leg.Itinerary.Items.length;j++)
{item=leg.Itinerary.Items[j];shape=item.Shape;if(i==0&&j==0&&obj.hasStart)
{obj.control.SetStartShape(item.LatLong,item.Text);if(shape)
{decorateStartShape(shape);}}
else if(i==route.RouteLegs.length-1&&j==leg.Itinerary.Items.length-1&&obj.hasEnd)
{obj.control.SetEndShape(item.LatLong,item.Text);if(shape)
{decorateEndShape(shape);}}
else
{if(shape)shape.Hide();}}}}
obj.control.addShapePoints(route.ShapePoints);if(obj.hasEnd)
{hideLoader();hideRouteLoader();if(obj.willDraw)obj.control.route=route;obj.control.drawRoute();}
else
{obj.control.nextChunk();}}
function decorateStartShape(shape)
{tKey=destinations[0];tPlaceData=routePlacesData[tKey];if(tPlaceData)
{shape.SetTitle("");updateDescription(shape,tPlaceData,tKey,false);tAlt="Start: "+tPlaceData.name;}
else
{shape.SetTitle(tKey);tAlt="Start: "+tKey;}
shape.SetCustomIcon('<div class="journeyPin"><img src="_include/img/icons/start.png" alt="'+tAlt+'" /></div>');}
function decorateEndShape(shape)
{tKey=destinations[destinations.length-1];tPlaceData=routePlacesData[tKey];if(tPlaceData)
{shape.SetTitle("");updateDescription(shape,tPlaceData,tKey,false);tAlt="End: "+tPlaceData.name;}
else
{shape.SetTitle(tKey);tAlt="End: "+tKey;}
shape.SetCustomIcon('<div class="journeyPin"><img src="_include/img/icons/end.png" alt="'+tAlt+'" /></div>');}
function hideRouteLoader(){$('#RouteLoader').hide();}
function getCurrentDestinations()
{return this.destinations;}
function getCurrentRoute()
{return currentShowRouteControl.route;}
function getMapPointData(destinations)
{var destinationsString="";$.each(destinations,function(index,dest){if(dest instanceof VELatLong)
{destinationsString+=dest.Longitude+":"+dest.Latitude;}
else
{destinationsString+=dest;}
if(index<destinations.length-1)destinationsString+="|";});loadMapPointData(onGetMapPointData,destinationsString,true);}
function onGetMapPointData(mapPointData)
{var latLongList=mapPointToLatLongList(mapPointData);var route=mapPointToRoute(mapPointData);currentShowRouteControl=new ShowRouteControl(latLongList,route);}
function mapPointToLatLongList(mapPointData)
{var latLongList=new Array();var mpItinerary=mapPointData.CalculateRouteResult.Itinerary;$.each(mpItinerary.Segments.Segment,function(segIndex,mpSegment){if(typeof(mpSegment.Directions.Direction[0])=="object")
{$.each(mpSegment.Directions.Direction,function(dirIndex,mpDirection){latLongList.push(new VELatLong(Number(mpDirection.LatLong.Latitude),Number(mpDirection.LatLong.Longitude)));});}
else
{var tDirection=mpSegment.Directions.Direction;latLongList.push(new VELatLong(Number(tDirection.LatLong.Latitude),Number(tDirection.LatLong.Longitude)));}});return latLongList;}
function mapPointToRoute(mapPointData)
{var route=new VERoute();var mpItinerary=mapPointData.CalculateRouteResult.Itinerary;route.Distance=mpItinerary.Distance;route.Time=mpItinerary.TripTime;$.each(mpItinerary.Segments.Segment,function(segIndex,mpSegment){var leg=new VERouteLeg();leg.Distance=mpSegment.Distance;leg.Time=mpSegment.TripTime;var itinerary=new VERouteItinerary();if(typeof(mpSegment.Directions.Direction[0])=="object")
{$.each(mpSegment.Directions.Direction,function(dirIndex,mpDirection){var item=new VERouteItineraryItem();item.Distance=mpDirection.Duration;item.LatLong=new VELatLong(Number(mpDirection.LatLong.Latitude),Number(mpDirection.LatLong.Longitude));item.Text=mpDirection.Instruction;item.Time=mpDirection.Distance;itinerary.Items.push(item);});}
else
{}
leg.Itinerary=itinerary;if(leg.Itinerary.Items.length>0)route.RouteLegs.push(leg);});return route;}
function insertPlaceIntoRoute(placeData,id)
{var tPlaceLatLong=new VELatLong(placeData.lat,placeData.lng);destinations.splice(getNearestLeg(tPlaceLatLong)+1,0,id);return destinations;}
function getNearestLeg(pinLatLong)
{var legs=getCurrentRoute().RouteLegs;var leg=new VERouteLeg();var nearestDistance=Number.MAX_VALUE;var nearestIndex=0;var pin=map.LatLongToPixel(pinLatLong);for(var i=0;i<legs.length;i++)
{leg=legs[i];var items=leg.Itinerary.Items;if(items.length>0)
{trace("getNearestLeg "+i+" items.length="+items.length);var start=map.LatLongToPixel(items[0].LatLong);var end=map.LatLongToPixel(items[items.length-1].LatLong);var a=new VEPixel((end.x-start.x),(end.y-start.y));var dist;if(Math.abs(((pin.x-start.x)/a.x)-((pin.y-start.y)/a.y))<0.1){dist=0;}else{var c=new VEPixel(pin.x-start.x,pin.y-start.y);var t=(vecDot(a,pin)-vecDot(a,start))/(a.x*a.x+a.y*a.y);var t=Math.max(0,Math.min(1,(vecDot(c,a)/vecMag(c))/vecMag(a)));var b=new VEPixel(pin.x-start.x-t*a.x,pin.y-start.y-t*a.y);var d=vecMag(b);dist=d;}
if(dist<nearestDistance){nearestDistance=d;nearestIndex=i;}}}
return nearestIndex;}
function getItinerarySummary()
{route=getCurrentRoute();tRoutePlaces=routePlacesData;function htmlObject(){this.startLocation='';this.endLocation='';this.currentDate='';this.totalDistance='';this.directions='<tr><td colspan="3">Please enter a route to generate directions</td></tr>';this.totalTime='';this.drivingTime='';this.noDate='';}
var html=new htmlObject();if(route!=undefined){if(route.RouteLegs.length>0)
{var legs=route.RouteLegs;var turns=null;var leg=null;var turnNum=0;var totalDistance=route.Distance;var time=0;var totalTime=0;var date=new Date(2000,1,1,0,0,0);var currentDate=new Date();var startLocation=null;var endLocation=null;var header=null;var placeKey;var placeData;startLocation=getDestinationValue(this.destinations[0]);endLocation=getDestinationValue(this.destinations[this.destinations.length-1]);html.startLocation=startLocation;html.endLocation=endLocation;html.currentDate=currentDate;html.totalDistance=totalDistance.toFixed(1)+" miles ("+milesToKm(totalDistance,1)+" km)";html.directions="<tr><th class=\"location\">Directions</th><th class=\"take\">Road Type</th><th class=\"miles\">Miles</th></tr>";for(var i=0;i<legs.length;i++)
{leg=legs[i];time=leg.Time;totalTime+=leg.Time;var turn=null;var legDistance=null;for(var j=0;j<leg.Itinerary.Items.length;j++)
{turnNum++;turn=leg.Itinerary.Items[j];html.directions+="<tr><td>"+turnNum+":  "+turn.Text+"</td>";legDistance=turn.Distance;var exp=/[MAB]{1}\d{1,5}(\(M\))?/g;var match=turn.Text.match(exp);if(match==null){html.directions+="<td>N/A</td>";}else{html.directions+="<td class=\"road\"><span>"+match+"</span></td>";}
html.directions+="<td>"+legDistance.toFixed(1)+" miles ("+milesToKm(legDistance,1)+" km)</td></tr>";}
date=new Date(2000,1,1,0,0,0);date.setMilliseconds(time*1000);}
date=new Date(2000,1,1,0,0,0);date.setMilliseconds(totalTime*1000);html.totalTime=toSmithTime(date.getHours()+":"+checkTime(date.getMinutes()));html.drivingTime=toSmithTime(date.getHours()+":"+checkTime(date.getMinutes()));}else{html.noData="<b>No route legs can be found. Please try again.</b>";}}else{html.noData="<b>No route can be found. Please try again.</b>";}
return html;}
var verifyQueue=new Array();var verifyCurrent=null;function initVerifyQueue()
{map.ShowDisambiguationDialog(false);verifyQueue=new Array();}
function verifyQueueNext()
{if(verifyQueue.length>0)
{if(verifyCurrent)verifyCurrent.active=false;verifyCurrent=verifyQueue.shift();verifyCurrent.find();}else{verifyCurrent=null;verifyQueueDone();}}
function verifyQueueStart()
{disableSubmit();}
function verifyQueueDone()
{enableSubmit();}
function verifyLocation(object,justTest)
{justTest=(justTest)?true:false;if(notEmptyOrDefault(object))
{if(verifyQueue.length>0)
{for(var i=0;i<verifyQueue.length;i++)
{if(verifyQueue[i].object==object)verifyQueue.splice(i--,1);}}
verifyQueue.push(new VerificationObject($(object).val().toString(),object,justTest));setValidStatus(object);clearDisambigIfCurrent(object);if(verifyCurrent==null){verifyQueueStart();verifyQueueNext();}}}
function VerificationObject(plocation,pobject,pJustTest){trace("new VerificationObject("+plocation+","+pobject+")");var o={id:Math.random(),active:false,location:plocation,object:pobject,justTest:pJustTest,find:function()
{o.active=true;var term=intoUk(o.location);map.Find(null,term,null,null,0,null,false,false,false,false,o.onVerify);},onVerify:function(layer,results,places,hasMore,veErrorMessage)
{if(o.active&&o.object)
{onVerifySearch(o,layer,results,places,hasMore,veErrorMessage);}
else
{verifyQueueNext();}}};return o;}
function clearDisambigIfCurrentDelayed(object)
{var f=function(){clearDisambigIfCurrent(object);};setTimeout(f,300);}
function clearDisambigIfCurrent(object)
{if(verifyCurrent!=null&&verifyCurrent.object==object){verifyCurrent.active=false;if($('#DisAmbiguation').html()!="")onVerifyChoose(null);}}
function onVerifySearch(fromVerify,layer,results,places,hasMore,veErrorMessage)
{if(verifyCurrent!=null)setValidStatus(verifyCurrent.object,(veErrorMessage==null));if(verifyCurrent!=null&&places!=null&&!fromVerify.justTest)
{var str='';var $DisAmbiguation=$("#DisAmbiguation");str+='<ul>';for(var i=0;i<places.length;i++){str+='<li><a onclick="onVerifyChoose(this); return false">'+places[i].Name+"</a></li>";}
str+='</ul>';var $input=$(verifyCurrent.object);var $inputPosition=$input.offset();$DisAmbiguation.prependTo('body');$DisAmbiguation.css({top:($inputPosition.top+18),left:$inputPosition.left});$DisAmbiguation.html(str);$DisAmbiguation.show();}
else
{verifyQueueNext();}}
function onVerifyChoose(e)
{trace("onVerifyChoose "+verifyCurrent.object);var $DisAmbiguation=$('#DisAmbiguation');if(verifyCurrent!=null&&e!=null)
{trace(verifyCurrent.object);$(verifyCurrent.object).val($(e).html());setValidStatus(verifyCurrent.object,true);}
$('ul',$DisAmbiguation).html("");$DisAmbiguation.hide();verifyQueueNext();}
function isRouteValidated(object)
{var tValid=($(object).val()!=""&&$(object).hasClass("routeValidated"))?true:false;return tValid;}
function setValidStatus(object,isValid)
{if(isValid==true)
{if(!$(object).hasClass("routeValidated"))
{$(object).addClass("routeValidated");}
if($(object).hasClass("routeInValidated"))
{$(object).removeClass("routeInValidated");}}
else if(isValid==false)
{if($(object).hasClass("routeValidated"))
{$(object).removeClass("routeValidated");}
if(!$(object).hasClass("routeInValidated"))
{$(object).addClass("routeInValidated");}}
else
{if($(object).hasClass("routeValidated"))
{$(object).removeClass("routeValidated");}
if($(object).hasClass("routeInValidated"))
{$(object).removeClass("routeInValidated");}}}
var smithRoutes=new Array({title:"Exmoor and Dartmoor",destinations:"Porlock|Lynmouth, Devon, England, United Kingdom|Combe Martin, Devon, England, United Kingdom|Simonsbath, Somerset, England, United Kingdom|Tiverton, England, United Kingdom|Chagford, Devon, England, United Kingdom|Lettaford, Devon, England, United Kingdom|Tavistock, England, United Kingdom|Milton Abbot, Devon, England, United Kingdom",time:"2:37",distance:"108.3",avoidMotorways:false},{title:"The Cotswolds",destinations:"Tetbury|Avening, Gloucestershire, England, United Kingdom|Duntisbourne Abbots, Gloucestershire, England, United Kingdom|Daglingworth, Gloucestershire, England, United Kingdom|Bibury, Gloucestershire, England, United Kingdom|Stow on the Wold, England, United Kingdom|{hotel_59}Cotswold House",time:"1:34",distance:"58.8",avoidMotorways:false},{title:"South Downs",destinations:"Milford, Godalming, Surrey|Cocking, West Sussex, England, United Kingdom|Chilgrove, West Sussex, England, United Kingdom|Lavant, West Sussex, England, United Kingdom|Chichester, West Sussex, England, United Kingdom|West Wittering, West Sussex, England, United Kingdom|West Wittering, West Sussex, England, United Kingdom",time:"1:20",distance:"41.5",avoidMotorways:false},{title:"North Norfolk",destinations:"Burnham Market, Norfolk, England, United Kingdom|Holkham, Norfolk, England, United Kingdom|Aylsham, Norfolk, England, United Kingdom|Wroxham, Norfolk, England, United Kingdom|Reedham, Norfolk, England, United Kingdom|Reedham, Norfolk, England, United Kingdom",time:"1:45",distance:"69.4",avoidMotorways:false},{title:"West Wales",destinations:"{hotel_130}Llety Bodfor,Aberdovey, Gwynedd, Wales, United Kingdom|Llwyngwril, Gwynedd, Wales, United Kingdom|Penmaenpool, Wales, United Kingdom|Harlech, Gwynedd, Wales, United Kingdom|Capel-Curig, Conwy, Wales, United Kingdom|Betws-y-coed, Wales, United Kingdom|Aberdovey, Gwynedd, Wales, United Kingdom",time:"5:17",distance:"234.3",avoidMotorways:false},{title:"Lake District",destinations:"Cartmel, Cumbria, England, United Kingdom|Newby Bridge, Cumbria, England, United Kingdom|Troutbeck Bridge, Cumbria, England, United Kingdom|Ambleside, Cumbria, England, United Kingdom|Keswick, Cumbria, England, United Kingdom",time:"1:49",distance:"69.2",avoidMotorways:false},{title:"Northwest Highlands",destinations:"{hotel_52}Pool House|Kinlochewe, Highland, Scotland, United Kingdom|Shieldaig, Highland, Scotland, United Kingdom|Cuaig, Highland, Scotland, United Kingdom|Applecross, Highland, Scotland, United Kingdom|Lochcarron, Highland, Scotland, United Kingdom|Kinlochewe, Highland, Scotland, United Kingdom|{hotel_52}Pool House",time:"4:56",distance:"265.3",avoidMotorways:false});function showSmithRouteDetails(routeIndex)
{var routeIndex=Number($('#RouteList').val());if(routeIndex>-1)
{var obj=smithRoutes[routeIndex];var tDestinations=obj.destinations.split("|");var tString="";var str="";$.each(tDestinations,function(index,dest){var str=dest.toString();var keyPair=extractKeyValue(str);if(keyPair!=null)
{str=keyPair.value;}
if(index==0)
{tString+='<p>From: '+unescape(str)+'</p>';}
else if(index==tDestinations.length-1)
{tString+='<p>To: '+unescape(str)+'</p>';}});$('#RouteDestenations').html(tString);$('#RouteTime').html(toSmithTime(obj.time));var dist=obj.distance+" miles ("+milesToKm(obj.distance,2)+" km)";$('#RouteDistance').html(dist);}
else
{$('#RouteDestenations').html("<p/>");$('#RouteTime').html("<p/>");$('#RouteDistance').html("<p/>");}}
function viewSmithRouteDetails()
{var routeIndex=Number($('#RouteList').val());if(routeIndex>-1&&!isLoading)
{showLoader();var obj=smithRoutes[routeIndex];parseDestinationsAndDrawRoute(obj.destinations,obj.avoidMotorways);}}
function customiseSmithRoute()
{var routeIndex=Number($('#RouteList').val());if(routeIndex>-1&&!isLoading)
{showLoader();$('#Accordian').accordion('activate',0);$('#Tab1').click();var obj=smithRoutes[routeIndex];parseDestinationsAndDrawRoute(obj.destinations,obj.avoidMotorways);}}
var GET_URL="/get_map_places.php";var GET_MAP_POINT_URL="/get_mwsroute.php";var GET_TOKEN_URL="/get_mwsroute.php?get_token=true";function onLoadMapPlaces(data)
{trace("data load : "+data);}
function onLoadMapPlacesError(xMLHttpRequest,textStatus,errorThrown)
{trace("onDataError: "+errorThrown);}
function loadMapPlaces(onDataLoadFunction,types)
{var tMapVisibleWidth=$("#smithMap").width();var tMapVisibleHeight=$("#smithMap").height();var bottomLeftPixel=new VEPixel(0,tMapVisibleHeight);var topRightPixel=new VEPixel(tMapVisibleWidth,0);var tSWLat=map.PixelToLatLong(bottomLeftPixel).Latitude;var tSWLng=map.PixelToLatLong(bottomLeftPixel).Longitude;var tNELat=map.PixelToLatLong(topRightPixel).Latitude;var tNELng=map.PixelToLatLong(topRightPixel).Longitude;var tZoom=13;var tData={saab:"true",sw_lat:tSWLat,sw_lng:tSWLng,ne_lat:tNELat,ne_lng:tNELng,zoom:tZoom,types:types.join(",")};var tCallback=onDataLoadFunction;$.getJSON(GET_URL,tData,tCallback);}
function loadAllMapPlaces(onDataLoadFunction)
{var tData={saab:"true",sw_lat:"49.50992",sw_lng:"-8.13931",ne_lat:"59.50992",ne_lng:"2.13931",zoom:"13",types:"Hotel"};var tCallback=onDataLoadFunction;$.getJSON(GET_URL,tData,tCallback);}
function loadMapPlacesForKeys(onDataLoadFunction,keys)
{var tData={saab:"true",sw_lat:"49.50992",sw_lng:"-8.13931",ne_lat:"59.50992",ne_lng:"2.13931",zoom:"13",keys:keys};var tCallback=onDataLoadFunction;$.getJSON(GET_URL,tData,tCallback);}
function loadMapPointData(onDataLoadFunction,destinationsString,avoidMotorWays)
{avoidMotorWays=(avoidMotorWays)?"true":"false";var tData={destinations:destinationsString,avoid_motorways:avoidMotorWays};var tCallback=onDataLoadFunction;$.getJSON(GET_MAP_POINT_URL,tData,tCallback);}
function loadTokenData(onDataLoadFunction)
{var tData={};var tCallback=onDataLoadFunction;$.getJSON(GET_TOKEN_URL,tData,tCallback);}
function clusterPins(placesData)
{var CLUSTER_RES=100;var gridX=Math.ceil($("#smithMap").width()/CLUSTER_RES);var gridY=Math.ceil($("#smithMap").height()/CLUSTER_RES);var clusters=new Array(gridX*gridY);var count=0;if(placesData!=null){for(var key in placesData)
{try
{count++;var item=mapPlacesData[key];var itemLatLong=new VELatLong(item.lat,item.lng);var itemPt=map.LatLongToPixel(itemLatLong);var pos=Math.floor(itemPt.x/CLUSTER_RES)*gridY+Math.floor(itemPt.y/CLUSTER_RES);var cluster=clusters[pos];var itemType=item.type.toLowerCase();var isOnRoute=(routePlacesData[key])?true:false;if(cluster==null||isOnRoute)
{cluster=new Object();cluster.type="Cluster";cluster.LatLong=itemLatLong;cluster.items=new Array();cluster.items.push(key);cluster.typeCount=new Object();cluster.typeCount[itemType]=1;cluster.typesLength=1;if(isOnRoute)
{clusters.push(cluster);}
else
{clusters[pos]=cluster;}}
else
{cluster.LatLong=avgLatLong(cluster.LatLong,itemLatLong,cluster.items.length,1);cluster.items.push(key);if(cluster.typeCount[itemType])
{cluster.typeCount[itemType]++;}
else
{cluster.typeCount[itemType]=1;cluster.typesLength++;}}}
catch(e)
{trace("Attempted to add a clustered item with no properties: "+key);}}}
for(var i=clusters.length-1;i>=0;i--)
{if(clusters[i]==null)clusters.splice(i,1);}
return clusters;}
function removeTypeFromClusters(clusters,type)
{for(var i=clusters.length-1;i>=0;i--)
{var cluster=clusters[i];for(var j=cluster.items.length-1;j>=0;j--)
{var placeId=cluster.items[j];if(mapPlacesData[placeId].type==type&&!routePlacesData[placeId])cluster.items.splice(j,1);}
if(cluster.items.length==0)clusters.splice(i,1);if(cluster.typeCount[type])
{delete cluster.typeCount[type];cluster.typesLength--;}}
return clusters;}
function avgPixel(u,v,uMass,vMass)
{if(uMass==null||uMass==undefined)uMass=1;if(vMass==null||vMass==undefined)vMass=1;var ratio=vMass/(uMass+vMass);return new VEPixel(u.x+ratio*(v.x-u.x),u.y+ratio*(v.y-u.y));}
function avgLatLong(u,v,uMass,vMass)
{if(uMass==null||uMass==undefined)uMass=1;if(vMass==null||vMass==undefined)vMass=1;var ratio=vMass/(uMass+vMass);return new VELatLong(u.Latitude+ratio*(v.Latitude-u.Latitude),u.Longitude+ratio*(v.Longitude-u.Longitude));}
function distPixel(u,v)
{var p=new VEPixel(u.x-v.x,u.y-v.y);return Math.sqrt(p.x*p.x+p.y*p.y);}
function buildSelects($s){this.$customSelects=$s;this.$customSelect=[];$customSelects.each(function(i){$customSelect[i]=new newCustomSelect($(this),i);$customSelect[i].render();});}
function newCustomSelect($e,i){var o={config:{selectBox:$e,selectOptions:$('option',$e),selectBoxParent:$e.parent(),arrowIconClass:'.rendered-select-arrow',newBoxClass:'.rendered-select',newListClass:'.c-select',newListId:'c-select-',newBoxHTML:'<div class=\"rendered-select\" id=\"RenderedSelect'+i+'\"><div class=\"s-1\"><input type=\"text\" name=\"\" readonly=\"\"/></div><span class=\"rendered-select-arrow\"></span></div>',newListHTML:function(i){var html='<div id=\"'+o.config.newListId+i+'\" class="c-select"><div class="c-select-content-skin"><div class="c-select-content"><ul></ul></div><div class="c-select-slider"><span class="up-handle"></span><div class="ui-slider-handle"></div><span class="down-handle"></span></div></div></div>';o.config.newListId='#'+o.config.newListId+i;return html;},sliderClass:'.c-select-slider',sliderHandleClass:'.ui-slider-handle',sliderUHandleClass:'.up-handle',sliderDHandleClass:'.down-handle',sliderContentClass:'.c-select-content',sliderContentSkinClass:'.c-select-content-skin'},current:{value:$('option:selected',$e).val(),text:$('option:selected',$e).text(),box:{},listBox:{},list:{},listItems:{},input:{},arrowIcon:{},selected:0,setSlider:{},isOpen:false},render:function(){o.config.selectBox.css({position:'absolute',right:'2000px'});o.config.selectBoxParent.append(o.config.newBoxHTML);o.current.box=$(o.config.newBoxClass,o.config.selectBoxParent);o.current.arrowIcon=$(o.config.arrowIconClass,o.config.selectBoxParent);o.current.input=$('input',o.current.box);$('body').append((o.config.newListHTML($(o.config.newListClass).length+1)));o.current.listBox=$(o.config.newListId);o.current.list=$('ul',o.current.listBox);o.config.selectOptions.each(function(i){var t=$(this).text();if(i==0){if(o.current.value==''){o.current.input.val(t);}
else{o.current.input.val(o.current.text);o.current.list.append('<li class=\"v-'+$(this).val()+' '+o.config.selectBox[0].id+'\">'+t+'</li>');}}
else{o.current.list.append('<li class=\"v-'+$(this).val()+' '+o.config.selectBox[0].id+'\">'+t+'</li>');}});o.current.listItems=$('li',o.current.list);o.current.listItemsTotal=(o.current.listItems.length-1);o.setEvents();o.setSlider.init();},getValue:function(c){var cA1=c.split(' ');var cA2=cA1[0].split('-');return cA2[1];},setEvents:function(){o.current.input.focus(function(){o.focus();});$(o.config.newListId).hover(function(){},function(){o.close();});$('li',o.current.list).hover(function(){var current;var v=o.getValue($(this)[0].className);o.config.selectOptions.each(function(i){if($(this)[0].value==v){o.current.value=v;}});$(this).css('background','#343017');},function(){$(this).css('background','none');});$('li',o.current.list).click(function(){o.select($(this));});o.current.arrowIcon.click(function(){if(o.current.isOpen==false){o.focus();}
else{o.close();}});},setSlider:{$slider:{},sliderHandle:{},content:{},contentSkin:{},upHandle:{},downHandle:{},stepSize:0,slideValue:0,currentPosition:0,maxSlide:0,minSlide:0,setStepSize:function(){var contentSize=(o.setSlider.content.innerHeight()-o.setSlider.contentSkin.innerHeight());var sliderSize=o.setSlider.$slider.innerHeight();var step=contentSize/100;o.setSlider.stepSize=step;},scrollRequiredCheck:function(){var ratio=o.setSlider.contentSkin.innerHeight()/o.setSlider.content.innerHeight();var result;if(ratio>1){result=true;}else{result=false;}
return result;},resizeHandle:function(){var ratio=o.setSlider.contentSkin.innerHeight()/o.setSlider.content.innerHeight();var handleHeight=Math.floor(ratio*o.setSlider.$slider.innerHeight());o.setSlider.sliderHandle.css({height:handleHeight});},init:function(){o.setSlider.$slider=$(o.config.sliderClass,o.current.listBox);o.setSlider.sliderHandle=$(o.config.sliderHandleClass,o.current.listBox);o.setSlider.content=$(o.config.sliderContentClass,o.current.listBox);o.setSlider.contentSkin=$(o.config.sliderContentSkinClass,o.current.listBox);o.setSlider.upHandle=$(o.config.sliderUHandleClass,o.current.listBox);o.setSlider.downHandle=$(o.config.sliderDHandleClass,o.current.listBox);o.setSlider.$slider.hide();if(o.setSlider.scrollRequiredCheck()==false){o.setSlider.$slider.show();o.setSlider.render();}},render:function(){o.setSlider.maxSlide=Math.abs(o.setSlider.stepSize*100)*-1;o.setSlider.minSlide=0;o.setSlider.setStepSize();o.setSlider.resizeHandle();o.setSlider.$slider.slider({slide:o.setSlider.onSlide});o.setSlider.setEvents();o.current.listBox.hide();},onSlide:function(e,ui){var temp=o.setSlider.content.css('top');var done=temp.substr(0,(temp.length-2));o.setSlider.currentPosition=Number(done);var newPosition=Math.floor(o.setSlider.minSlide-o.setSlider.stepSize*ui.value);o.setSlider.content.css({top:newPosition+'px'});o.setSlider.slideValue=ui.value;},setEvents:function(){o.setSlider.sliderHandle.hover(function(){$(this).css({background:'#403c22'});},function(){$(this).css({background:'#262313'});});o.setSlider.upHandle.click(function(){alert('asdsd');});o.setSlider.downHandle.click(function(){});}},blur:function(){o.close();},focus:function(){closeCustoms();o.config.selectBoxParent.removeClass('rendered-select-error');o.config.selectBoxParent.addClass('rendered-select-focus');o.open();},open:function(){o.current.arrowIcon.addClass('rendered-select-arrow-open');o.current.isOpen=true;o.config.selectBox.select();var p=o.config.selectBoxParent.offset();var h=o.config.selectBoxParent.innerHeight();o.current.listBox.css({display:'block',position:'absolute',zIndex:'10000000',top:p.top+18,left:p.left});$(document).keypress(function(e){o.keypress(e);});},keypress:function(e){if(e.which==40){if(o.current.selected<o.current.listItemsTotal){o.current.listItems.removeClass('selected');o.current.selected++;o.current.listItems.eq(o.current.selected).addClass('selected');o.current.value=$('.selected',o.current.list)[0].value;return false;}}
if(e.which==38){if(o.current.selected>0){o.current.listItems.removeClass('selected');o.current.selected=o.current.selected-1;o.current.listItems.eq(o.current.selected).addClass('selected');o.current.value=$('.selected',o.current.list)[0].value;return false;}}
if(e.which==13){o.current.value=$('.selected',o.current.list)[0].value;o.select($('.selected',o.current.list));o.current.listItems.removeClass('selected');return false;}
if(e.which==27){o.current.listItems.removeClass('selected');o.close();}},select:function(c){o.config.selectOptions.removeAttr('selected');o.config.selectOptions.each(function(index,option){if(String(option.value)==String(o.getValue(c[0].className))){option.selected=true;o.config.selectBox.change();}});o.current.input[0].value=c.text();o.current.input.change();$(document).unbind('keypress');o.close();},close:function(){o.current.isOpen=false;o.config.selectBoxParent.removeClass('rendered-select-focus');o.current.arrowIcon.removeClass('rendered-select-arrow-open');$(document).unbind('keypress');o.current.selected=0;o.current.listBox.hide();if(o.current.value==''){o.config.selectBoxParent.addClass('rendered-select-error');}},reset:function(){o.config.selectOptions.removeAttr('selected');o.config.selectOptions.each(function(){if($(this)[0].value=='0'){$(this).attr('selected','selected');o.current.input[0].value=$(this).text();}});}};return o;}
function fieldBlur($fieldInput){$fieldInput.parent().removeClass('field-focus');}
function closeCustoms(){for(i=0;i<$customSelect.length;i++){if($customSelect[i].current.isOpen==true){$customSelect[i].close();}}}
function toId(e){var f='#'+e;return f;}
$(document).ready(function(){});function initPage(){initAccordion();this.Config=new initConfigObject();this.Itinerary=new initItineraryObject();this.MapSize=new initMapResizeObject();this.WelcomePopUp=new initWelcomePopUp();initWidgets();initTabs();initSelectLists();initMapFeatures();initSmithNavHeader();initMotorwaysToggle();initTidy();initFieldStatusToggle();initValueReplace();}
function initConfigObject(){var o={interfaceWidth:$('#interface').width(),headerHeight:$('#Header').height()};return o;}
function initMapResizeObject(){var o={window:{},windowWidth:0,windowHeight:0,init:function(){o.window=$(window);o.resizeMap();o.window.resize(function(){o.resizeMap();});},resizeMap:function(){var w=890;var h=o.window.height();var newHeight=h-Config.headerHeight;if(newHeight<472){newHeight=472;}
map.Resize((w-Config.interfaceWidth),newHeight);showApp();Itinerary.resize();}};o.init();return o;}
function initItineraryObject(){var o={$button:$('#ItineraryTrigger'),$overlay:$('#MapContainer #Itinerary'),$closeButton:$('#CloseItinerary'),live:false,init:function(){o.$button.css({cursor:'pointer'});o.$button.click(function(){if(o.live==false){o.render();}
else{o.close();}});o.$closeButton.click(function(){o.close();}).css({cursor:'pointer'});},resize:function(){if(o.live==true){o.render();}},render:function(){o.live=true;$('span',o.$button).addClass('button-active');var w=637;var h=$(window).height();var newHeight=h-Config.headerHeight;if(newHeight<472){newHeight=472;}
$('#TableContainer').css({height:(newHeight-220)});o.$overlay.css({height:newHeight});var $Summary=getItinerarySummary();$('#TableContainer').append('<table id="DirectionsTable" border="0" cellpadding="0" cellspacing="0"></table>');$('#DirectionsTable',o.$overlay).html($Summary.directions).find('tr:even').addClass('alt');$('#StartLocation',o.$overlay).html($Summary.startLocation);$('#FinishLocation',o.$overlay).html($Summary.endLocation);$('#DrivingTime',o.$overlay).html($Summary.drivingTime);$('#TotalDistance',o.$overlay).html($Summary.totalDistance);o.$overlay.show();},close:function(){o.live=false;$('span',o.$button).removeClass('button-active');o.$overlay.hide();}};o.init();return o;}
function initWelcomePopUp(){var o={init:function(){o.widget=$('#WelcomePopUp');o.button=$('.button',o.widget);o.widget.prependTo('#Container');o.render();},render:function(){o.widget.animate({opacity:'show'},1000);o.open=true;o.events();},events:function(){o.button.click(function(){o.close(true);});$('.slide-trigger').click(function(){if(o.open==true){o.close(false);}});$('#Tabs li').click(function(){if(o.open==true){o.close(false);}});},close:function(activate){o.open=false;o.widget.animate({opacity:'hide'},1000,function(){o.openUI();if(activate==true){$('#Accordian').accordion('activate',0);}});},openUI:function(){$('#smithNavHeaderPng').animate({top:'0px'},1000,function(){$('#smithNavHeader').animate({top:'0px'},500,function(){$('#smithNavControls').animate({left:'0px'},600);});});}}
o.init();return o;}
function initWidgets(){var $smithMap=$('#smithMap');var loaderHTML='<div id=\"Loader\"><div class=\"loader-background\"></div><div class=\"loader-content\"><p><img src=\"_include/img/global/loader.gif\" /></p><p>Updating map</p></div></div>';$smithMap.append(loaderHTML);var popupHTML='<div id=\"Popup\"><div class=\"loader-background\"></div><div class=\"popup-content\"><h2></h2><p id=\"messageBody\"></p></div></div>';$smithMap.append(popupHTML);}
function initTabs(){var $tabs=$("#Tabs li:not([id='Tab3'])");$tabs.css({cursor:'pointer'});$tabs.click(function(){hideInfoPopup();closeCustoms();$tabs.removeClass('active');$(this).addClass('active');$('.tab-container').hide();switch($(this)[0].id){case'Tab1':$('.tab-container-1').show();break;case'Tab2':$('#Accordian').accordion('activate',-1);$('.tab-container-2').show();break;case'Tab3':$('.tab-container-3').show();break;}});var $saabTab=$('#Tab3');$saabTab.css({cursor:'pointer'});$saabTab.click(function(){hideInfoPopup();$('#DropOffPoints li.saab a').click();});}
function initCustomSelects(){var $selects=$('.frow-select select');buildSelects($selects);}
function initAccordion(){$('#Accordian').accordion({alwaysOpen:false,active:-1});$('#Accordian .slide-trigger').css({cursor:'pointer'});}
function initSelectLists(){var $MainListItems=$('#DropOffPoints li');var $MainListItemsTriggers=$('a.trigger',$MainListItems);var $MainListItemsInnerLists=$('.inner-list',$MainListItems);$MainListItems.css({cursor:'pointer'});$MainListItems.hover(function(){$(this).addClass('hover');},function(){$(this).removeClass('hover');});$MainListItemsTriggers.click(function(){$MainListItemsInnerLists.css({display:'none'});$MainListItems.removeClass('active');if($(this).parent().hasClass('inner-list-open')==false){$MainListItems.removeClass('inner-list-open');$(this).parent().addClass('active');$(this).parent().addClass('inner-list-open');$(this).parent().find('.inner-list').animate({opacity:'show'},400).css({height:'auto'});}
else
{$MainListItems.removeClass('inner-list-open');}
return false;});}
function initMapFeatures(){var $MapTriggers=$('#DropOffPoints a');$MapTriggers.click(function(){var itemClasses=$(this).parent()[0].className;var itemClasses=itemClasses.split(' ');var mapFunction=itemClasses[0];if($(this).parent().hasClass('live')==false)
{$(this).parent().addClass('live');showPlacePins(mapFunction);}
else
{$(this).parent().removeClass('live');hidePlacePins(mapFunction);}
return false;});}
function initSmithNavHeader(){var $buttons=$('#smithNavHeader span');var activeClass='button-active';$buttons.click(function(){$buttons.removeClass(activeClass);$(this).addClass(activeClass);});}
function initTidy(){$('#smithNavHeader span').css({cursor:'pointer'});$('#smithNavControls div').css({cursor:'pointer'});$('#Itinerary #ButtonsContainer span').css({cursor:'pointer'});$('.pointer').css({cursor:'pointer'});$('#Footer').show();}
function initSmithRoutes(){var optStr='<option value="-1" selected="true">Choose your Smith Route...</option>';$.each(smithRoutes,function(index,obj){optStr+='<option value="'+index+'">'+obj.title+'</option>';});$('#RouteList').html(optStr);$('#RouteList').change(function(evt){showSmithRouteDetails();});showSmithRouteDetails();$('#RouteView').click(viewSmithRouteDetails);$('#RouteCustomise').click(customiseSmithRoute);}
function initMotorwaysToggle(){$motorwaysTrigger=$('.motorways-trigger').parent();$motorwaysTrigger.css({cursor:'pointer'});$motorwaysTrigger.click(function(){setMotorwaysToggle(!avoidMotorWays);});}
function setMotorwaysToggle(state)
{trace("setMotorwaysToggle("+state+")");avoidMotorWays=state;var $p=$('.motorways-trigger').parent();if($p.hasClass('frow-custom-check-active')!=avoidMotorWays)
{$p.toggleClass('frow-custom-check-active');}}
function initFieldStatusToggle(){$('.input-toggle').each(function(){var o=new fieldStatusObject($(this));o.init();});}
function fieldStatusObject(e){var o={init:function(){o._field=e;o._fieldClassList=o._field.attr('class').split(' ');o._fieldSelect=$(toId(o._fieldClassList[1]));o._fieldSelectInput=$('input',o._fieldSelect);o.monitor();},monitor:function(){o._field.focus(function(){$(this).css({color:'#b2a65f'});});o._field.change(function(){$(this).css({color:'#b2a65f'});o._fieldSelectInput.css({color:'#3f3a1c'});});o._fieldSelectInput.change(function(){$(this).css({color:'#b2a65f'});o._field.css({color:'#3f3a1c'});if($(this)[0].value!='Choose a Smith hotel ...'){o._field[0].value='Street, town, city, postcode';}
else{$(this).css({color:'#3f3a1c'});o._field.css({color:'#b2a65f'});}});}}
return o;}
function initValueReplace(){$('input.value-replace').each(function(){var o=new valueReplace($(this));});function valueReplace(e){var o={init:function(){o.field=$(e);o.isSet=false;o.defaultValue=o.field.val();o.monitor();},monitor:function(){o.field.focus(function(){if($(this)[0].value==o.defaultValue){$(this)[0].value='';}});o.field.blur(function(){if($(this)[0].value==''){$(this)[0].value=o.defaultValue;}});}}
o.init();return o;}}
