/* GLOBAL VARS USED IN THIS FILE
*
* sDefaultCountryName	- The country to select from the quote form country drop-down (AL)
* sDefaultAirportCode	- The airport to select from the quote form airport drop-down (AL, AP)
* sDefaultTripType	- The trip type to select from the quote form trip type drop-down (TI)
* sDefaultDestination	- The destination (UK/EUROPE/WWEXUSA/WWINCUSA) to select from the quote form trip type drop-down (TI)
*
*/

/*
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 */
jQuery.getPos=function(e){var l=0;var t=0;var w=jQuery.intval(jQuery.css(e,'width'));var h=jQuery.intval(jQuery.css(e,'height'));var wb=e.offsetWidth;var hb=e.offsetHeight;while(e.offsetParent){l+=e.offsetLeft+(e.currentStyle?jQuery.intval(e.currentStyle.borderLeftWidth):0);t+=e.offsetTop+(e.currentStyle?jQuery.intval(e.currentStyle.borderTopWidth):0);e=e.offsetParent}l+=e.offsetLeft+(e.currentStyle?jQuery.intval(e.currentStyle.borderLeftWidth):0);t+=e.offsetTop+(e.currentStyle?jQuery.intval(e.currentStyle.borderTopWidth):0);return{x:l,y:t,w:w,h:h,wb:wb,hb:hb}};jQuery.getClient=function(e){if(e){w=e.clientWidth;h=e.clientHeight}else{w=(window.innerWidth)?window.innerWidth:(document.documentElement&&document.documentElement.clientWidth)?document.documentElement.clientWidth:document.body.offsetWidth;h=(window.innerHeight)?window.innerHeight:(document.documentElement&&document.documentElement.clientHeight)?document.documentElement.clientHeight:document.body.offsetHeight}return{w:w,h:h}};jQuery.getScroll=function(e){if(e){t=e.scrollTop;l=e.scrollLeft;w=e.scrollWidth;h=e.scrollHeight}else{if(document.documentElement&&document.documentElement.scrollTop){t=document.documentElement.scrollTop;l=document.documentElement.scrollLeft;w=document.documentElement.scrollWidth;h=document.documentElement.scrollHeight}else if(document.body){t=document.body.scrollTop;l=document.body.scrollLeft;w=document.body.scrollWidth;h=document.body.scrollHeight}}return{t:t,l:l,w:w,h:h}};jQuery.intval=function(v){v=parseInt(v);return isNaN(v)?0:v};jQuery.fn.ScrollTo=function(s){o=jQuery.speed(s);return this.each(function(){new jQuery.fx.ScrollTo(this,o)})};jQuery.fx.ScrollTo=function(e,o){var z=this;z.o=o;z.e=e;z.p=jQuery.getPos(e);z.s=jQuery.getScroll();z.clear=function(){clearInterval(z.timer);z.timer=null};z.t=(new Date).getTime();z.step=function(){var t=(new Date).getTime();var p=(t-z.t)/z.o.duration;if(t>=z.o.duration+z.t){z.clear();setTimeout(function(){z.scroll(z.p.y,z.p.x)},13)}else{st=((-Math.cos(p*Math.PI)/2)+0.5)*(z.p.y-z.s.t)+z.s.t;sl=((-Math.cos(p*Math.PI)/2)+0.5)*(z.p.x-z.s.l)+z.s.l;z.scroll(st,sl)}};z.scroll=function(t,l){window.scrollTo(l,t)};z.timer=setInterval(function(){z.step()},13)};

/*
 * hoverIntent r6 // 2011.02.26 // jQuery 1.5.1+
 * <http://cherne.net/brian/resources/jquery.hoverIntent.html>
 * 
 * @param  f  onMouseOver function || An object with configuration options
 * @param  g  onMouseOut function  || Nothing (use configuration options object)
 * @author    Brian Cherne brian(at)cherne(dot)net
*/
(function(a){a.fn.hoverIntent=function(k,l){var b="mousemove",c={sensitivity:7,interval:100,timeout:0};c=a.extend(c,l?{over:k,out:l}:k);var e,f,g,h,d=function(a){e=a.pageX;f=a.pageY},j=function(k,i){i.hoverIntent_t=clearTimeout(i.hoverIntent_t);if(Math.abs(g-e)+Math.abs(h-f)<c.sensitivity){a(i).unbind(b,d);i.hoverIntent_s=1;return c.over.apply(i,[k])}else{g=e;h=f;i.hoverIntent_t=setTimeout(function(){j(k,i)},c.interval)}},m=function(b,a){a.hoverIntent_t=clearTimeout(a.hoverIntent_t);a.hoverIntent_s=0;return c.out.apply(a,[b])},i=function(i){var f="mouseover",l=this,k=(i.type==f?i.fromElement:i.toElement)||i.relatedTarget;while(k&&k!=l)try{k=k.parentNode}catch(i){k=l}if(k==l)return false;var n=jQuery.extend({},i),e=l;if(e.hoverIntent_t)e.hoverIntent_t=clearTimeout(e.hoverIntent_t);if(i.type==f){g=n.pageX;h=n.pageY;a(e).bind(b,d);if(e.hoverIntent_s!=1)e.hoverIntent_t=setTimeout(function(){j(n,e)},c.interval)}else{a(e).unbind(b,d);if(e.hoverIntent_s==1)e.hoverIntent_t=setTimeout(function(){m(n,e)},c.timeout)}};return this.mouseover(i).mouseout(i)}})(jQuery);

/* 
 * ColorBox v1.3.18 - a full featured, light-weight, customizable lightbox based on jQuery 1.3+
 * Copyright (c) 2011 Jack Moore - jack@colorpowered.com
 * Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*/
(function(a,b,c){function Y(c,d,e){var g=b.createElement(c);return d&&(g.id=f+d),e&&(g.style.cssText=e),a(g)}function Z(a){var b=y.length,c=(Q+a)%b;return c<0?b+c:c}function $(a,b){return Math.round((/%/.test(a)?(b==="x"?z.width():z.height())/100:1)*parseInt(a,10))}function _(a){return K.photo||/\.(gif|png|jpe?g|bmp|ico)((#|\?).*)?$/i.test(a)}function ba(){var b;K=a.extend({},a.data(P,e));for(b in K)a.isFunction(K[b])&&b.slice(0,2)!=="on"&&(K[b]=K[b].call(P));K.rel=K.rel||P.rel||"nofollow",K.href=K.href||a(P).attr("href"),K.title=K.title||P.title,typeof K.href=="string"&&(K.href=a.trim(K.href))}function bb(b,c){a.event.trigger(b),c&&c.call(P)}function bc(){var a,b=f+"Slideshow_",c="click."+f,d,e,g;K.slideshow&&y[1]?(d=function(){F.text(K.slideshowStop).unbind(c).bind(j,function(){if(Q<y.length-1||K.loop)a=setTimeout(W.next,K.slideshowSpeed)}).bind(i,function(){clearTimeout(a)}).one(c+" "+k,e),r.removeClass(b+"off").addClass(b+"on"),a=setTimeout(W.next,K.slideshowSpeed)},e=function(){clearTimeout(a),F.text(K.slideshowStart).unbind([j,i,k,c].join(" ")).one(c,function(){W.next(),d()}),r.removeClass(b+"on").addClass(b+"off")},K.slideshowAuto?d():e()):r.removeClass(b+"off "+b+"on")}function bd(b){if(!U){P=b,ba(),y=a(P),Q=0,K.rel!=="nofollow"&&(y=a("."+g).filter(function(){var b=a.data(this,e).rel||this.rel;return b===K.rel}),Q=y.index(P),Q===-1&&(y=y.add(P),Q=y.length-1));if(!S){S=T=!0,r.show();if(K.returnFocus)try{P.blur(),a(P).one(l,function(){try{this.focus()}catch(a){}})}catch(c){}q.css({opacity:+K.opacity,cursor:K.overlayClose?"pointer":"auto"}).show(),K.w=$(K.initialWidth,"x"),K.h=$(K.initialHeight,"y"),W.position(),o&&z.bind("resize."+p+" scroll."+p,function(){q.css({width:z.width(),height:z.height(),top:z.scrollTop(),left:z.scrollLeft()})}).trigger("resize."+p),bb(h,K.onOpen),J.add(D).hide(),I.html(K.close).show()}W.load(!0)}}var d={transition:"elastic",speed:300,width:!1,initialWidth:"600",innerWidth:!1,maxWidth:!1,height:!1,initialHeight:"450",innerHeight:!1,maxHeight:!1,scalePhotos:!0,scrolling:!0,inline:!1,html:!1,iframe:!1,fastIframe:!0,photo:!1,href:!1,title:!1,rel:!1,opacity:.9,preloading:!0,current:"image {current} of {total}",previous:"previous",next:"next",close:"close",open:!1,returnFocus:!0,loop:!0,slideshow:!1,slideshowAuto:!0,slideshowSpeed:2500,slideshowStart:"start slideshow",slideshowStop:"stop slideshow",onOpen:!1,onLoad:!1,onComplete:!1,onCleanup:!1,onClosed:!1,overlayClose:!0,escKey:!0,arrowKey:!0,top:!1,bottom:!1,left:!1,right:!1,fixed:!1,data:undefined},e="colorbox",f="cbox",g=f+"Element",h=f+"_open",i=f+"_load",j=f+"_complete",k=f+"_cleanup",l=f+"_closed",m=f+"_purge",n=a.browser.msie&&!a.support.opacity,o=n&&a.browser.version<7,p=f+"_IE6",q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X="div";W=a.fn[e]=a[e]=function(b,c){var f=this;b=b||{},W.init();if(!f[0]){if(f.selector)return f;f=a("<a/>"),b.open=!0}return c&&(b.onComplete=c),f.each(function(){a.data(this,e,a.extend({},a.data(this,e)||d,b)),a(this).addClass(g)}),(a.isFunction(b.open)&&b.open.call(f)||b.open)&&bd(f[0]),f},W.init=function(){if(!r){if(!a("body")[0]){a(W.init);return}z=a(c),r=Y(X).attr({id:e,"class":n?f+(o?"IE6":"IE"):""}),q=Y(X,"Overlay",o?"position:absolute":"").hide(),s=Y(X,"Wrapper"),t=Y(X,"Content").append(A=Y(X,"LoadedContent","width:0; height:0; overflow:hidden"),C=Y(X,"LoadingOverlay").add(Y(X,"LoadingGraphic")),D=Y(X,"Title"),E=Y(X,"Current"),G=Y(X,"Next"),H=Y(X,"Previous"),F=Y(X,"Slideshow").bind(h,bc),I=Y(X,"Close")),s.append(Y(X).append(Y(X,"TopLeft"),u=Y(X,"TopCenter"),Y(X,"TopRight")),Y(X,!1,"clear:left").append(v=Y(X,"MiddleLeft"),t,w=Y(X,"MiddleRight")),Y(X,!1,"clear:left").append(Y(X,"BottomLeft"),x=Y(X,"BottomCenter"),Y(X,"BottomRight"))).find("div div").css({"float":"left"}),B=Y(X,!1,"position:absolute; width:9999px; visibility:hidden; display:none"),a("body").prepend(q,r.append(s,B)),L=u.height()+x.height()+t.outerHeight(!0)-t.height(),M=v.width()+w.width()+t.outerWidth(!0)-t.width(),N=A.outerHeight(!0),O=A.outerWidth(!0),r.css({"padding-bottom":L,"padding-right":M}).hide(),G.click(function(){W.next()}),H.click(function(){W.prev()}),I.click(function(){W.close()}),J=G.add(H).add(E).add(F),q.click(function(){K.overlayClose&&W.close()}),a(b).bind("keydown."+f,function(a){var b=a.keyCode;S&&K.escKey&&b===27&&(a.preventDefault(),W.close()),S&&K.arrowKey&&y[1]&&(b===37?(a.preventDefault(),H.click()):b===39&&(a.preventDefault(),G.click()))})}},W.remove=function(){r.add(q).remove(),r=null,a("."+g).removeData(e).removeClass(g)},W.position=function(a,b){function g(a){u[0].style.width=x[0].style.width=t[0].style.width=a.style.width,C[0].style.height=C[1].style.height=t[0].style.height=v[0].style.height=w[0].style.height=a.style.height}var c=0,d=0,e=r.offset();z.unbind("resize."+f),r.css({top:-99999,left:-99999}),K.fixed&&!o?r.css({position:"fixed"}):(c=z.scrollTop(),d=z.scrollLeft(),r.css({position:"absolute"})),K.right!==!1?d+=Math.max(z.width()-K.w-O-M-$(K.right,"x"),0):K.left!==!1?d+=$(K.left,"x"):d+=Math.round(Math.max(z.width()-K.w-O-M,0)/2),K.bottom!==!1?c+=Math.max(z.height()-K.h-N-L-$(K.bottom,"y"),0):K.top!==!1?c+=$(K.top,"y"):c+=Math.round(Math.max(z.height()-K.h-N-L,0)/2),r.css({top:e.top,left:e.left}),a=r.width()===K.w+O&&r.height()===K.h+N?0:a||0,s[0].style.width=s[0].style.height="9999px",r.dequeue().animate({width:K.w+O,height:K.h+N,top:c,left:d},{duration:a,complete:function(){g(this),T=!1,s[0].style.width=K.w+O+M+"px",s[0].style.height=K.h+N+L+"px",b&&b(),setTimeout(function(){z.bind("resize."+f,W.position)},1)},step:function(){g(this)}})},W.resize=function(a){S&&(a=a||{},a.width&&(K.w=$(a.width,"x")-O-M),a.innerWidth&&(K.w=$(a.innerWidth,"x")),A.css({width:K.w}),a.height&&(K.h=$(a.height,"y")-N-L),a.innerHeight&&(K.h=$(a.innerHeight,"y")),!a.innerHeight&&!a.height&&(A.css({height:"auto"}),K.h=A.height()),A.css({height:K.h}),W.position(K.transition==="none"?0:K.speed))},W.prep=function(b){function g(){return K.w=K.w||A.width(),K.w=K.mw&&K.mw<K.w?K.mw:K.w,K.w}function h(){return K.h=K.h||A.height(),K.h=K.mh&&K.mh<K.h?K.mh:K.h,K.h}if(!S)return;var c,d=K.transition==="none"?0:K.speed;A.remove(),A=Y(X,"LoadedContent").append(b),A.hide().appendTo(B.show()).css({width:g(),overflow:K.scrolling?"auto":"hidden"}).css({height:h()}).prependTo(t),B.hide(),a(R).css({"float":"none"}),o&&a("select").not(r.find("select")).filter(function(){return this.style.visibility!=="hidden"}).css({visibility:"hidden"}).one(k,function(){this.style.visibility="inherit"}),c=function(){function q(){n&&r[0].style.removeAttribute("filter")}var b,c,g=y.length,h,i="frameBorder",k="allowTransparency",l,o,p;if(!S)return;l=function(){clearTimeout(V),C.hide(),bb(j,K.onComplete)},n&&R&&A.fadeIn(100),D.html(K.title).add(A).show();if(g>1){typeof K.current=="string"&&E.html(K.current.replace("{current}",Q+1).replace("{total}",g)).show(),G[K.loop||Q<g-1?"show":"hide"]().html(K.next),H[K.loop||Q?"show":"hide"]().html(K.previous),K.slideshow&&F.show();if(K.preloading){b=[Z(-1),Z(1)];while(c=y[b.pop()])o=a.data(c,e).href||c.href,a.isFunction(o)&&(o=o.call(c)),_(o)&&(p=new Image,p.src=o)}}else J.hide();K.iframe?(h=Y("iframe")[0],i in h&&(h[i]=0),k in h&&(h[k]="true"),h.name=f+ +(new Date),K.fastIframe?l():a(h).one("load",l),h.src=K.href,K.scrolling||(h.scrolling="no"),a(h).addClass(f+"Iframe").appendTo(A).one(m,function(){h.src="//about:blank"})):l(),K.transition==="fade"?r.fadeTo(d,1,q):q()},K.transition==="fade"?r.fadeTo(d,0,function(){W.position(0,c)}):W.position(d,c)},W.load=function(b){var c,d,e=W.prep;T=!0,R=!1,P=y[Q],b||ba(),bb(m),bb(i,K.onLoad),K.h=K.height?$(K.height,"y")-N-L:K.innerHeight&&$(K.innerHeight,"y"),K.w=K.width?$(K.width,"x")-O-M:K.innerWidth&&$(K.innerWidth,"x"),K.mw=K.w,K.mh=K.h,K.maxWidth&&(K.mw=$(K.maxWidth,"x")-O-M,K.mw=K.w&&K.w<K.mw?K.w:K.mw),K.maxHeight&&(K.mh=$(K.maxHeight,"y")-N-L,K.mh=K.h&&K.h<K.mh?K.h:K.mh),c=K.href,V=setTimeout(function(){C.show()},100),K.inline?(Y(X).hide().insertBefore(a(c)[0]).one(m,function(){a(this).replaceWith(A.children())}),e(a(c))):K.iframe?e(" "):K.html?e(K.html):_(c)?(a(R=new Image).addClass(f+"Photo").error(function(){K.title=!1,e(Y(X,"Error").text("This image could not be loaded"))}).load(function(){var a;R.onload=null,K.scalePhotos&&(d=function(){R.height-=R.height*a,R.width-=R.width*a},K.mw&&R.width>K.mw&&(a=(R.width-K.mw)/R.width,d()),K.mh&&R.height>K.mh&&(a=(R.height-K.mh)/R.height,d())),K.h&&(R.style.marginTop=Math.max(K.h-R.height,0)/2+"px"),y[1]&&(Q<y.length-1||K.loop)&&(R.style.cursor="pointer",R.onclick=function(){W.next()}),n&&(R.style.msInterpolationMode="bicubic"),setTimeout(function(){e(R)},1)}),setTimeout(function(){R.src=c},1)):c&&B.load(c,K.data,function(b,c,d){e(c==="error"?Y(X,"Error").text("Request unsuccessful: "+d.statusText):a(this).contents())})},W.next=function(){!T&&y[1]&&(Q<y.length-1||K.loop)&&(Q=Z(1),W.load())},W.prev=function(){!T&&y[1]&&(Q||K.loop)&&(Q=Z(-1),W.load())},W.close=function(){S&&!U&&(U=!0,S=!1,bb(k,K.onCleanup),z.unbind("."+f+" ."+p),q.fadeTo(200,0),r.stop().fadeTo(300,0,function(){r.add(q).css({opacity:1,cursor:"auto"}).hide(),bb(m),A.remove(),setTimeout(function(){U=!1,bb(l,K.onClosed)},1)}))},W.element=function(){return a(P)},W.settings=d,a("."+g,b).live("click",function(a){a.which>1||a.shiftKey||a.altKey||a.metaKey||(a.preventDefault(),bd(this))}),W.init()})(jQuery,document,this);

/*
 ! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * bgiframe Version 2.1.3-pre
*/
(function(a){function b(a){return a&&a.constructor===Number?a+"px":a}a.fn.bgiframe=a.browser.msie&&/msie 6\.0/i.test(navigator.userAgent)?function(c){c=a.extend({top:"auto",left:"auto",width:"auto",height:"auto",opacity:true,src:"javascript:false;"},c);var d='<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+c.src+'"'+'style="display:block;position:absolute;z-index:-1;'+(c.opacity!==false?"filter:Alpha(Opacity='0');":"")+"top:"+(c.top=="auto"?"expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+'px')":b(c.top))+";"+"left:"+(c.left=="auto"?"expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+'px')":b(c.left))+";"+"width:"+(c.width=="auto"?"expression(this.parentNode.offsetWidth+'px')":b(c.width))+";"+"height:"+(c.height=="auto"?"expression(this.parentNode.offsetHeight+'px')":b(c.height))+";"+'"/>';return this.each(function(){if(a(this).children("iframe.bgiframe").length===0)this.insertBefore(document.createElement(d),this.firstChild)})}:function(){return this};a.fn.bgIframe=a.fn.bgiframe})(jQuery)

/* 
 * disqus comments
*/
if ( $('#disqus_thread').length ) {
	(function(){var dsq=document.createElement('script');dsq.type='text/javascript';dsq.async=true;dsq.src='http://essentialtravelblog.disqus.com/embed.js';(document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(dsq)})();
}

/*
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie=function(key,value,options){if(arguments.length>1&&String(value)!=="[object Object]"){options=jQuery.extend({},options);if(value===null||value===undefined){options.expires=-1}if(typeof options.expires==='number'){var days=options.expires,t=options.expires=new Date();t.setDate(t.getDate()+days)}value=String(value);return(document.cookie=[encodeURIComponent(key),'=',options.raw?value:encodeURIComponent(value),options.expires?'; expires='+options.expires.toUTCString():'',options.path?'; path='+options.path:'',options.domain?'; domain='+options.domain:'',options.secure?'; secure':''].join(''))}options=value||{};var result,decode=options.raw?function(s){return s}:decodeURIComponent;return(result=new RegExp('(?:^|; )'+encodeURIComponent(key)+'=([^;]*)').exec(document.cookie))?decode(result[1]):null};

/*
 * jQuery Expander Plugin v1.4
 *
 * Date: Sun Dec 11 15:08:42 2011 EST
 * Requires: jQuery v1.3+
 *
 * Copyright 2011, Karl Swedberg
 * Dual licensed under the MIT and GPL licenses (just like jQuery):
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
*/
(function(d){d.expander={version:"1.4",defaults:{slicePoint:100,preserveWords:true,widow:4,expandText:"read more",expandPrefix:"&hellip; ",expandAfterSummary:false,summaryClass:"summary",detailClass:"details",moreClass:"read-more",lessClass:"read-less",collapseTimer:0,expandEffect:"fadeIn",expandSpeed:250,collapseEffect:"fadeOut",collapseSpeed:200,userCollapse:true,userCollapseText:"read less",userCollapsePrefix:" ",onSlice:null,beforeExpand:null,afterExpand:null,onCollapse:null}};d.fn.expander=function(k){function H(a,
c){var g="span",h=a.summary;if(c){g="div";if(w.test(h)&&!a.expandAfterSummary)h=h.replace(w,a.moreLabel+"$1");else h+=a.moreLabel;h='<div class="'+a.summaryClass+'">'+h+"</div>"}else h+=a.moreLabel;return[h,"<",g+' class="'+a.detailClass+'"',">",a.details,"</"+g+">"].join("")}function I(a){var c='<span class="'+a.moreClass+'">'+a.expandPrefix;c+='<a href="#">'+a.expandText+"</a></span>";return c}function x(a,c){if(a.lastIndexOf("<")>a.lastIndexOf(">"))a=a.slice(0,a.lastIndexOf("<"));if(c)a=a.replace(J,
"");return a}function y(a,c){c.stop(true,true)[a.collapseEffect](a.collapseSpeed,function(){c.prev("span."+a.moreClass).show().length||c.parent().children("div."+a.summaryClass).show().find("span."+a.moreClass).show()})}function K(a,c,g){if(a.collapseTimer)z=setTimeout(function(){y(a,c);d.isFunction(a.onCollapse)&&a.onCollapse.call(g,false)},a.collapseTimer)}var u="init";if(typeof k=="string"){u=k;k={}}var r=d.extend({},d.expander.defaults,k),L=/^<(?:area|br|col|embed|hr|img|input|link|meta|param).*>$/i,
J=/(&(?:[^;]+;)?|\w+)$/,M=/<\/?(\w+)[^>]*>/g,A=/<(\w+)[^>]*>/g,B=/<\/(\w+)>/g,w=/(<\/[^>]+>)\s*$/,N=/^<[^>]+>.?/,z;k={init:function(){this.each(function(){var a,c,g,h,l,n,v,C=[],s=[],o={},p=this,f=d(this),D=d([]),b=d.meta?d.extend({},r,f.data()):r,O=!!f.find("."+b.detailClass).length,q=!!f.find("*").filter(function(){return/^block|table|list/.test(d(this).css("display"))}).length,t=(q?"div":"span")+"."+b.detailClass,E="span."+b.moreClass,P=b.expandSpeed||0,m=d.trim(f.html());d.trim(f.text());var e=
m.slice(0,b.slicePoint);if(!d.data(this,"expander")){d.data(this,"expander",true);d.each(["onSlice","beforeExpand","afterExpand","onCollapse"],function(i,j){o[j]=d.isFunction(b[j])});e=x(e);for(summTagless=e.replace(M,"").length;summTagless<b.slicePoint;){newChar=m.charAt(e.length);if(newChar=="<")newChar=m.slice(e.length).match(N)[0];e+=newChar;summTagless++}e=x(e,b.preserveWords);h=e.match(A)||[];l=e.match(B)||[];g=[];d.each(h,function(i,j){L.test(j)||g.push(j)});h=g;c=l.length;for(a=0;a<c;a++)l[a]=
l[a].replace(B,"$1");d.each(h,function(i,j){var F=j.replace(A,"$1"),G=d.inArray(F,l);if(G===-1){C.push(j);s.push("</"+F+">")}else l.splice(G,1)});s.reverse();if(O){c=f.find(t).remove().html();e=f.html();m=e+c;a=""}else{c=m.slice(e.length);if(c===""||c.split(/\s+/).length<b.widow)return;a=s.pop()||"";e+=s.join("");c=C.join("")+c}b.moreLabel=f.find(E).length?"":I(b);if(q)c=m;e+=a;b.summary=e;b.details=c;b.lastCloseTag=a;if(o.onSlice)b=(g=b.onSlice.call(p,b))&&g.details?g:b;q=H(b,q);f.html(q);n=f.find(t);
v=f.find(E);n.hide();v.find("a").unbind("click.expander").bind("click.expander",function(i){i.preventDefault();v.hide();D.hide();o.beforeExpand&&b.beforeExpand.call(p);n.stop(false,true)[b.expandEffect](P,function(){n.css({zoom:""});o.afterExpand&&b.afterExpand.call(p);K(b,n,p)})});D=f.find("div."+b.summaryClass);b.userCollapse&&!f.find("span."+b.lessClass).length&&f.find(t).append('<span class="'+b.lessClass+'">'+b.userCollapsePrefix+'<a href="#">'+b.userCollapseText+"</a></span>");f.find("span."+
b.lessClass+" a").unbind("click.expander").bind("click.expander",function(i){i.preventDefault();clearTimeout(z);i=d(this).closest(t);y(b,i);o.onCollapse&&b.onCollapse.call(p,true)})}})},destroy:function(){if(this.data("expander")){this.removeData("expander");this.each(function(){var a=d(this),c=d.meta?d.extend({},r,a.data()):r,g=a.find("."+c.detailClass).contents();a.find("."+c.moreClass).remove();a.find("."+c.summaryClass).remove();a.find("."+c.detailClass).after(g).remove();a.find("."+c.lessClass).remove()})}}};
k[u]&&k[u].call(this);return this};d.fn.expander.defaults=d.expander.defaults})(jQuery);


/*
 * 
 * TableSorter 2.0 - Client-side table sorting with ease!
 * Version 2.0.5b
 * @requires jQuery v1.2.3
 * 
 * Copyright (c) 2007 Christian Bach
 * Examples and docs at: http://tablesorter.com
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * 
 */
(function($){$.extend({tablesorter:new
function(){var parsers=[],widgets=[];this.defaults={cssHeader:"header",cssAsc:"headerSortUp",cssDesc:"headerSortDown",cssChildRow:"expand-child",sortInitialOrder:"asc",sortMultiSortKey:"shiftKey",sortForce:null,sortAppend:null,sortLocaleCompare:true,textExtraction:"simple",parsers:{},widgets:[],widgetZebra:{css:["even","odd"]},headers:{},widthFixed:false,cancelSelection:true,sortList:[],headerList:[],dateFormat:"us",decimal:'/\.|\,/g',onRenderHeader:null,selectorHeaders:'thead th',debug:false};function benchmark(s,d){log(s+","+(new Date().getTime()-d.getTime())+"ms");}this.benchmark=benchmark;function log(s){if(typeof console!="undefined"&&typeof console.debug!="undefined"){console.log(s);}else{alert(s);}}function buildParserCache(table,$headers){if(table.config.debug){var parsersDebug="";}if(table.tBodies.length==0)return;var rows=table.tBodies[0].rows;if(rows[0]){var list=[],cells=rows[0].cells,l=cells.length;for(var i=0;i<l;i++){var p=false;if($.metadata&&($($headers[i]).metadata()&&$($headers[i]).metadata().sorter)){p=getParserById($($headers[i]).metadata().sorter);}else if((table.config.headers[i]&&table.config.headers[i].sorter)){p=getParserById(table.config.headers[i].sorter);}if(!p){p=detectParserForColumn(table,rows,-1,i);}if(table.config.debug){parsersDebug+="column:"+i+" parser:"+p.id+"\n";}list.push(p);}}if(table.config.debug){log(parsersDebug);}return list;};function detectParserForColumn(table,rows,rowIndex,cellIndex){var l=parsers.length,node=false,nodeValue=false,keepLooking=true;while(nodeValue==''&&keepLooking){rowIndex++;if(rows[rowIndex]){node=getNodeFromRowAndCellIndex(rows,rowIndex,cellIndex);nodeValue=trimAndGetNodeText(table.config,node);if(table.config.debug){log('Checking if value was empty on row:'+rowIndex);}}else{keepLooking=false;}}for(var i=1;i<l;i++){if(parsers[i].is(nodeValue,table,node)){return parsers[i];}}return parsers[0];}function getNodeFromRowAndCellIndex(rows,rowIndex,cellIndex){return rows[rowIndex].cells[cellIndex];}function trimAndGetNodeText(config,node){return $.trim(getElementText(config,node));}function getParserById(name){var l=parsers.length;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==name.toLowerCase()){return parsers[i];}}return false;}function buildCache(table){if(table.config.debug){var cacheTime=new Date();}var totalRows=(table.tBodies[0]&&table.tBodies[0].rows.length)||0,totalCells=(table.tBodies[0].rows[0]&&table.tBodies[0].rows[0].cells.length)||0,parsers=table.config.parsers,cache={row:[],normalized:[]};for(var i=0;i<totalRows;++i){var c=$(table.tBodies[0].rows[i]),cols=[];if(c.hasClass(table.config.cssChildRow)){cache.row[cache.row.length-1]=cache.row[cache.row.length-1].add(c);continue;}cache.row.push(c);for(var j=0;j<totalCells;++j){cols.push(parsers[j].format(getElementText(table.config,c[0].cells[j]),table,c[0].cells[j]));}cols.push(cache.normalized.length);cache.normalized.push(cols);cols=null;};if(table.config.debug){benchmark("Building cache for "+totalRows+" rows:",cacheTime);}return cache;};function getElementText(config,node){var text="";if(!node)return"";if(!config.supportsTextContent)config.supportsTextContent=node.textContent||false;if(config.textExtraction=="simple"){if(config.supportsTextContent){text=node.textContent;}else{if(node.childNodes[0]&&node.childNodes[0].hasChildNodes()){text=node.childNodes[0].innerHTML;}else{text=node.innerHTML;}}}else{if(typeof(config.textExtraction)=="function"){text=config.textExtraction(node);}else{text=$(node).text();}}return text;}function appendToTable(table,cache){if(table.config.debug){var appendTime=new Date()}var c=cache,r=c.row,n=c.normalized,totalRows=n.length,checkCell=(n[0].length-1),tableBody=$(table.tBodies[0]),rows=[];for(var i=0;i<totalRows;i++){var pos=n[i][checkCell];rows.push(r[pos]);if(!table.config.appender){var l=r[pos].length;for(var j=0;j<l;j++){tableBody[0].appendChild(r[pos][j]);}}}if(table.config.appender){table.config.appender(table,rows);}rows=null;if(table.config.debug){benchmark("Rebuilt table:",appendTime);}applyWidget(table);setTimeout(function(){$(table).trigger("sortEnd");},0);};function buildHeaders(table){if(table.config.debug){var time=new Date();}var meta=($.metadata)?true:false;var header_index=computeTableHeaderCellIndexes(table);$tableHeaders=$(table.config.selectorHeaders,table).each(function(index){this.column=header_index[this.parentNode.rowIndex+"-"+this.cellIndex];this.order=formatSortingOrder(table.config.sortInitialOrder);this.count=this.order;if(checkHeaderMetadata(this)||checkHeaderOptions(table,index))this.sortDisabled=true;if(checkHeaderOptionsSortingLocked(table,index))this.order=this.lockedOrder=checkHeaderOptionsSortingLocked(table,index);if(!this.sortDisabled){var $th=$(this).addClass(table.config.cssHeader);if(table.config.onRenderHeader)table.config.onRenderHeader.apply($th);}table.config.headerList[index]=this;});if(table.config.debug){benchmark("Built headers:",time);log($tableHeaders);}return $tableHeaders;};function computeTableHeaderCellIndexes(t){var matrix=[];var lookup={};var thead=t.getElementsByTagName('THEAD')[0];var trs=thead.getElementsByTagName('TR');for(var i=0;i<trs.length;i++){var cells=trs[i].cells;for(var j=0;j<cells.length;j++){var c=cells[j];var rowIndex=c.parentNode.rowIndex;var cellId=rowIndex+"-"+c.cellIndex;var rowSpan=c.rowSpan||1;var colSpan=c.colSpan||1
var firstAvailCol;if(typeof(matrix[rowIndex])=="undefined"){matrix[rowIndex]=[];}for(var k=0;k<matrix[rowIndex].length+1;k++){if(typeof(matrix[rowIndex][k])=="undefined"){firstAvailCol=k;break;}}lookup[cellId]=firstAvailCol;for(var k=rowIndex;k<rowIndex+rowSpan;k++){if(typeof(matrix[k])=="undefined"){matrix[k]=[];}var matrixrow=matrix[k];for(var l=firstAvailCol;l<firstAvailCol+colSpan;l++){matrixrow[l]="x";}}}}return lookup;}function checkCellColSpan(table,rows,row){var arr=[],r=table.tHead.rows,c=r[row].cells;for(var i=0;i<c.length;i++){var cell=c[i];if(cell.colSpan>1){arr=arr.concat(checkCellColSpan(table,headerArr,row++));}else{if(table.tHead.length==1||(cell.rowSpan>1||!r[row+1])){arr.push(cell);}}}return arr;};function checkHeaderMetadata(cell){if(($.metadata)&&($(cell).metadata().sorter===false)){return true;};return false;}function checkHeaderOptions(table,i){if((table.config.headers[i])&&(table.config.headers[i].sorter===false)){return true;};return false;}function checkHeaderOptionsSortingLocked(table,i){if((table.config.headers[i])&&(table.config.headers[i].lockedOrder))return table.config.headers[i].lockedOrder;return false;}function applyWidget(table){var c=table.config.widgets;var l=c.length;for(var i=0;i<l;i++){getWidgetById(c[i]).format(table);}}function getWidgetById(name){var l=widgets.length;for(var i=0;i<l;i++){if(widgets[i].id.toLowerCase()==name.toLowerCase()){return widgets[i];}}};function formatSortingOrder(v){if(typeof(v)!="Number"){return(v.toLowerCase()=="desc")?1:0;}else{return(v==1)?1:0;}}function isValueInArray(v,a){var l=a.length;for(var i=0;i<l;i++){if(a[i][0]==v){return true;}}return false;}function setHeadersCss(table,$headers,list,css){$headers.removeClass(css[0]).removeClass(css[1]);var h=[];$headers.each(function(offset){if(!this.sortDisabled){h[this.column]=$(this);}});var l=list.length;for(var i=0;i<l;i++){h[list[i][0]].addClass(css[list[i][1]]);}}function fixColumnWidth(table,$headers){var c=table.config;if(c.widthFixed){var colgroup=$('<colgroup>');$("tr:first td",table.tBodies[0]).each(function(){colgroup.append($('<col>').css('width',$(this).width()));});$(table).prepend(colgroup);};}function updateHeaderSortCount(table,sortList){var c=table.config,l=sortList.length;for(var i=0;i<l;i++){var s=sortList[i],o=c.headerList[s[0]];o.count=s[1];o.count++;}}function multisort(table,sortList,cache){if(table.config.debug){var sortTime=new Date();}var dynamicExp="var sortWrapper = function(a,b) {",l=sortList.length;for(var i=0;i<l;i++){var c=sortList[i][0];var order=sortList[i][1];var s=(table.config.parsers[c].type=="text")?((order==0)?makeSortFunction("text","asc",c):makeSortFunction("text","desc",c)):((order==0)?makeSortFunction("numeric","asc",c):makeSortFunction("numeric","desc",c));var e="e"+i;dynamicExp+="var "+e+" = "+s;dynamicExp+="if("+e+") { return "+e+"; } ";dynamicExp+="else { ";}var orgOrderCol=cache.normalized[0].length-1;dynamicExp+="return a["+orgOrderCol+"]-b["+orgOrderCol+"];";for(var i=0;i<l;i++){dynamicExp+="}; ";}dynamicExp+="return 0; ";dynamicExp+="}; ";if(table.config.debug){benchmark("Evaling expression:"+dynamicExp,new Date());}eval(dynamicExp);cache.normalized.sort(sortWrapper);if(table.config.debug){benchmark("Sorting on "+sortList.toString()+" and dir "+order+" time:",sortTime);}return cache;};function makeSortFunction(type,direction,index){var a="a["+index+"]",b="b["+index+"]";if(type=='text'&&direction=='asc'){return"("+a+" == "+b+" ? 0 : ("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : ("+a+" < "+b+") ? -1 : 1 )));";}else if(type=='text'&&direction=='desc'){return"("+a+" == "+b+" ? 0 : ("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : ("+b+" < "+a+") ? -1 : 1 )));";}else if(type=='numeric'&&direction=='asc'){return"("+a+" === null && "+b+" === null) ? 0 :("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : "+a+" - "+b+"));";}else if(type=='numeric'&&direction=='desc'){return"("+a+" === null && "+b+" === null) ? 0 :("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : "+b+" - "+a+"));";}};function makeSortText(i){return"((a["+i+"] < b["+i+"]) ? -1 : ((a["+i+"] > b["+i+"]) ? 1 : 0));";};function makeSortTextDesc(i){return"((b["+i+"] < a["+i+"]) ? -1 : ((b["+i+"] > a["+i+"]) ? 1 : 0));";};function makeSortNumeric(i){return"a["+i+"]-b["+i+"];";};function makeSortNumericDesc(i){return"b["+i+"]-a["+i+"];";};function sortText(a,b){if(table.config.sortLocaleCompare)return a.localeCompare(b);return((a<b)?-1:((a>b)?1:0));};function sortTextDesc(a,b){if(table.config.sortLocaleCompare)return b.localeCompare(a);return((b<a)?-1:((b>a)?1:0));};function sortNumeric(a,b){return a-b;};function sortNumericDesc(a,b){return b-a;};function getCachedSortType(parsers,i){return parsers[i].type;};this.construct=function(settings){return this.each(function(){if(!this.tHead||!this.tBodies)return;var $this,$document,$headers,cache,config,shiftDown=0,sortOrder;this.config={};config=$.extend(this.config,$.tablesorter.defaults,settings);$this=$(this);$.data(this,"tablesorter",config);$headers=buildHeaders(this);this.config.parsers=buildParserCache(this,$headers);cache=buildCache(this);var sortCSS=[config.cssDesc,config.cssAsc];fixColumnWidth(this);$headers.click(function(e){var totalRows=($this[0].tBodies[0]&&$this[0].tBodies[0].rows.length)||0;if(!this.sortDisabled&&totalRows>0){$this.trigger("sortStart");var $cell=$(this);var i=this.column;this.order=this.count++%2;if(this.lockedOrder)this.order=this.lockedOrder;if(!e[config.sortMultiSortKey]){config.sortList=[];if(config.sortForce!=null){var a=config.sortForce;for(var j=0;j<a.length;j++){if(a[j][0]!=i){config.sortList.push(a[j]);}}}config.sortList.push([i,this.order]);}else{if(isValueInArray(i,config.sortList)){for(var j=0;j<config.sortList.length;j++){var s=config.sortList[j],o=config.headerList[s[0]];if(s[0]==i){o.count=s[1];o.count++;s[1]=o.count%2;}}}else{config.sortList.push([i,this.order]);}};setTimeout(function(){setHeadersCss($this[0],$headers,config.sortList,sortCSS);appendToTable($this[0],multisort($this[0],config.sortList,cache));},1);return false;}}).mousedown(function(){if(config.cancelSelection){this.onselectstart=function(){return false};return false;}});$this.bind("update",function(){var me=this;setTimeout(function(){me.config.parsers=buildParserCache(me,$headers);cache=buildCache(me);},1);}).bind("updateCell",function(e,cell){var config=this.config;var pos=[(cell.parentNode.rowIndex-1),cell.cellIndex];cache.normalized[pos[0]][pos[1]]=config.parsers[pos[1]].format(getElementText(config,cell),cell);}).bind("sorton",function(e,list){$(this).trigger("sortStart");config.sortList=list;var sortList=config.sortList;updateHeaderSortCount(this,sortList);setHeadersCss(this,$headers,sortList,sortCSS);appendToTable(this,multisort(this,sortList,cache));}).bind("appendCache",function(){appendToTable(this,cache);}).bind("applyWidgetId",function(e,id){getWidgetById(id).format(this);}).bind("applyWidgets",function(){applyWidget(this);});if($.metadata&&($(this).metadata()&&$(this).metadata().sortlist)){config.sortList=$(this).metadata().sortlist;}if(config.sortList.length>0){$this.trigger("sorton",[config.sortList]);}applyWidget(this);});};this.addParser=function(parser){var l=parsers.length,a=true;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==parser.id.toLowerCase()){a=false;}}if(a){parsers.push(parser);};};this.addWidget=function(widget){widgets.push(widget);};this.formatFloat=function(s){var i=parseFloat(s);return(isNaN(i))?0:i;};this.formatInt=function(s){var i=parseInt(s);return(isNaN(i))?0:i;};this.isDigit=function(s,config){return/^[-+]?\d*$/.test($.trim(s.replace(/[,.']/g,'')));};this.clearTableBody=function(table){if($.browser.msie){function empty(){while(this.firstChild)this.removeChild(this.firstChild);}empty.apply(table.tBodies[0]);}else{table.tBodies[0].innerHTML="";}};}});$.fn.extend({tablesorter:$.tablesorter.construct});var ts=$.tablesorter;ts.addParser({id:"text",is:function(s){return true;},format:function(s){return $.trim(s.toLocaleLowerCase());},type:"text"});ts.addParser({id:"digit",is:function(s,table){var c=table.config;return $.tablesorter.isDigit(s,c);},format:function(s){return $.tablesorter.formatFloat(s);},type:"numeric"});ts.addParser({id:"currency",is:function(s){return/^[Â£$â‚¬?.]/.test(s);},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/[Â£$â‚¬]/g),""));},type:"numeric"});ts.addParser({id:"ipAddress",is:function(s){return/^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);},format:function(s){var a=s.split("."),r="",l=a.length;for(var i=0;i<l;i++){var item=a[i];if(item.length==2){r+="0"+item;}else{r+=item;}}return $.tablesorter.formatFloat(r);},type:"numeric"});ts.addParser({id:"url",is:function(s){return/^(https?|ftp|file):\/\/$/.test(s);},format:function(s){return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//),''));},type:"text"});ts.addParser({id:"isoDate",is:function(s){return/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s);},format:function(s){return $.tablesorter.formatFloat((s!="")?new Date(s.replace(new RegExp(/-/g),"/")).getTime():"0");},type:"numeric"});ts.addParser({id:"percent",is:function(s){return/\%$/.test($.trim(s));},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g),""));},type:"numeric"});ts.addParser({id:"usLongDate",is:function(s){return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/));},format:function(s){return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"shortDate",is:function(s){return/\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);},format:function(s,table){var c=table.config;s=s.replace(/\-/g,"/");if(c.dateFormat=="us"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$1/$2");}else if(c.dateFormat=="uk"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$2/$1");}else if(c.dateFormat=="dd/mm/yy"||c.dateFormat=="dd-mm-yy"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/,"$1/$2/$3");}return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"time",is:function(s){return/^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);},format:function(s){return $.tablesorter.formatFloat(new Date("2000/01/01 "+s).getTime());},type:"numeric"});ts.addParser({id:"metadata",is:function(s){return false;},format:function(s,table,cell){var c=table.config,p=(!c.parserMetadataName)?'sortValue':c.parserMetadataName;return $(cell).metadata()[p];},type:"numeric"});ts.addWidget({id:"zebra",format:function(table){if(table.config.debug){var time=new Date();}var $tr,row=-1,odd;$("tr:visible",table.tBodies[0]).each(function(i){$tr=$(this);if(!$tr.hasClass(table.config.cssChildRow))row++;odd=(row%2==0);$tr.removeClass(table.config.widgetZebra.css[odd?0:1]).addClass(table.config.widgetZebra.css[odd?1:0])});if(table.config.debug){$.tablesorter.benchmark("Applying Zebra widget",time);}}});})(jQuery);

/* table sorter extension */

$.tablesorter.addParser({ 
	id: 'transfers', 
	is: function(s) { 
		return false; 
	}, 
	format: function(s) { 
		return s.replace(/ minutes/,"").replace(/not required/,0);
	}, 
	type: 'numeric' 
}); 



/*
* display tweets
*/

(function(a){a.fn.tweet=function(b){function n(b){var d={};d.item=b;d.source=b.source;d.screen_name=b.from_user||b.user.screen_name;d.avatar_size=c.avatar_size;d.avatar_url=m(b,document.location.protocol==="https:");d.retweet=typeof b.retweeted_status!="undefined";d.tweet_time=i(b.created_at);d.join_text=c.join_text=="auto"?k(b.text):c.join_text;d.tweet_id=b.id_str;d.twitter_base="http://"+c.twitter_url+"/";d.user_url=d.twitter_base+d.screen_name;d.tweet_url=d.user_url+"/status/"+d.tweet_id;d.reply_url=d.twitter_base+"intent/tweet?in_reply_to="+d.tweet_id;d.retweet_url=d.twitter_base+"intent/retweet?tweet_id="+d.tweet_id;d.favorite_url=d.twitter_base+"intent/favorite?tweet_id="+d.tweet_id;d.retweeted_screen_name=d.retweet&&b.retweeted_status.user.screen_name;d.tweet_relative_time=j(d.tweet_time);d.entities=b.entities?(b.entities.urls||[]).concat(b.entities.media||[]):[];d.tweet_raw_text=d.retweet?"RT @"+d.retweeted_screen_name+" "+b.retweeted_status.text:b.text;d.tweet_text=a([h(d.tweet_raw_text,d.entities)]).linkUser().linkHash()[0];d.tweet_text_fancy=a([d.tweet_text]).makeHeart().capAwesome().capEpic()[0];d.user=e('<a class="tweet_user" href="{user_url}">{screen_name}</a>',d);d.join=c.join_text?e(' <span class="tweet_join">{join_text}</span> ',d):" ";d.avatar=d.avatar_size?e('<a class="tweet_avatar" href="{user_url}"><img src="{avatar_url}" height="{avatar_size}" width="{avatar_size}" alt="{screen_name}\'s avatar" title="{screen_name}\'s avatar" border="0"/></a>',d):"";d.time=e('<span class="tweet_time"><a href="{tweet_url}" title="view tweet on twitter">{tweet_relative_time}</a></span>',d);d.text=e('<span class="tweet_text">{tweet_text_fancy}</span>',d);d.reply_action=e('<a class="tweet_action tweet_reply" href="{reply_url}">reply</a>',d);d.retweet_action=e('<a class="tweet_action tweet_retweet" href="{retweet_url}">retweet</a>',d);d.favorite_action=e('<a class="tweet_action tweet_favorite" href="{favorite_url}">favorite</a>',d);return d}function m(a,b){if(b){return"user"in a?a.user.profile_image_url_https:m(a,false)}else{return a.profile_image_url||a.user.profile_image_url}}function l(){var a="https:"==document.location.protocol?"https:":"http:";var b=c.fetch===null?c.count:c.fetch;var d="&include_entities=1&callback=?";if(c.list){return a+"//"+c.twitter_api_url+"/1/"+c.username[0]+"/lists/"+c.list+"/statuses.json?page="+c.page+"&per_page="+b+d}else if(c.favorites){return a+"//"+c.twitter_api_url+"/favorites/"+c.username[0]+".json?page="+c.page+"&count="+b+d}else if(c.query===null&&c.username.length==1){return a+"//"+c.twitter_api_url+"/1/statuses/user_timeline.json?screen_name="+c.username[0]+"&count="+b+(c.retweets?"&include_rts=1":"")+"&page="+c.page+d}else{var e=c.query||"from:"+c.username.join(" OR from:");return a+"//"+c.twitter_search_url+"/search.json?&q="+encodeURIComponent(e)+"&rpp="+b+"&page="+c.page+d}}function k(a){if(a.match(/^(@([A-Za-z0-9-_]+)) .*/i)){return c.auto_join_text_reply}else if(a.match(d)){return c.auto_join_text_url}else if(a.match(/^((\w+ed)|just) .*/im)){return c.auto_join_text_ed}else if(a.match(/^(\w*ing) .*/i)){return c.auto_join_text_ing}else{return c.auto_join_text_default}}function j(a){var b=arguments.length>1?arguments[1]:new Date;var c=parseInt((b.getTime()-a)/1e3,10);var d="";if(c<1){d="just now"}else if(c<60){d=c+" seconds ago"}else if(c<120){d="a minute ago"}else if(c<45*60){d=parseInt(c/60,10).toString()+" minutes ago"}else if(c<2*60*60){d="an hour ago"}else if(c<24*60*60){d=""+parseInt(c/3600,10).toString()+" hours ago"}else if(c<48*60*60){d="a day ago"}else{d=parseInt(c/86400,10).toString()+" days ago"}return"about "+d}function i(a){return Date.parse(a.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i,"$1,$2$4$3"))}function h(a,b){return a.replace(d,function(a){var c=/^[a-z]+:/i.test(a)?a:"http://"+a;var d=a;for(var e=0;e<b.length;++e){var f=b[e];if(f.url==c&&f.expanded_url){c=f.expanded_url;d=f.display_url;break}}return'<a href="'+g(c)+'">'+g(d)+"</a>"})}function g(a){return a.replace(/</g,"<").replace(/>/g,"^>")}function f(b,c){return function(){var d=[];this.each(function(){d.push(this.replace(b,c))});return a(d)}}function e(a,b){if(typeof a==="string"){var c=a;for(var d in b){var e=b[d];c=c.replace(new RegExp("{"+d+"}","g"),e===null?"":e)}return c}else return a(b)}var c=a.extend({username:null,list:null,favorites:false,query:null,avatar_size:null,count:3,fetch:null,page:1,retweets:true,intro_text:null,outro_text:null,join_text:null,auto_join_text_default:"i said,",auto_join_text_ed:"i",auto_join_text_ing:"i am",auto_join_text_reply:"i replied to",auto_join_text_url:"i was looking at",loading_text:null,refresh_interval:null,twitter_url:"twitter.com",twitter_api_url:"api.twitter.com",twitter_search_url:"search.twitter.com",template:"{avatar}{time}{join}{text}",comparator:function(a,b){return b["tweet_time"]-a["tweet_time"]},filter:function(a){return true}},b);var d=/\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/gi;a.extend({tweet:{t:e}});a.fn.extend({linkUser:f(/(^|[\W])@(\w+)/gi,'$1@<a href="http://'+c.twitter_url+'/$2">$2</a>'),linkHash:f(/(?:^| )[\#]+([\w\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff\u0600-\u06ff]+)/gi,' <a href="http://'+c.twitter_search_url+"/search?q=&tag=$1&lang=all"+(c.username&&c.username.length==1&&!c.list?"&from="+c.username.join("%2BOR%2B"):"")+'">#$1</a>'),capAwesome:f(/\b(awesome)\b/gi,'<span class="awesome">$1</span>'),capEpic:f(/\b(epic)\b/gi,'<span class="epic">$1</span>'),makeHeart:f(/(<)+[3]/gi,"<tt class='heart'>&#x2665;</tt>")});return this.each(function(b,d){var f=a('<ul class="tweet_list">');var g='<p class="tweet_intro">'+c.intro_text+"</p>";var h='<p class="tweet_outro">'+c.outro_text+"</p>";var i=a('<p class="loading">'+c.loading_text+"</p>");if(c.username&&typeof c.username=="string"){c.username=[c.username]}a(d).bind("tweet:load",function(){if(c.loading_text)a(d).empty().append(i);a.getJSON(l(),function(b){a(d).empty().append(f);if(c.intro_text)f.before(g);f.empty();var i=a.map(b.results||b,n);i=a.grep(i,c.filter).sort(c.comparator).slice(0,c.count);f.append(a.map(i,function(a){return"<li>"+e(c.template,a)+"</li>"}).join("")).children("li:first").addClass("tweet_first").end().children("li:odd").addClass("tweet_even").end().children("li:even").addClass("tweet_odd");if(c.outro_text)f.after(h);a(d).trigger("loaded").trigger(i.length===0?"empty":"full");if(c.refresh_interval){window.setTimeout(function(){a(d).trigger("tweet:load")},1e3*c.refresh_interval)}})}).trigger("tweet:load")})}})(jQuery)



// onload

$(function () {

	// add read more link to reviews
	
	$('.review-quote blockquote p').expander({
		slicePoint: 140,
		detailClass: 'read-more-details'
	});
	
	// car parks table sorter
	
	$(".car-parks-table").tablesorter({
		headers: { 
			2: { 
				sorter:'transfers' 
			}
		},
		sortList: [[1,1],[3,1]]
	});
	 
	// load the thawte certificate
	
	$('#thawte-certificate').bind('click', function() {
		
		window.open('https://sealinfo.thawte.com/thawtesplash?form_file=fdf/thawtesplash.fdf&dn=*.ESSENTIALTRAVEL.CO.UK&lang=en','vnull','width=522,height=550');
			
	});
	
	var currentDate = new Date();
	var sYear = currentDate.getFullYear();
	var sMonth = currentDate.getMonth();
	var sDay = currentDate.getDate();
	
	$('#thawte-certificate div').html(sDay + " - " + (sMonth + 1) + " - " + sYear);
	
	// load more articles
	
	if (! typeof section == "undefined") {
		switch(section) {
			case "24-hour-guide":
				$('#nav-twenty-four').addClass('active');
			break;
			case "how-to":
				$('#nav-how-to').addClass('active');
			break;
			case "q-and-a":
				$('#nav-q-and-a').addClass('active');
			break;
			case "top-10":
				$('#nav-top-ten').addClass('active');
			break;
			case "review":
				$('#nav-reviews').addClass('active');
			break;
			case "feature":
				$('#nav-feature').addClass('active');
			break;
			default:
			  
		}
	}
	
	if ($('#article-list').find('.last-article').length ) {
		$('#load-more-articles').css({display:'none'});
	}
	
	$('#load-more-articles').live("click", function(){
	
		var vDataLoad = $(this).attr('data-load');
		var vDataSection = $(this).attr('data-section');
		
		$.ajax({
			url: 'http://'+window.location.host+'/magazine/load.asp?load=' + vDataLoad + "&section=" + vDataSection,
			success: function(data) {
				$('<div class="loaded">' + data + "</div>").appendTo('#article-list').fadeIn('fast');
				$('#load-more-articles').attr('data-load', parseInt(vDataLoad) + 11);
				if ($('#article-list').find('.last-article').length ) {
					$('#load-more-articles').css({display:'none'});
				}
			}
		});
		
	});
	
	$('#load-more-reviews').live("click", function(){
		
		$('#load-more-reviews').fadeOut();
		$('#loading-reviews').fadeIn();
		var vDataLoad = $(this).attr('data-load');
		var vDataSection = $(this).attr('data-section');
		var vCarParkCode = $(this).attr('data-airport');
		
		if (typeof template == 'undefined') {
			template = "";
		}
		
	
		
		$.ajax({
			url: 'http://'+window.location.host+'/'+vDataSection+'/load.asp?load=' + vDataLoad + '&carparkcode=' + vCarParkCode + '&template=' + template,
			success: function(data) {
				$('#loading-reviews').fadeOut();
				$(data).appendTo('#customer-reviews ol').fadeIn('fast');
				$('.review-quote blockquote p').expander({
					slicePoint: 140,
					detailClass: 'read-more-details'
				});
				
				$('#load-more-reviews').attr('data-load', parseInt(vDataLoad) + 11);
				
				$('#load-more-reviews').fadeIn();
				
				if ($('#customer-reviews ol').find('.last-article').length ) {
					$('#load-more-reviews').fadeOut();
				}
				
				if ( $('#customer-reviews ol li.review').length <= 11  ) {
					$('#load-more-reviews').fadeOut();
				}
			}
		});
		
	});
	
	// new aurport parking page
	
	$('#r-load').live("click", function(){
		
		$('#r-load').html('loading... &darr;');
		//$('#loading-reviews').fadeIn();
		var vDataLoad = $(this).attr('data-load');
		var vDataSection = $(this).attr('data-section');
		var vCarParkCode = $(this).attr('data-airport');
		
		if (typeof template == 'undefined') {
			template = "";
		}
		
	
		
		$.ajax({
			url: 'http://'+window.location.host+'/'+vDataSection+'/review-load.asp?load=' + vDataLoad + '&carparkcode=' + vCarParkCode + '&template=' + template,
			success: function(data) {
				$(data).appendTo('#more-reviews').fadeIn('fast');
				$('.review-data blockquote p').expander({
					slicePoint: 140,
					detailClass: 'read-more-details'
				});
				
				$('#r-load').attr('data-load', parseInt(vDataLoad) + 3);
				
				$('#r-load').fadeIn();
				
				$('#r-load').html('load more reviews &rarr;');
				
				$('#review-count-num').text($('.customer-review').length);
				
			}
		});
		
	});
	
	if ( $('#more-reviews').html() == "" ) {
		$('#r-load').trigger('click');
	}
	
	// display tweets
	
	$("#tweets div").tweet({
		avatar_size: 30,
		count: 5,
		query: "from:essentialtravel",
		loading_text: "searching twitter...",
		template: "{avatar} {text} {time}"
	});
	
	// set the divs to be the same height on the magazine homepage
	

	var q1 = $('.q-and-a-wrapper:eq(0)').height();
	var q1 = $('.q-and-a-wrapper:eq(0)').height();
	var q2 = $('.q-and-a-wrapper:eq(1)').height();
	var t1 = $('.top-ten-wrapper:eq(0)').height();
	var t2 = $('.top-ten-wrapper:eq(1)').height();
	
	var sameHeight = new Array(q1,q2,t1,t2);
	
	sameHeight.sort();
	
	var newheight = sameHeight[sameHeight.length - 1] + 30;
	
	$('.q-and-a-wrapper, .top-ten-wrapper').css({height:newheight});
	
	a = $('#q-and-a').height();
	b = $('#top-ten').height();

	if (a > b) {

		$('#top-ten').css({
			height: a
		});

	} else {

		$('#q-and-a').css({
			height: b
		});

	}
	
	c = $('#how-to').height();
	d = $('#twenty-four').height();

	if (c > d) {

		$('#twenty-four').css({
			height: c
		});

	} else {

		$('#how-to').css({
			height: d
		});

	}

	// add a modal window to any link that has a class of .ajax

	$(".ajax").colorbox({
		width:'600',
		height:'400',
		initialWidth:'600',
		initialHeight:'400'
	});
	
	// build a slideshow
	
	if ( $('#slides').length ) {
	
		$('#slides').slides({
			preload: true,
			preloadImage: 'https://images.essentialtravel.co.uk/new-et/modal/loading.gif',
			play: 5000,
			pause: 2500,
			hoverPause: true,
			effect: 'fade',
			crossfade: true,
			pagination: false,
			generatePagination: false,
			generateNextPrev: true
		});
	
	}

	// fix the iframe z-index bug

	$("iframe").each(function(){
		var ifr_source = $(this).attr('src');
		var wmode = "wmode=transparent";
		if (ifr_source.indexOf('?') != -1) {
			$(this).attr('src',ifr_source+'&'+wmode);
		} else {
			$(this).attr('src',ifr_source+'?'+wmode);
		}
	});
	
	// google +1 buttons
	
	if (typeof gapi !== 'undefined') {
		gapi.plusone.render("gplus", {size: "tall", count: "true"});
		gapi.plusone.render("gplus2", {size: "medium", count: "true"});
		gapi.plusone.render("gplus3", {size: "medium", count: "true"});
	}
	
	// blog share bar
	
	// new parking options
	
	if ( $('#options').length ) {
	
		$('.review-data blockquote p').expander({
			slicePoint: 140,
			detailClass: 'read-more-details'
		});
		
		 // fix sub nav on scroll
		var $win = $(window)
		  , $nav = $('#options')
		  , navTop = $('#options').length && $('#options').offset().top
		  , isFixed = 0;


		function processScroll() {
		  var i, scrollTop = $win.scrollTop()
		  if (scrollTop >= navTop && !isFixed) {
			isFixed = 1
			$nav.addClass('options-fixed')
			$('#carpark').css({marginTop:'150px'});
		  } else if (scrollTop <= navTop && isFixed) {
			isFixed = 0
			$('#carpark').css({marginTop:'0px'});
			$nav.removeClass('options-fixed')
		  }

		}
		
		processScroll();

		$win.on('scroll', processScroll);
		
		$('.carparks-option').click(function(){$('#carpark').ScrollTo(1200,{axis:'y',offset:-80 });return false});
		$('.reviews-option').click(function(){$('#reviews').ScrollTo(1200,{axis:'y',offset:-80 });return false});
		$('.map-option').click(function(){$('#maps').ScrollTo(1200,{axis:'y',offset:-80 });return false});
		$('.tips-option').click(function(){$('#tips').ScrollTo(1200,{axis:'y',offset:-80 });return false});
		
		$('.backtotop a, #sub-quote a, .large-quote a').click(function(){$('body').ScrollTo(1200);return false});
		
		$('#usps li a[href="#reviews"]').live('click', function(e){
			$('#reviews').ScrollTo(1200);
			e.preventDefault();
		});
		
		$('#usps li a[href="#tips"]').live('click', function(e){
			$('#tips').ScrollTo(1200);
			e.preventDefault();
		});
		
		$('.top-cp').on('click',function(){
	 
			var t = $(this).attr('data-code');
			
			$('#carparkreference').val(t);
			
			return false;
			
		});
		 
		$('.backtotop a, #sub-quote a, .car-parks-table .quote-btn, .large-quote a').click(function(){$('body').ScrollTo(1200);return false});
		
		$('.carparks-option').bind('mouseover', function(){
			$('.cp-count').css({visibility:'hidden'});
		}).bind('mouseout',function(){
			$('.cp-count').css({visibility:'visible'});
		});
		
		sLoaded = 0;
		
		$('.from-price a').mouseover(function(){
			if (sLoaded === 0) {
				$.ajax({
					url: 'http://'+window.location.host+'/popup/?airportparking.parking-prices-explained',
					success: function(data) {
						$(data).appendTo('#price-tool-tip');				
					}
				});
			}
			$('#price-tool-tip').fadeIn('fast');
			sLoaded = 1;
		}).mouseout(function(){
			$('#price-tool-tip').fadeOut('fast');
		}).click(function(){
			return false;
		});	
		
		$('tr').mouseover(function(){
			$(this).addClass('tr-over');
		}).mouseout(function(){
			$(this).removeClass('tr-over');
		});
		
	
	
	}
	
	
	
	if ( $('#share-bar').length > 0 ) {
	
		var winResize = function () {
		
			if ( $(window).width() < 1109 ) {
				$('#share-bar').fadeOut();
				$('.share-bar-sml').fadeIn().css({display:'inline-block'});
			} else {
				$('#share-bar').fadeIn();
				$('.share-bar-sml').fadeOut();
			}
		
		};
		
		winResize();
	
		var sh = $('#share-bar').offset().top;
		
		$(window).scroll(function () {
		
			var sc = $(window).scrollTop();

			$('#share-bar').css('position',((sc+10)>sh) ? 'fixed' : 'absolute');
			$('#share-bar').css('top',((sc+10)>sh) ? '10px' : '');
					
		});
		
		$(window).resize(function () {
			winResize();
		});
	
		
		$('.share-email a[href="#email"]').bind('click', function () {
			$(this).parent().find('.holder').fadeIn(100);
			return false;
		});
		
		$('.close-form').bind('click', function () {
			$(this).parent().fadeOut(100);
			$(this).parent().find('.form').slideDown(100);
			$(this).parent().find('.message').slideUp(100);
			$formEle = $('.form input:not([type="submit"]), .form textarea');
			$(this).parents().find($formEle).val('');
			return false;
		});
		
		$('#submit-1').bind('click', function () {
			var isValid = true;
			var to = $(this).parents().find('#to-1');
			var from = $(this).parents().find('#from-1');
			var message = $(this).parents().find('#message-1');
			var url = location.href;
			
			if ( to.val() === '' ) {
				to.addClass('not-valid');
				to.next().html('&times; Enter your friends email address');
				isValid = false;
			} else {
				to.next().html('');
				to.removeClass('not-valid');
			}
			
			if ( from.val() === '' ) {
				from.addClass('not-valid');
				from.next().html('&times; Enter your email address');
				isValid = false;
			} else {
				from.next().html('');
				from.removeClass('not-valid');
			}
			
			if ( message.val() === '' ) {
				message.addClass('not-valid');
				message.next().html('&times; Enter a message');
				isValid = false;
			} else {
				message.next().html('');
				message.removeClass('not-valid');
			}
			
			if (isValid === true) {
				$.ajax({
					url: 'http://'+window.location.host+'/magazine/share-email.asp',
					data: 'to='+to.val()+'&from='+from.val()+'&message='+message.val()+'&url='+url,
					success: function(data){
						$('#submit-1').parents().find('.form').slideUp(100);
						$('#submit-1').parents().find('.message').html(data).slideDown(100);
					}
				});
			}
			
			return false;
		
		});
		
		$('.form-reset').live('click', function () {
			var to = $(this).parents().find('#to-1').val('');
			$(this).parents().find('.form').slideDown(100);
			$(this).parents().find('.message').slideUp(100).html('');
			return false;
		});
	
	}
	
	// drop down menu
	
	$('#nav a[href="#"]').each(function(){
	
		$(this).bind('click',function(){
				return false;
		});

		$(this).css({cursor:'default'});

	});
	
	$("#nav li").hoverIntent({    
		sensitivity: 1,   
		interval: 50,    
		over: function () {
			$(this).addClass('hover-active');
			$('.holder',this).bgiframe().fadeIn(100);
		},
		timeout: 100,  
		out: function () {
			$(this).removeClass('hover-active');
			$('.holder',this).fadeOut(100);
		}
	});
	
	//  /MSIE 6/i.test(navigator.userAgent)
	
	// display hidden content if javascript is turned on

	$('.no-js').css({display:'block'});

	// Current Date ====================================================================

	var today = new Date();
	var month = today.getMonth() + 1;
	var day = today.getDate();
	var year = today.getFullYear();
	
	function addDays(d) {
	
		var p = new Date();
		p.setDate( p.getDate() + d );
		var days = p.getDate();
	
		return days +'/'+ month +'/'+ year;
	
	}
	
	var dateStringPlus1 = addDays(1);
	var dateStringPlus5 = addDays(5);
	
	var todaysDate = Date.parse(month +'/'+ day +'/'+ year);
	var dateString = day +'/'+ month +'/'+ year;
	
	// loading quote pop up.
	
	var currentProduct = $('input[name="product"]').val();
	
	if ( ( $('.quote-form').length > 0 ) && ( typeof currentProduct !== 'undefined')  )  {
	
		
		var productFolder = '';
		
		if ( currentProduct == 'lounges') {
			productFolder = 'airportlounges';
		} else {
			productFolder = currentProduct;
		}
		
		$.ajax({
			url: '/'+ productFolder +'/loading.html',
			success: function(data) {
				loadingHtml = data;
			},
			statusCode: {
				404: function() {
					loadingHtml = "<h1>Loading Quote...</h1>";
				}
			}
		});
	}
	
	// Trip Type Change ====================================================================
	
	$('#trip-type').bind('change keyup', function () {
	
		var triptype = $(this).val();
		
		var options = "";
		
		var optionMap = {
			'0' : '-- select --',
			'1' : '1',
			'2' : '2',
			'3' : '3',
			'4' : '4',
			'5' : '5',
			'6' : '6',
			'7' : '7',
			'8' : '8',
			'9' : 'over 8'
		};
		
		var travellers = $('#number-travellers').val();
		
		switch(triptype) {
		
			case 'single': case 'singleski': case 'multi': case 'multiski':
				
				$.each(optionMap, function(val, text) {
				
					options += '<option value="'+ val +'">'+ text +'</option>';
					
				});
								
			break;
			
			case 'backpacker': case 'backpackerski':
								
				$.each(optionMap, function(val, text) {
				
					options += '<option value="'+ val +'">'+ text +'</option>';
					
					return (this != "2");
					
				});
								
				if ( travellers > 2 ) {
					travellers = 2;
				}
			
			break;

		}
		
		$('#number-travellers').find('option').remove().end().append(options).val(travellers).trigger('change');
	
	});
	
	$('#trip-type').trigger('change');

	// Date Pickers ====================================================================

	function chiDates() {
		
		var vChiStartDate = $('#start-date').val();
		vChiStartDate = vChiStartDate.split("/");
		var vChiEndDate = $('#end-date').val();
		vChiEndDate = vChiEndDate.split("/");
		
		$('input[name="StartDateDay"]').val(vChiStartDate[0]);
		$('input[name="StartDateMonth"]').val(vChiStartDate[1]);
		$('input[name="StartDateYear"]').val(vChiStartDate[2]);
		
		$('input[name="EndDateDay"]').val(vChiEndDate[0]);
		$('input[name="EndDateMonth"]').val(vChiEndDate[1]);
		$('input[name="EndDateYear"]').val(vChiEndDate[2]);
					
	}
	
	$('#start-date').val(dateString).datepicker({
		dateFormat: 'd/m/yy',
		firstDay: 1,
		maxDate: '+1y',
		changeMonth: true,
		changeYear: true,
		onSelect: function (date) {
			$('#end-date').datepicker('option', {minDate: $('#start-date').val()});
			if ( currentProduct == 'carhireinsurance') {
				chiDates();
			}
		},
		minDate: new Date()
	}).attr('readonly', true);
	
	
	$('#end-date').val(dateString).datepicker({
		dateFormat: 'd/m/yy',
		firstDay: 1,
		maxDate: '+1y',
		changeMonth: true,
		changeYear: true,
		minDate: $('#start-date').val(),
		onSelect: function (date) {
			if ( currentProduct == 'carhireinsurance') {
				chiDates();
			}
		}
	}).attr('readonly', true);
	
	if ( currentProduct == 'carhireinsurance') {
	
		chiDates();
		
	}

	// Airport Lounges
	
	var loungesCookieStart = dateStringPlus1;
	
	if ( $.cookie('lounges_quote') !== null ) {
	
		var cookieStartDate = $.cookie('lounges_quote').split('||'),
		cookieStartDate = cookieStartDate[0].split('/'),
		todaysDatePlus1 = Date.parse(month +'/'+ (day + 1) +'/'+ year),
		cookieDate = Date.parse(cookieStartDate[1] + "/" + cookieStartDate[0] + "/" + cookieStartDate[2]);
		
		if ( cookieDate < todaysDatePlus1 ) {
			loungesCookieStart = dateStringPlus1;
		} else {
			loungesCookieStart = cookieStartDate[0] + "/" + cookieStartDate[1] + "/" + cookieStartDate[2];
		}
		
	}

	
	$('#lounge-start-date').val(loungesCookieStart).datepicker({
		dateFormat: 'd/m/yy',
		firstDay: 1,
		maxDate: '+1y',
		changeMonth: true,
		changeYear: true,
		minDate: +1,
		onSelect: function(){
			var vDate = $('#lounge-start-date').val();
			var aDate = vDate.split("/");
			$('input[name="arrivaldateday"]').val(aDate[0]);
			$('input[name="arrivaldatemonth"]').val(aDate[1]);
			$('input[name="arrivaldateyear"]').val(aDate[2]);
		}
	}).attr('readonly', true); 
	
	var vDate = $('#lounge-start-date').val();
	
	if (typeof vDate != 'undefined' ) {
		var aDate = vDate.split("/");
		$('input[name="arrivaldateday"]').val(aDate[0]);
		$('input[name="arrivaldatemonth"]').val(aDate[1]);
		$('input[name="arrivaldateyear"]').val(aDate[2]);
	}
	
	// AP
	
	var parkingCookieStart = dateString;
	var parkingCookieEnd = dateStringPlus5;
	
	if ( $.cookie('parking_quote') !== null ) {
	
		var cookieQuote = $.cookie('parking_quote').split('||'),
		cookieStartDate = cookieQuote[0].split('/'),
		cookieEndDate = cookieQuote[1].split('/'),
		todaysDate = Date.parse(month +'/'+ day +'/'+ year),
		cookieQuoteStart = Date.parse(cookieStartDate[1] + "/" + cookieStartDate[0] + "/" + cookieStartDate[2]),
		cookieQuoteEnd = Date.parse(cookieEndDate[1] + "/" + cookieEndDate[0] + "/" + cookieEndDate[2]);
		
		if ( cookieQuoteStart < todaysDate ) {
			parkingCookieStart = dateString;
		} else {
			parkingCookieStart = cookieStartDate[0] + "/" + cookieStartDate[1] + "/" + cookieStartDate[2];
		}
		
		if ( cookieQuoteEnd < todaysDate ) {
			parkingCookieEnd = dateStringPlus5;
		} else {
			parkingCookieEnd = cookieEndDate[0] + "/" + cookieEndDate[1] + "/" + cookieEndDate[2];
		}
		
		// times
		
		$('#parking-from-time').val(cookieQuote[2]);
		$('#parking-returning-time').val(cookieQuote[3]);
		
	}
	
	$('#parking-from').val(parkingCookieStart).datepicker({
		dateFormat: 'd/m/yy',
		firstDay: 1,
		maxDate: '+1y +11m',
		changeMonth: true,
		changeYear: true,
		onSelect: function (date) {
			$('#parking-returning').datepicker('option', {minDate: $('#parking-from').val()});
		},
		minDate: new Date()
	}).attr('readonly', true);
	
	
	$('#parking-returning').val(parkingCookieEnd).datepicker({
		dateFormat: 'd/m/yy',
		firstDay: 1,
		maxDate: '+1y +11m',
		changeMonth: true,
		changeYear: true,
		minDate: $('#parking-from').val()
	}).attr('readonly', true);
	
	try {
		$('#airport').val(sDefaultAirportCode);
	} catch(e) {
	}

		
	// Number Of Travellers ====================================================================
	
	$('#number-travellers').val( $("#number-travellers option:first").val() );
		
	$('#number-travellers').bind('change keyup', function () {
	
		var travellers = $('#number-travellers').val();
		
		$('.age-boxes ul li').css({display: 'none'});
			
		if ( travellers == 0 ) {
		
			$('#travellers-ages').slideUp('fast');
			
		} else {
		
			$('#travellers-ages').fadeIn('fast');
			
		}

		for ( var x = 1; x <= travellers; x++ ) {
		
			 $('.age-boxes ul li:nth-child('+ x +')').fadeIn('fast');
		
		}
		
		for ( var y = x; y <= $('.age-boxes ul li').length; y++ ) {
		
			$('.age-boxes ul li:nth-child('+ y +') input').val('');
			
		}
		
	});
	
	// Form Validation ====================================================================

    var Validate = {
        dates: {
			 today: function () {

                var t = new Date();
                var m = t.getMonth() + 1;
                var d = t.getDate();
                var y = t.getFullYear();

                return Date.parse(m + '/' + d + '/' + y);

            },
            dateFormatCheck: /^\d{1,2}(\/)\d{1,2}\1\d{4}$/,
            dateCheckErr: 'Please enter your dates in the correct format dd/mm/yyyy\n',
            dateCheck: function (a) {

                var b = Validate.dates.dateFormatCheck.test(a.val());

                if (b) {

                    a.removeClass(Validate.errorClass);

                    return true;

                } else {

                    a.addClass(Validate.errorClass);

                    return false;

                }

            },
            pastDateErr: 'Your chosen date is in the past\n',
            pastDate: function (a, b) {

                if (typeof (a) === 'object') {

                    var c = a.val().split('/');

                    c = Date.parse(c[1] + '/' + c[0] + '/' + c[2]);

                } else if (typeof (a) === 'number') {

                    var c = a;

                }

                if (typeof (b) === 'object') {

                    var d = b.val().split('/');

                    d = Date.parse(d[1] + '/' + d[0] + '/' + d[2]);

                } else if (typeof (b) === 'number') {

                    var d = b;

                }

                if (c < d) {

                    if (typeof (a) === 'object') {
                        a.addClass(Validate.errorClass);
                    }

                    return false;
                } else {
                    return true;
                }

            },
			daysInMonthErr: 'Your chosen day does not exist in the chosen month\n',
			daysInMonth: function (a) {
			
                var c = a.val().split('/'),
				day = c[0],
				month = c[1] - 1,
				year = c[2];
			
				function daysInMonth(m, y) { // m is 0 indexed: 0-11
					switch (m) {
						case 1 :
							return (y % 4 == 0 && y % 100) || y % 400 == 0 ? 29 : 28;
						case 8 : case 3 : case 5 : case 10 :
							return 30;
						default :
							return 31
					}
				}
				
				function isValid(d, m, y) {
					return m >= 0 && m < 12 && d > 0 && d <= daysInMonth(m, y);
				}
				
				isValid(day, month, year);
			}
        },
		postCode : function () {
		
		
		},
		values:{
			allZero: function(a) {
			
				var c = 0;
				
				for (b = 0; b <= a.length - 1; b++) {
					c = c + parseInt(a[b]);
				}
				
				if ( c === 0 ) {
					return false;
				} else {
					return true;
				}
			},
			allZeroErr: 'You need to select at least 1 traveller',
			allZeroDriverErr: 'You need to select at least 1 driver'
			
		},
        errorClass: 'not-valid'
    };
	
	
	
	$('#submit').bind('click', function () {

		var errors = '',
			startDate = $('.start'),
			endDate = $('.end'),
			product = $('#product'),
			startTime = $('#parking-from-time'),
			endTime = $('#parking-returning-time'),
			airport = $('#airport').val(),
			aStartDate = startDate.val().split("/");
									
			if ( typeof startTime.val() != 'undefined' ) {
			
				var aStartTime = startTime.val().split(":");
			
			}
			
			if ( typeof endDate.val() != 'undefined' ) {
			
				var aEndDate = endDate.val().split("/");			
			
			}
			
			if ( typeof endTime.val() != 'undefined' ) {
			
				aEndTime = endTime.val().split(":");
			
			}

		//parking
		if ( currentProduct == 'airportparking') {
			$('#ap').val(airport);
			$('#ddd').val(aStartDate[0]);
			$('#ddm').val(parseInt(aStartDate[1]));
			$('#ddy').val(aStartDate[2]);
			$('#dth').val(aStartTime[0]);
			$('#dtm').val(aStartTime[1]);
			$('#rdd').val(aEndDate[0]);
			$('#rdm').val(parseInt(aEndDate[1]));
			$('#rdy').val(aEndDate[2]);
			$('#rth').val(aEndTime[0]);
			$('#rtm').val(aEndTime[1]);
		}
		
		// set cookies for the current quote
		
		if ( currentProduct == 'lounges' ) {
		
			$.cookie('lounges_quote', startDate.val() + "||" + $('#arrivaltime').val() + "||" + $('#adults').val() + '||' + $('#children').val() + '||' + $('#infants').val(), { expires: 30 });
			
		} else if ( currentProduct == 'airportparking' ) {
		
			$.cookie('parking_quote', startDate.val() + "||" + endDate.val() + "||" + $('#parking-from-time').val() + "||" + $('#parking-returning-time').val(), { expires: 30 });
		
		}
		
		
		
		// check to see if total travellers is greater than 0
		
		var adults = $('#adults'),
		children = $('#children'),
		infants = $('#infants'),
		drivers = $('#Drivers');
		
		if ( typeof adults.val() != 'undefined' || typeof children.val() != 'undefined' || typeof infants.val() != 'undefined' ) {
		
			var totalTravellers = new Array(adults.val(), children.val(), infants.val());

			if (!Validate.values.allZero(totalTravellers)) {

				errors += Validate.values.allZeroErr;
				adults.addClass(Validate.errorClass);
				children.addClass(Validate.errorClass);
				infants.addClass(Validate.errorClass);
			}
		
		}
		
		if ( typeof drivers.val() != 'undefined' ) {
		
			var totalTravellers = new Array(drivers.val());

			if (!Validate.values.allZero(totalTravellers)) {

				errors += Validate.values.allZeroDriverErr;
				drivers.addClass(Validate.errorClass);
				
			}
		
		}
		
		
		// check to see if the start date month has the chosen amount of days
		/*if (!Validate.dates.daysInMonth(startDate)) {

			errors += Validate.dates.daysInMonthErr;

		}*/
				
		// check to see if the start date is in the correct format
		if (!Validate.dates.dateCheck(startDate)) {

			errors += Validate.dates.dateCheckErr;

		}

		// check to see if the start date is in the correct format
		if (!Validate.dates.dateCheck(startDate)) {

			errors += Validate.dates.dateCheckErr;

		}

		// check to see if the end date is in the correct format
		if ( typeof endDate.val() != 'undefined' ) {
			if (!Validate.dates.dateCheck(endDate)) {

				errors += Validate.dates.dateCheckErr;

			}
		}

		// check to see if the start date is before the today
		if (!Validate.dates.pastDate(startDate, Validate.dates.today())) {

			errors += 'Your trip start date is before today.\n';

		}
		
		// check to see if the end date is before the start date
		if ( typeof endDate.val() != 'undefined' ) {
			if (!Validate.dates.pastDate(endDate, startDate)) {

				errors += 'Your trip end date is before your start date.\n';

			}
		}

		// output errors
		if (errors !== '') {

			alert(errors);
			return false;

		} else {
		
			$.colorbox({
				overlayClose: false,
				html:loadingHtml,
				onComplete:function(){
				
					$('#loading-x').live('myEvent', function(){
						$(this).delay(2000).html('<img src="https://images.essentialtravel.co.uk/et/loading.gif" width="100" height="100">');
						$('#cboxClose').css({display:'none'});
					});
					
					$('#loading-x').trigger('myEvent');
					
				}
			});
			
			return true;

		}

	});
	
	$('select.people').bind('change',function(){
		$('select.people').removeClass('not-valid');
	});
	
	$('#TripType').bind('change',function(){
		
		if ( $(this).val() == 'annual' ) {
			$('#end-date-row').fadeOut('fast');
		} else {
			$('#end-date-row').fadeIn('fast');
		}
	
	});

	// fix hover effect on the tab navigation in IE6 (IESucks)
	
	$('.tab-nav li').hover(
		function () {
			$(this).addClass('over');
		},
		function () {
			$(this).removeClass('over');
		}
	);
	
	// fix :last-child psuedo class on the blog article info list in IE6 (IESucks)
	
	$('.article-info li:last-child').css({border:'none', marginRight:0, paddingRight:0});
	
	// tab nav functions
	
	$('.tab-panel').not(':eq(0)').css({display:'none'});
	
	$('.overall-score').css({display:'none'});
	
	if ( $('#maps').length ) {
		var timerId = setTimeout(function() {initialize()}, 500);
	}

	$('.tab-nav li a').bind('click', function (event) {
	
		event.preventDefault();

		$('.tab-nav li').removeClass('selected');
		
		$(this).parent().addClass('selected');
		
		var panel = $(this).attr('href');
		
		//window.location.hash = panel;
		
		$('.tab-panel:visible').css({display:'none'});
				
		if ( panel === '#map' ) {
			
			$(panel).slideDown('slow', function(){
				
				if ( $('#map_canvas').html() === '' ) {
					var timerId = setTimeout(function() {initialize()}, 500);
				}
				
			});

		} else {
		
			$(panel).slideDown('slow');
			
		}

		if ( panel === '#reviews' ) {
		
			$('.overall-score').slideDown('slow');
			
		} else {
		
			$('.overall-score').slideUp('slow');
			
		}
		
		//window.location.hash = panel;
		
		//return false;
		
	});
	
	$('.tab-nav li a[href="'+window.location.hash+'"]').trigger('click');

	/*$('#reviews-count').bind('click', function(){
		 
		$('.tab-nav li a[href="#reviews"]').trigger('click');
		
		return false;
	});*/
	
	$('a:not(.tab-nav li a, #options li a)[href="#reviews"]').live('click', function(e){
		if ( $('#reviews').is(':hidden') ) {
			$('.tab-nav li a[href="#reviews"]').trigger('click');
		}
		$('.tab-nav').ScrollTo(1200);
		e.preventDefault();
		//return false;
	});
	
	$('a:not(.tab-nav li a)[href="#map"]').live('click', function(){
		$('.tab-nav li a[href="#map"]').trigger('click');
		return false;
	});
	
	$('a:not(.tab-nav li a, #options li a)[href="#tips"]').live('click', function(){
		$('.tab-nav li a[href="#tips"]').trigger('click');
		return false;
	});
	
	$('a:not(.tab-nav li a)[href="#overview"]').live('click', function(){
		$('.tab-nav li a[href="#overview"]').trigger('click');
		return false;
	});
	
	$('a:not(.tab-nav li a)[href="#parkride"]').live('click', function(){
		$('.tab-nav li a[href="#parkride"]').trigger('click');
		return false;
	});
	
	$('a:not(.tab-nav li a)[href="#meetgreet"]').live('click', function(){
		$('.tab-nav li a[href="#meetgreet"]').trigger('click');
		return false;
	});
	
	
	// google maps and directions api
	if (typeof longLat !== 'undefined') {
	
		longLat = longLat.replace(" ","").split("~");
		
		if (typeof airportLocation !== 'undefined') {
		
			if (airportLocation !== '') {
		
				airportLocation = airportLocation.replace(" ","").split("~");
				var apLong = parseFloat(airportLocation[0]),
				apLat = parseFloat(airportLocation[1]);
			
			}
		}
	
	
		var longitude = parseFloat(longLat[0]), 
			latitude = parseFloat(longLat[1]),
			zoom = parseFloat(longLat[2]),
			directionsDisplay,
			map;
	
		var directionsService = new google.maps.DirectionsService();

		function initialize() {
		
			directionsDisplay = new google.maps.DirectionsRenderer();
			
			var carpark = new google.maps.LatLng(longitude, latitude);
			
			if (typeof airportLocation !== 'undefined') {
		
				if (airportLocation !== '') {
				var airport = new google.maps.LatLng(apLong, apLat);
				}
			}
			
			var myOptions = {
				zoom: zoom,
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				center: carpark,
				scrollwheel: false
			}
			map = new google.maps.Map($("#map_canvas")[0], myOptions);
			
			if (typeof carParks !== 'undefined') {
			
				var marker = new google.maps.Marker({
					position: carpark,
					icon: new google.maps.Marker({
						url: 'https://images.essentialtravel.co.uk/new-et/airport-map.png',
						size: google.maps.Size(25, 34),
						origin: google.maps.Point(0,0),
						anchor: google.maps.Point(12, 34)
					}),
					shadow: new google.maps.Marker({
						url: 'https://images.essentialtravel.co.uk/new-et/carpark-shadow-map.png',
						size: google.maps.Size(44, 18),
						origin: google.maps.Point(0,0),
						anchor: google.maps.Point(0, 44)
					}),
					zIndex:2,
					map: map,
					animation: google.maps.Animation.DROP
				});
			
			} else {
				
				if (typeof airportLocation !== 'undefined') {
		
					if (airportLocation !== '') {
				
						var apMarker = new google.maps.Marker({
							position: airport,
							icon: new google.maps.Marker({
								url: 'https://images.essentialtravel.co.uk/new-et/airport-map.png',
								size: google.maps.Size(25, 34),
								origin: google.maps.Point(0,0),
								anchor: google.maps.Point(12, 34)
							}),
							shadow: new google.maps.Marker({
								url: 'https://images.essentialtravel.co.uk/new-et/carpark-shadow-map.png',
								size: google.maps.Size(44, 18),
								origin: google.maps.Point(0,0),
								anchor: google.maps.Point(0, 44)
							}),
							zIndex:2,
							map: map,
							animation: google.maps.Animation.DROP
						});
					
					}
				
				}
				
				if ( template == '24-hour-guide.asp') {
					i = 'https://images.essentialtravel.co.uk/new-et/country-large-map.png';
				} else {
					i = 'https://images.essentialtravel.co.uk/new-et/carpark-large-map.png';
				}
			
				var marker = new google.maps.Marker({
					position: carpark,
					icon: new google.maps.Marker({
						url: i,
						size: google.maps.Size(25, 34),
						origin: google.maps.Point(0,0),
						anchor: google.maps.Point(12, 34)
					}),
					shadow: new google.maps.Marker({
						url: 'https://images.essentialtravel.co.uk/new-et/carpark-shadow-map.png',
						size: google.maps.Size(44, 18),
						origin: google.maps.Point(0,0),
						anchor: google.maps.Point(0, 44)
					}),
					map: map,
					animation: google.maps.Animation.DROP
				});
			
			}
			
			
			if (typeof carParks !== 'undefined') {
			
				var infowindow = new google.maps.InfoWindow();
				
				var mCarParks, i;
				
				// add car parks
				
				for (i = 0; i < carParks.length; i++) {  
					mCarParks = new google.maps.Marker({
						position: new google.maps.LatLng(carParks[i][0], carParks[i][1]),
						icon: new google.maps.Marker({
							url: 'https://images.essentialtravel.co.uk/new-et/carpark-map.png',
							size: google.maps.Size(18, 25),
							origin: google.maps.Point(0,0),
							anchor: google.maps.Point(9, 25)
						}),
						shadow: new google.maps.Marker({
							url: 'https://images.essentialtravel.co.uk/new-et/carpark-shadow-map.png',
							size: google.maps.Size(44, 18),
							origin: google.maps.Point(0,0),
							anchor: google.maps.Point(0, 44)
						}),
						zIndex:1,
						map: map,
						animation: google.maps.Animation.DROP,
						title: carParks[i][2] + ' (' + carParks[i][4] + ')'
					});	
					
					google.maps.event.addListener(mCarParks, 'click', (function(mCarParks, i) {
						return function() {
						  infowindow.setContent('<p><a href="' + carParks[i][3] + '">' + carParks[i][2] + '</a></p><p><strong>Car Park Type:</strong> ' + carParks[i][4] + '</p>');
						  infowindow.open(map, mCarParks);
						}
					 })(mCarParks, i));
				}
			
			}
			
			directionsDisplay.setMap(map);
			directionsDisplay.setPanel($("#directionsPanel")[0]);
		}

		function calcRoute() {
			var start = $('#post-code').val();
			var end = longitude + ',' + latitude;
			var request = {
				origin: start,
				destination: end,
				travelMode: google.maps.TravelMode.DRIVING
			};
			directionsService.route(request, function (response, status) {
				if (status == google.maps.DirectionsStatus.OK) {
					directionsDisplay.setDirections(response);
				}
			});
		}
		
			// post code for google directions
		
		$('#post-code-directions').bind('click', function(){
		
			calcRoute();
			
			return false;
		});
	
	}

// lounges

function toDate() {
	vToday = new Date();
	vToday.setDate(vToday.getDate()+1);

	d = vToday.getDate();
	m = vToday.getMonth();
	y = vToday.getFullYear();

	$('#arrivaldateday').val(d);
	$('#arrivaldatemonth').val(m + 1);
	$('#arrivaldateyear').val(y);
}

if ( $.cookie('lounges_quote') !== null ) {
	
	var loungesPeople = $.cookie('lounges_quote').split('||');
	
	if ( loungesPeople[2] + loungesPeople[3] + loungesPeople[4] > 0 ) {
		$('#adults').val(loungesPeople[2]);
		$('#children').val(loungesPeople[3]);
		$('#infants').val(loungesPeople[4]);
	}
}

if ( typeof sDefaultCountryName != 'undefined') {
	$('#country').val(sDefaultCountryName);
	countryChanger();
}

$('#country').change(function() {
	countryChanger();
});

$('#airport, #arrivaldateday, #arrivaldatemonth, #arrivaldateyear').change(function() {
	timeChanger();
});


function countryChanger() {
	
	var sName = $('#country').val();

	$.ajax({
		url: '/quote/countryairports.asp',
		data: 'name='+sName,
		cache: false,
		success: function(html){
			eval(html);

			setTimeout(selectDefaultAirport, 1000);
		}
	});
}

function selectDefaultAirport() {
	if ($("#country").val() == sDefaultCountryName) {
	
		var oSel = document.getElementById('airport');

		for (var iInc = 0; iInc < oSel.options.length; iInc++) {
			if (oSel.options[iInc].value == sDefaultAirportCode) {
				oSel.selectedIndex = iInc;

				timeChanger();
			}
		}
	} else {
		timeChanger();
	}
}

function timeChanger() {
	var aStartDate = $('#lounge-start-date').val().split('/');
	var sCode = $('#airport').val();
	var iDay = aStartDate[0];
	var iMonth = aStartDate[1];
	var iYear = aStartDate[2];
	var sTime = $('#arrivaltime').val();

	if (sTime == null) sTime = "";

	var iAdults = $('#adults').val();
	var iChildren = $('#children').val();
	var iInfants = $('#infants').val();

	$.ajax({
		url: '/quote/airporttimes.asp',
		data: 'code='+sCode+'&day='+iDay+'&month='+iMonth+'&year='+iYear+'&time='+sTime+'&adults='+iAdults+'&children='+iChildren+'&infants='+iInfants,
		cache: false,
		success: function(html){
			eval(html);
			if ( $.cookie('lounges_quote') !== null ) {
				var time = $.cookie('lounges_quote').split('||');
				$('#arrivaltime').val(time[1]);
			}
		}
	});
}

function validate() {
	if($('#country').val() == '') {
		alert('Please select a country.');

		return false;
	} else {
		if ($('#arrivaltime').val() == '') {
			alert('Please select an arrival time.');

			return false;
		} else {
			var ArrivalDay =$("#arrivaldateday").val();
			var ArrivalMonth=$("#arrivaldatemonth").val();
			var ArrivalYear =$("#arrivaldateyear").val(); 

			var startDate=new Date();
			var today=new Date();

			startDate.setFullYear(ArrivalYear,ArrivalMonth-1,ArrivalDay);

			var dd = new Date(ArrivalYear,ArrivalMonth, 0);
			var totalDaysMonth=dd.getDate();

			if (startDate<today) {
				alert("Invalid arrival date");
				var text= document.getElementById("arrivaldateday");
				text.focus(); 

				return false;
			} else if (ArrivalDay>totalDaysMonth) {
				alert ("There are not "+ ArrivalDay+" Days in the start month you provided. Please amend to continue.")

				return false;
			} else {
				if (ArrivalMonth==2) {
					if(ArrivalYear%400 ==0 || (ArrivalYear%100 != 0 && ArrivalYear%4 == 0)) {
						if (ArrivalDay>29) {
							alert("Invalid arrival date");

							return false;
						}
					} else {
						if (ArrivalDay>28) {
							alert("Invalid arrival date");

							return false;
						}
					}
				}

				return LoadingQuote();
			}
		}
	}
}

// CH	

if  ( currentProduct == 'carhire' ) {

	var sGap = '&' + 'nbsp;'
	var bOverAutocomplete = false;
	var bOverPickup = false;
	var bOverReturnTo = false;
	var sThing;
	var sMonths='JanFebMarAprMayJunJulAugSepOctNovDec';
	
	weekFromToday = new Date();
	weekFromToday.setDate(weekFromToday.getDate()+7);
	weekFromTodayDay = weekFromToday.getDate();
	weekFromTodayMonth = weekFromToday.getMonth()+1;
	weekFromTodayYear = weekFromToday.getFullYear();
	
	function formatty(row) {
		var sValue = row[1];
		sThing = jQuery(this).attr('id');

		if (sValue.indexOf('$$') >= 0) {
			var aValues = sValue.split('$$');

			return '<div style="position: relative; top: -2px; background-color: #000; color: #fff; width: 100%; font-weight: bold; height: 13px; padding-top: 2px; padding-bottom: 2px;">'+aValues[1]+'</div>'+sGap+row[0];

		} else {
			return sGap+row[0];

		}
	}

	jQuery('#pickupDate').val(sDay + ' ' + sMonths.substr(((sMonth) * 3), 3) + ' ' + sYear);
	jQuery('#returnDate').val(weekFromTodayDay + ' ' + sMonths.substr(((weekFromTodayMonth - 1) * 3), 3) + ' ' + weekFromTodayYear);

	
	jQuery('#pickup, #returnto').keypress( function() {
		jQuery('#'+jQuery(this).attr('id')+'id').val('');
	} );

	jQuery('#pickup').autocomplete(
	'/quote/carhire_countries.asp',
	{
		delay:10,
		minChars:3,
		matchSubset:false,
		autoFill:false,
		maxItemsToShow:1000,
		formatItem: formatty,
		onItemSelect: function(row) {
			selecty(this, row);

			//Get id
			sValue = row.extra[0];

			if (sValue.indexOf('$$') >= 0) {
				var aValues = sValue.split('$$');

				sValue = aValues[0];

			}

			jQuery('#pickupid').val(sValue);

			if (jQuery('#returnto').val() == 'Please type your return location') {
				jQuery('#returnto').val(jQuery('#pickup').val());
				jQuery('#returntoid').val(jQuery('#pickupid').val());
			}
		},
		width: 220
	});

	jQuery('#returnto').autocomplete(
	'/quote/carhire_countries.asp',
	{
		delay:10,
		minChars:3,
		matchSubset:false,
		autoFill:false,
		maxItemsToShow:1000,
		formatItem: formatty,
		onItemSelect: function(row) {
			selecty(this, row);

			//Get id
			sValue = row.extra[0];

			if (sValue.indexOf('$$') >= 0) {
				var aValues = sValue.split('$$');

				sValue = aValues[0];

			}

			jQuery('#returntoid').val(sValue);

			bOverPickup = false;
		},
		width: 220
	});

	jQuery('#pickup').hover( function() {
		bOverPickup = true;
	}, function() {
		bOverPickup = false;
	});

	jQuery('#returnto').hover( function() {
		bOverReturnTo = true;
	}, function() {
		bOverReturnTo = false;
	});

	/*jQuery(document).mousedown( function() {
		if ((!(bOverAutocomplete))&&(!(bOverPickup))) {
			jQuery('#pickup')[0].autocompleter.hideIt();
		}

		if ((!(bOverAutocomplete))&&(!(bOverReturnTo))) {
			jQuery('#returnto')[0].autocompleter.hideIt();
		}
	});*/


	

	function selecty(thissy, row) {
		var sValue = row.innerHTML;
		var aValues = sValue.split(sGap);

		sValue = aValues[1];

		jQuery(thissy).val(sValue);

	}

	jQuery('#pickup, #returnto').focus( function () {
		jQuery(this).val('');
	});
	
	$('#carhire-submit').bind('click',function(){
		
		return chvalidate();
	
	});

	function chvalidate() {
		if((jQuery('#pickupid').val() == '') || (jQuery('#pickup').val() == '') || (jQuery('#pickup').val() == 'Please type your pick up location')) {
			alert('Please select a pick up location.');

			jQuery('#pickup').focus();

			return false;

		} else if((jQuery('#returntoid').val() == '') || (jQuery('#returnto').val() == '') || (jQuery('#returnto').val() == 'Please type your pick up location')) {
			alert('Please select a return to location.');

			jQuery('#returnto').focus();

			return false;

		} else {
			var dNow = new Date();

			var sDate = jQuery('#pickupDate').val();
			var sTime = jQuery('#pickupTime').val();
			var dPickUp = stringToDate(sDate, sTime);

			sDate = jQuery('#returnDate').val();
			sTime = jQuery('#returnTime').val();
			var dReturn = stringToDate(sDate, sTime);

			if(dPickUp < dNow) {
				alert('You have selected a pick up date in the past. Please try again.');
				return false;

			} else if(dReturn < dPickUp) {
				alert('You have selected a return date before your pick up date. Please try again.');
				return false;

			} else {
				return true;

			}
		}
	}

	function stringToDate(sDate, sTime) {
		var aDate = sDate.split(' ');
		var iMonth;

		switch(aDate[1]) {
			case 'Jan':
				iMonth = 0;
				break;

			case 'Feb':
				iMonth = 1;
				break;

			case 'Mar':
				iMonth = 2;
				break;

			case 'Apr':
				iMonth = 3;
				break;

			case 'May':
				iMonth = 4;
				break;

			case 'Jun':
				iMonth = 5;
				break;

			case 'Jul':
				iMonth = 6;
				break;

			case 'Aug':
				iMonth = 7;
				break;

			case 'Sep':
				iMonth = 8;
				break;

			case 'Oct':
				iMonth = 9;
				break;

			case 'Nov':
				iMonth = 10;
				break;

			case 'Dec':
				iMonth = 11;

		}

		var aTime = sTime.split(':');
		var dDate = new Date(aDate[2], iMonth, aDate[0], aTime[0], aTime[1], 0);

		return dDate;
	}

	function catcalc(cal) {
		var date = cal.date;
		var time = date.getTime()
		// use the _other_ field
		var field = document.getElementById("returnDate");
		if (field == cal.params.inputField) {
			field = document.getElementById("pickupDate");
			time -= Date.WEEK; // substract one week
		} else {
			time += Date.WEEK; // add one week
		}
		var date2 = new Date(time);
		field.value = date2.print("%d %b %Y");
	}
	Calendar.setup({
		inputField	:	"pickupDate",
		ifFormat	:	"%d %b %Y",
		onUpdate	:	catcalc
	});
	Calendar.setup({
		inputField	:	"returnDate",
		ifFormat	:	"%d %b %Y"
	});
	
	}

});


// ====================================================================


















