//flickering IE6  image fix
try {
  document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}


//booking.js hotel-dropdown.js login.js

        //pop-up window (for maps)
		function popitup(path){
			newwindow=window.open(path,'name','height=430,width=500');
			if(window.focus){newwindow.focus();}
			//alert(path);
			return false;
		}
		
		//pop-up window for Facebook link
		function fbs_click() {u=location.href;t=document.title;window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');return false;}

$(document).ready(function(){
	
	//hotel drop down
	//$("#smallNav").before('<div id="chooseHotel"><a id="toggle" class="toggle" href="#non">Choose a hotel</a><a class="toggle imglink" href="#non"><img id="arrow" src="' + sRoot + 'images/design/blue-arrow.gif" alt="" /></a><ul id="hotels"><li class="first"><a class="head" href="#non"><span>Dublin</span></a><ul><li><a href="#non">The Croke Park Hotel</a></li><li><a href="#non">Westbury Quarter</a></li></ul></li><li><a class="head" href="#non"><span>Cork</span></a><ul><li><a href="#non">Bankside Quarter</a></li></ul></li><li><a class="head" href="#non"><span>London</span></a><ul><li><a href="/locations/london/bloomsbury">Blomsbury Quarter</a></li><li><a href="#non">Kensington Quarter</a></li><li><a href="/locations/london/marylebone">Marylebone Quarter</a></li></ul></li><li><a class="head" href="#non"><span>Bristol</span></a><ul><li><a href="#non">Quayside Quarter</a></li></ul></li><li><a class="head" href="#non"><span>Boston</span></a><ul><li><a href="#non">Boston Quarter</a></li></ul></li><li><a class="head" href="#non"><span>Washington DC</span></a><ul><li><a href="#non">Courtyard Quarter</a></li><li><a href="#non">Normandy Quarter</a></li><li><a href="#non">Washington Quarter</a></li></ul></li><li><a class="toggle closeX" href="#non"><span>Close</span></a></li></ul></div>');


	$("#hotels").hide();

	$('#hotels').accordion({
				header: '.head',
				active: true, 
	    		alwaysOpen: false,
				autoheight: false 
			});
	
		    $('#chooseHotel').hover(
      function () {
	  if($("#hotels").css("display") == "none" ){
        $("#hotels").slideDown(800);
				$("#arrow").attr("src", sRoot + "images/design/blue-arrow-up.gif");
     }
	  }, 
      function () {
        $("#hotels").slideUp(800 );
			$("#arrow").attr("src", sRoot + "images/design/blue-arrow.gif");
      }
    );
		

	if($('#hotels').bgiframe){
	    $('#hotels').bgiframe();
	}
	


	//login box 
	
//	$("#smallNav").append('<div id="loginBox"><form action="/loggedin.asp"><fieldset><label for="fName">Username</label><input id="fName" name="fName" type="text" size="15" /><label for="fPass">Password</label><input id="fPass" name="fPass" type="text" size="15" /><input class="login" type="image" src="'+ sRoot + 'images/design/login.gif" alt="login" value="Login" /> <a href="#non">Forgot password?</a></fieldset></form></div>');
	
	//$("#login, .login").attr("href", "#non");
	//$("#smallNav a#login").attr("href", "#non");

	$("#smallNav #login").click(function() { 
		if ($("#loginBox").is(":hidden")) {
			$("#loginBox").fadeIn(800);
		}
		else {
		    $("#loginBox").fadeOut(800);
		}
		return false;
	});
	
	$(".closeLoginBox").click(function() {
		$("#loginBox").fadeOut(800);
	});
	
	//if login box has hidden class remove it but keep hidden with jquery .hide(), this avoids some IE versions briefly showing it
	if($("#loginBox").is(".hidden")){
	    //hide in jquery way
	    $('#loginBox').hide();      
	    //remove css hidding now javascript has hidden it
        $("#loginBox").removeClass("hidden");
	
	}
	
//	$("#smallNav #login").click(function() { 
//	    alert('fade');
//		$("#loginBox").fadeIn(800);
//	});
	
	$("#loginBox .login").hover(function() {
			  $(this).attr("src",sRoot + "images/design/login-over.gif");
			}, function() {
			  $(this).attr("src",sRoot + "images/design/login.gif");
			});
	
    //set-up (+) buttons on hotel availability room's
    //modified to check cookies to see whether or not the rooms should be hidden
    $("div.hotelResults .expand a").each(function(i){
    
       var show = showAvailabilityItem('roomOpen_'+$(this).children('span')[0].id);
       //add correct (but named backwards!) class depending on whether showing or not
        if(show){
	       $(this).children('span').addClass('close');
        }else{
	       $(this).children('span').addClass('open');
        }
        //adding <a> tag with JS is nice but was took ages when hotel result set's were larger
	  //$(this).html("<a href='#nogo'>"+$(this).html()+"</a>"); 
	  //$(this).wrap("<a href='#nogo'></a>");
	   //hide roomInfo if not showing
	   if(!show){
	    $(this).parents('tr').next('tr').children('td.roomInfo').children('div').hide();
	   }
	   $(this).click(function(){
	       $(this).parents('tr').next('tr').children('td.roomInfo').children('div').slideToggle();
	       $(this).children('span').toggleClass('open').toggleClass('close');
	       //$(this).children('span').toggleClass('close');
	       //set cookie to say if should show item on page refresh
	       if ($(this).children('span.close').length) {
	        saveItemVisibility('roomOpen_'+$(this).children('span')[0].id,true);
	       }else{
	        saveItemVisibility('roomOpen_'+$(this).children('span')[0].id,false);
	       }

	   });
	});
	

		
	//set-up link to show all rates if cookie doesn't say they should already be shown
    $("div.showAllRates a").each(function(){
        if(showAvailabilityItem("moreOpen_"+this.id)){
            $(this).hide();
        }else{
            //set up onclick to show all rates
	        $("div.showAllRates a").click(function () {
	            $(this).parent().parent().children(".moreResults").fadeIn(800);
	            $(this).hide();
	            //set cookie so stays open on page refresh
	            saveItemVisibility("moreOpen_"+$(this)[0].id, true);
	        });           
	        $(this).parent().parent().children(".moreResults").hide();
        }
    });
	//$(".expand").html("<a href='#nogo'>"+$(".expand").html()+"</a>");
		
//	$(".roomInfo").children("div").hide();
//	$(".expand").children("a").children("span").addClass("open");

//	$(".expand").click(function () {
//		$(this).parent().parent().children().children("td.roomInfo").children("div").slideToggle();
//		var kid = $(this).children("a").children("span");
//		if (kid.attr('className') == "open") {
//			kid.addClass("close");
//			kid.removeClass("open");
//		}else{kid.addClass("open");
//			kid.removeClass("close")
//		}
//	});
	
	$("#calcToggle").html("<a href='#nogo' class='open'>"+$("#calcToggle").html()+"</a>");
		
	$(".roomCalc").hide();

	$("#calcToggle").click(function () {
		$(this).parent().children(".roomCalc").slideToggle();
		var kid = $(this).children("a");
		if (kid.attr('className') == "open") {
			kid.addClass("close");
			kid.removeClass("open");
		}else{kid.addClass("open");
			kid.removeClass("close")
		}
	});
	
	$("#share").html("<a href='#nogo'>"+$("#share").html()+"</a>");
		
	$(".socialBookmarks").hide();
	
	$("#share").children("a").children("span").addClass("open");

	$("#share").click(function () {
		$(this).parent().children(".socialBookmarks").slideToggle();
		var kid = $(this).children("a").children("span");
		if (kid.attr('className') == "open") {
			kid.addClass("close");
			kid.removeClass("open");
		}else{kid.addClass("open");
			kid.removeClass("close")
		}
	});
	
	
	
	
	//set-up (+) buttons on hotel availability <h2>'s
	//$("h2.slide").html("<a href='#nogo' class='close'>"+$("h2.slide").html()+"</a>"); 
	
	if($("div.hotelResults h2").length > 1){
	    $("div.hotelResults h2").each(function(i){
	        if(showAvailabilityItem("hotelOpen_"+$(this)[0].id)){
	            //don't actualy need to do this anymore as a tag already has this class
	            //$(this).children("a").addClass('open');
	            
	            //$(this).html("<a href='#nogo' class='open'>"+$(this).html()+"</a>");
            } else {
	            $(this).children("a").removeClass('open');
	            $(this).children("a").addClass('close');
	            //$(this).html("<a href='#nogo' class='close'>"+$(this).html()+"</a>");
                $(this).parent().children('.slide').hide();
            }
            $(this).parent().children('.slide').removeClass('hidden');
	    });
    	
	    //set-up (+) buttons on hotel availability rooms
    	
    	
    //	$("h2.slide").click(function(){
    //	});
    	
    //	$(".slide1").html("<a href='#nogo' class='close'>"+$(".slide1").html()+"</a>");
    //	$(".slide2").html("<a href='#nogo' class='close'>"+$(".slide2").html()+"</a>");
    	
    //	$(".slide").hide();
    //	
    //	$(".slide1, .slide2").click(function () {
    //		$(this).parent().children(".slide").slideToggle();
    //		var kid = $(this).children("a");
    //		if (kid.attr('className') == "open") {
    //			kid.addClass("close");
    //			kid.removeClass("open");
    //		}else{kid.addClass("open");
    //			kid.removeClass("close")
    //		}
    //	});
    //	
        //open and close hotels on click
        $("div.hotelResults h2 a").click(function(){
            $(this).toggleClass("close");
            $(this).toggleClass("open");
            $(this).parents('.hotelResults').children('.slide').slideToggle();
            //save cookie open or closed using id of surrounding h2
            saveItemVisibility('hotelOpen_'+$(this).parent()[0].id,$(this).hasClass('open'))
        });
        //click for all link
	    $("h2 span.price").append('<span class="click">Show detail</span>');
	    $('.hotelResults h2').click(function() {
		    $(this).children().children().children(".click").toggle();
	       return false;
	    });

    } else {
        //leave single hotel open
	    $("div.hotelResults h2").each(function(i){
	        //$(this).html("<a href='#nogo' class='open'>"+$(this).html()+"</a>");
	        $(this).children('a').removeClass('close');
	        $(this).children('a').addClass('open');
            $(this).parent().children('.slide').removeClass('hidden');
	    });
    }
	
	//expanding forms
	
	$("h2.toggle1, h2.toggle2, h2.toggle3, h2.toggle4, h2.toggle5, h2.toggle6, .toggle7").parent().children("div.fBox").hide();
	
	$("h2.toggle1").html("<a href='#nogo' class='open'>"+$("h2.toggle1").html()+"</a>");
	$("h2.toggle2").html("<a href='#nogo' class='open'>"+$("h2.toggle2").html()+"</a>");
	$("h2.toggle3").html("<a href='#nogo' class='open'>"+$("h2.toggle3").html()+"</a>");
	$("h2.toggle4").html("<a href='#nogo' class='open'>"+$("h2.toggle4").html()+"</a>");
	$("h2.toggle5").html("<a href='#nogo' class='open'>"+$("h2.toggle5").html()+"</a>");
	$("h2.toggle6").html("<a href='#nogo' class='open'>"+$("h2.toggle6").html()+"</a>");
	
	$("h2.toggle1, h2.toggle2, h2.toggle3, h2.toggle4, h2.toggle5, h2.toggle6,.toggle7").click(function () {
		$(this).parent().children("div.fBox").slideToggle();
		var kid1 = $(this).children("a");
		if (kid1.attr('className') == "open") {
			kid1.addClass("close");
			kid1.removeClass("open");
		}else{kid1.addClass("open");
			kid1.removeClass("close")
		}
	});
	
	//button rollovers
	$(".calc").hover(function() {
	  $(this).attr("src",sRoot + "images/design/btn-calc-over.gif");
	}, function() {
	  $(this).attr("src",sRoot + "images/design/btn-calc.gif");
	});

	
	
	$(".fCancel").hover(function() {
	  $(this).attr("src",sRoot + "images/design/btn-cancel-over.gif");
	}, function() {
	  $(this).attr("src",sRoot + "images/design/btn-cancel.gif");
	});
	$(".fSave").hover(function() {
	  $(this).attr("src",sRoot + "images/design/btn-save-over.gif");
	}, function() {
	  $(this).attr("src",sRoot + "images/design/btn-save.gif");
	});
	
	$("#fSubmit, .fSubmit").hover(function() {
	  $(this).attr("src",sRoot + "images/design/submit-over.gif");
	}, function() {
	  $(this).attr("src",sRoot + "images/design/submit.gif");
	});
	
	$(".reserve input").hover(function() {
	  $(this).attr("src",sRoot + "images/design/btn-reserve-over.gif");
	}, function() {
	  $(this).attr("src",sRoot + "images/design/btn-reserve.gif");
	});
	
	$("#fSubmitDark, .submit").hover(function() {
	  $(this).attr("src",sRoot + "images/design/submit-over.gif");
	}, function() {
	  $(this).attr("src",sRoot + "images/design/submit.gif");
	});
	
	$("#proceed").hover(function() {
	  $(this).attr("src",sRoot + "images/design/proceed-to-guest-over.gif");
	}, function() {
	  $(this).attr("src",sRoot + "images/design/proceed-to-guest.gif");
	});
	
	$(".calc").hover(function() {
	  $(this).attr("src",sRoot + "images/design/btn-calc-over.gif");
	}, function() {
	  $(this).attr("src",sRoot + "images/design/btn-calc.gif");
	});
	
	$("#continue, .fContinue, .myform .continue").hover(function() {
	  $(this).attr("src",sRoot + "images/design/continue-over.gif");
	}, function() {
	  $(this).attr("src",sRoot + "images/design/continue.gif");
	});
	
	$(".selectContinue").hover(function() {
	  $(this).attr("src",sRoot + "images/design/btn-sel-cont-over.gif");
	}, function() {
	  $(this).attr("src",sRoot + "images/design/btn-sel-cont.gif");
	})
	
	$(".add").hover(function() {
	  $(this).attr("src",sRoot + "images/design/btn-add-over.gif");
	}, function() {
	  $(this).attr("src",sRoot + "images/design/btn-add.gif");
	})
	
	$(".skip").hover(function() {
	  $(this).attr("src",sRoot + "images/design/btn-skip-over.gif");
	}, function() {
	  $(this).attr("src",sRoot + "images/design/btn-skip.gif");
	})
	
	$(".search").hover(function() {
	  $(this).attr("src",sRoot + "images/design/btn-search-over.gif");
	}, function() {
	  $(this).attr("src",sRoot + "images/design/btn-search.gif");
	})
	
	$(".findVenue").hover(function() {
	  $(this).attr("src",sRoot + "images/design/btn-venue-over.gif");
	}, function() {
	  $(this).attr("src",sRoot + "images/design/btn-venue.gif");
	})
	
	$(".confirm").hover(function() {
	  $(this).attr("src",sRoot + "images/design/btn-confirm-over.gif");
	}, function() {
	  $(this).attr("src",sRoot + "images/design/btn-confirm.gif");
	})
	
	$(".go").hover(function() {
	  $(this).attr("src",sRoot + "images/design/btn-go-over.gif");
	}, function() {
	  $(this).attr("src",sRoot + "images/design/btn-go.gif");
	})
	$(".select").hover(function() {
	  $(this).attr("src",sRoot + "images/design/btn-select-over.gif");
	}, function() {
	  $(this).attr("src",sRoot + "images/design/btn-select.gif");
	})
	
	$(".remove").hover(function() {
	  $(this).attr("src",sRoot + "images/design/blue-close-over.gif");
	}, function() {
	  $(this).attr("src",sRoot + "images/design/blue-close.gif");
	})
	
	$(".another").hover(function() {
	  $(this).attr("src",sRoot + "images/design/btn-add-another-over.gif");
	}, function() {
	  $(this).attr("src",sRoot + "images/design/btn-add-another.gif");
	})	
	
	$(".fLogin").hover(function() {
	  $(this).attr("src",sRoot + "images/design/btn-login-over.gif");
	}, function() {
	  $(this).attr("src",sRoot + "images/design/btn-login.gif");
	})
	
	$(".convert").hover(function() {
	  $(this).attr("src",sRoot + "images/design/btn-convert-over.gif");
	}, function() {
	  $(this).attr("src",sRoot + "images/design/btn-convert.gif");
	})

	
}); 

//checks cookies and if name is present then the item should be shown
function showAvailabilityItem(cookiename){
    //TODO - add extra criteria
    
   // return true;
    
    
    var x = readCookie(cookiename);
   return x != null;
    
    //return $.cookie(cookiename);


}
//caches name value collection of cookies
var cookieArray;

//reads cookie value from cached items in cookieArray 
//(much faster than checking each cookie individually - saves ~15s load time)
//remember if a cookie is changed in JS then this won't get the latest version
function readCookie(cookiename) {
    //if cookieArray not set-up yet, fill it
    if(!cookieArray){
        cookieArray = [];
	    var ca = document.cookie.split(';');
	    for(var i=0;i < ca.length;i++) {
	        var ia = ca[i].split('=');
	        cookieArray[jQuery.trim(ia[0])]  = jQuery.trim(ia[1]);
	    }
	}
	//check if array contains name
	if(cookieArray[cookiename]){
	    return cookieArray[cookiename];
	} else{
	    return null;
	}
}

//creates or deletes a cookie to say whether or not an availability item shoild show
function saveItemVisibility(cookiename, state){
    if(state){
        $.cookie(cookiename,state,{path:'/'});
     } else{
        $.cookie(cookiename,null);
        
     }
}
$(document).ready(function(){
	
	

	$("#mapLondonList a.closeButton").click(function(){
		$("#mapLondonList").addClass("hideLocationList");
	});
	$("#mapBostonList a.closeButton").click(function(){
		$("#mapBostonList").addClass("hideLocationList");
	});
	$("#mapWashingtonList a.closeButton").click(function(){
		$("#mapWashingtonList").addClass("hideLocationList");
	});
	$("#mapDublinList a.closeButton").click(function(){
		$("#mapDublinList").addClass("hideLocationList");
	});
	$("#mapCorkList a.closeButton").click(function(){
		$("#mapCorkList").addClass("hideLocationList");
	});
	$("#mapBristolList a.closeButton").click(function(){
		$("#mapBristolList").addClass("hideLocationList");
	});
	
	$("#mapBostonRollover").mouseover(function(){
		showList("#mapBostonList");
	});
	$("#mapLondonRollover").mouseover(function(){
		showList("#mapLondonList");
	});
	$("#mapWashingtonRollover").mouseover(function(){
		showList("#mapWashingtonList");
	});
	$("#mapDublinRollover").mouseover(function(){
		showList("#mapDublinList");
	});
	$("#mapCorkRollover").mouseover(function(){
		showList("#mapCorkList");
	});
	$("#mapBristolRollover").mouseover(function(){
		showList("#mapBristolList");
	});

function showList(dislayList){
	$("#mapBostonList").addClass("hideLocationList");
	$("#mapWashingtonList").addClass("hideLocationList");
	$("#mapLondonList").addClass("hideLocationList");
	$("#mapDublinList").addClass("hideLocationList");
	$("#mapCorkList").addClass("hideLocationList");
	$("#mapBristolList").addClass("hideLocationList");
	$(dislayList).removeClass("hideLocationList");
} 
	
})

//function to standardise size of opening pop up windows
function wopen(url, name, w, h)
{
	// Fudge factors for window decoration space.
	// In my tests these work well on all platforms & browsers.
	w += 32;
	h += 96;
 	var win = window.open(url, name, 'width=' + w + ', height=' + h + ', ' + 'location=no, menubar=no, ' + 'status=no, toolbar=no, scrollbars=yes, resizable=yes');
 	win.resizeTo(w, h);
 	win.focus();
}


/* Andrew Urquhart : Client-Side Request Object for javascript : http://andrewu.co.uk/tools/request/
COPYRIGHT:You are free to use this script for any use you wish if this comment is left intact. Feel free to enhance the script and send me the updated version. Please don't redistribute. This script is provided as is,with no warranty of any kind. Use it at your own risk. Copyright Andrew Urquhart; VERSION:#1.41 2007-06-28 18:10 UTC*/
function RObj(ea){var LS="";var QS=new Object();var un="undefined";var x=null;var f="function";var n="number";var r="string";var e1="ERROR:Index out of range in\r\nRequest.QueryString";var e2="ERROR:Wrong number of arguments or invalid property assignment\r\nRequest.QueryString";var e3="ERROR:Object doesn't support this property or method\r\nRequest.QueryString.Key";var dU=window.decodeURIComponent?1:0;function Err(arg){if(ea){alert("Request Object:\r\n"+arg)}};function URID(t){var d="";if(t){for(var i=0;i<t.length;++i){var c=t.charAt(i);d+=(c=="+"?" ":c)}}return(dU?decodeURIComponent(d):unescape(d))};function OL(o){var l=0;for(var i in o){if(typeof o[i]!=f){l++}};return l};function AK(key){var auk=true;for(var u in QS){if(typeof QS[u]!=f&&u.toString().toLowerCase()==key.toLowerCase()){auk=false;return u}}if(auk){QS[key]=new Object();QS[key].toString=function(){return TS(QS[key])};QS[key].Count=function(){return OL(QS[key])};QS[key].Count.toString=function(){return OL(QS[key]).toString()};QS[key].Item=function(e){if(typeof e==un){return QS[key]}else {if(typeof e==n){var a=QS[key][Math.ceil(e)];if(typeof a==un){Err(e1+"(\""+key+"\").Item("+e+")")};return a}else {Err("ERROR:Expecting numeric input in\r\nRequest.QueryString(\""+key+"\").Item(\""+e+"\")")}}};QS[key].Item.toString=function(e){if(typeof e==un){return QS[key].toString()}else {var a=QS[key][e];if(typeof a==un){Err(e1+"(\""+key+"\").Item("+e+")")};return a.toString()}};QS[key].Key=function(e){var t=typeof e;if(t==r){var a=QS[key][e];return(typeof a!=un&&a&&a.toString()?e:"")}else {Err(e3+"("+(e?e:"")+")")}};QS[key].Key.toString=function(){return x}};return key};function AVTK(key,val){if(key!=""){var key=AK(key);var l=OL(QS[key]);QS[key][l+1]=val}};function TS(o){var s="";for(var i in o){var ty=typeof o[i];if(ty=="object"){s+=TS(o[i])}else if(ty!=f){s+=o[i]+", "}};var l=s.length;if(l>1){return(s.substring(0,l-2))}return(s==""?x:s)};function KM(k,o){var k=k.toLowerCase();for(var u in o){if(typeof o[u]!=f&&u.toString().toLowerCase()==k){return u}}}if(window.location&&window.location.search){LS=window.location.search;var l=LS.length;if(l>0){LS=LS.substring(1,l);var preAmpAt=0;var ampAt=-1;var eqAt=-1;var k=0;var skip=false;for(var i=0;i<l;++i){var c=LS.charAt(i);if(LS.charAt(preAmpAt)=="="||(preAmpAt==0&&i==0&&c=="=")){skip=true}if(c=="="&&eqAt==-1&&!skip){eqAt=i}if(c=="&"&&ampAt==-1){if(eqAt!=-1){ampAt=i}if(skip){preAmpAt=i+1};skip=false}if(ampAt>eqAt){AVTK(URID(LS.substring(preAmpAt,eqAt)),URID(LS.substring(eqAt+1,ampAt)));preAmpAt=ampAt+1;eqAt=ampAt=-1;++k}}if(LS.charAt(preAmpAt)!="="&&(preAmpAt!=0||i!=0||c!="=")){if(preAmpAt!=l){if(eqAt!=-1){AVTK(URID(LS.substring(preAmpAt,eqAt)),URID(LS.substring(eqAt+1,l)))}else if(preAmpAt!=l-1){AVTK(URID(LS.substring(preAmpAt,l)),"")}}if(l==1){AVTK(LS.substring(0,1),"")}}}};var TC=OL(QS);if(!TC){TC=0};QS.toString=function(){return LS.toString()};QS.Count=function(){return(TC?TC:0)};QS.Count.toString=function(){return(TC?TC.toString():"0")};QS.Item=function(e){if(typeof e==un){return LS}else {if(typeof e==n){var e=Math.ceil(e);var c=0;for(var i in QS){if(typeof QS[i]!=f&&++c==e){return QS[i]}};Err(e1+"().Item("+e+")")}else {return QS[KM(e,QS)]}};return x};QS.Item.toString=function(){return LS.toString()};QS.Key=function(e){var t=typeof e;if(t==n){var e=Math.ceil(e);var c=0;for(var i in QS){if(typeof QS[i]!=f&&++c==e){return i}}}else if(t==r){var e=KM(e,QS);var a=QS[e];return(typeof a!=un&&a&&a.toString()?e:"")}else {Err(e2+"().Key("+(e?e:"")+")")};Err(e1+"().Item("+e+")")};QS.Key.toString=function(){Err(e2+"().Key")};this.QueryString=function(k){if(typeof k==un){return QS}else {if(typeof k==n){return QS.Item(k)};var k=KM(k,QS);if(typeof QS[k]==un){t=new Object();t.Count=function(){return 0};t.Count.toString=function(){return "0"};t.toString=function(){return x};t.Item=function(e){return x};t.Item.toString=function(){return x};t.Key=function(e){Err(e3+"("+(e?e:"")+")")};t.Key.toString=function(){return x};return t}else {return QS[k]}}};this.QueryString.toString=function(){return LS.toString()};this.QueryString.Count=function(){return(TC?TC:0)};this.QueryString.Count.toString=function(){return(TC?TC.toString():"0")};this.QueryString.Item=function(e){if(typeof e==un){return LS.toString()}else {if(typeof e==n){var e=Math.ceil(e);var c=0;for(var i in QS){if(typeof QS[i]!=f&&++c==e){return QS[i]}};Err(e1+".Item("+e+")")}else {return QS[KM(e,QS)]}}if(typeof e==n){Err(e1+".Item("+e+")")};return x};this.QueryString.Item.toString=function(){return LS.toString()};this.QueryString.Key=function(e){var t=typeof e;if(t==n){var e=Math.ceil(e);var c=0;for(var i in QS){if(typeof QS[i]=="object"&&(++c==e)){return i}}}else if(t==r){var e=KM(e,QS);var a=QS[e];return(typeof a!=un&&a&&a.toString()?e:"")}else {Err(e2+".Key("+(e?e:"")+")")};Err(e1+".Item("+e+")")};this.QueryString.Key.toString=function(){Err(e2+".Key")};this.Version=1.4;this.Author="Andrew Urquhart (http://andrewu.co.uk)"};var Request=new RObj(false);



//DATEPICKER ON DOUBLE SELECTS WITH DATE RANGE////////////////////////////////////////


$(function(){


//INITIAL VALUES////////////////////////////////////////

    
	function initialValues(DP1, DP2){
	
	    if($('div#startDate select').length && $('div#endDate select').length){
					var from = new Date();
    	    var to = new Date().addDays(1);
    	    
    	    var checkIn = Request.QueryString("checkIn");
    	    
   	    
    	    if($.cookie('LastCheckIn')){
    	        var parts = $.cookie('LastCheckIn').split('/');
    	        var fromLast = new Date();
    	        fromLast.setFullYear(parts[2]);
    	        fromLast.setMonth(parts[1]-1);
    	        fromLast.setDate(parts[0]);
    	        if(fromLast >= new Date()){
    	            from = fromLast;
    	        }
    	    }
    	    if($.cookie('LastCheckIn')){
    	        var parts = $.cookie('LastCheckOut').split('/');
    	        var toLast = new Date();
    	        toLast.setFullYear(parts[2]);
    	        toLast.setMonth(parts[1]-1);
    	        toLast.setDate(parts[0]);
    	        if(toLast > from){
    	            to = toLast;
    	        }
    	    }

					if(checkIn == undefined)
					{	
						updateDateSelects("start-Date", from);
    		
						updateDateSelects("end-Date", to);
					}
					
			    syncDP(DP1, DP2);
		}
	}



	var updateDateSelects = function (whichSelects, selectedDate)
	{		
		selectedDates = new Date(selectedDate);
	
		var d = selectedDates.getDate();
		var m = selectedDates.getMonth();
		var y = selectedDates.getFullYear();
		var day = selectedDates.getDay();
		var thisDay = Date.dayNames[day];
		
		if (whichSelects == "start-Date") {
			($('div#startDate select')[0]).selectedIndex = d - 1;
			($('div#startDate select')[1]).selectedIndex = m;
			($('div#startDate select')[2]).selectedIndex = y - new Date().getFullYear();//2005;

			$('.checkIn').replaceWith("<h3 class='checkIn'>Check in (" + thisDay + ")</h3>");
	
			syncDP(true, false);
			
		} else {
			($('div#endDate select')[0]).selectedIndex = d - 1;
			($('div#endDate select')[1]).selectedIndex = m;
			($('div#endDate select')[2]).selectedIndex = y - new Date().getFullYear();//2005;
				
			$('.checkOut').replaceWith("<h3 class='checkOut'>Check out (" + thisDay + ")</h3>");
			syncDP(false, true);
		}
	
	}

	function daysInFebruary (year){
		// February has 29 days in any year evenly divisible by four,
		// EXCEPT for centurial years which are not also divisible by 400.
		return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
	}
	
	function daysInMonth(intMonth,intYear){

		var dteMonth = new Date(intYear,intMonth);
		var intDaysInMonth = 28;//the fewest number of days in a month
		var blnDateFound = false;//Set a variable to check on the while loop

		while (!blnDateFound)
		{
			dteMonth.setDate(intDaysInMonth+1);//create the next possible day
			var intNewMonth = dteMonth.getMonth();//new month date

			if (intNewMonth != intMonth)//if the month has changed
				blnDateFound = true;
			else
				intDaysInMonth++;
		}
		
		return intDaysInMonth;	
	
	}

	function syncDP(DP1, DP2){
	
		if(DP1){
			    var selects = $('div#startDate select');
				var d = new Date(selects[2].value, selects[1].value - 1, selects[0].value);
			
				$('#start-Date').dpSetSelected(d.asString());
		}
		
		if(DP2){
	
			    var selects = $('div#endDate select');
				var f = new Date(selects[2].value, selects[1].value - 1, selects[0].value);
			
				$('#end-Date').dpSetSelected(f.asString());
		}
	}

	$('div#startDate select').bind( 'change', function(){
	
	  var startSelects = $('div#startDate select');
	  var endSelects = $('div#endDate select');
		
		var d1Year = startSelects[2].value;
		var d1Month = startSelects[1].value - 1; 
		var d1Day = startSelects[0].value;

		//Get number of days in selected month/year
		var daysInSelectedMonth = daysInMonth(d1Month, d1Year);
		
		//if selected days > num days in month, set month to 1.
		if(d1Day > daysInSelectedMonth)
		{
			d1Day = 1;
		}
		
		//var d1 = new Date(startSelects[2].value, startSelects[1].value - 1, startSelects[0].value);
		//var d2 = new Date(endSelects[2].value, endSelects[1].value - 1, endSelects[0].value);
		
		var d1 = new Date(d1Year, d1Month, d1Day);
		var d2 = new Date(endSelects[2].value, endSelects[1].value - 1, endSelects[0].value);
		
		var today = new Date();
		var tomorrow = new Date().addDays(1);

     //only prevent ridiculous dates on year otherwise impossible to select dates
		if ($(this).hasClass('y') && (d1 < tomorrow || d1 > today.addMonths(12))) {
			d1 = tomorrow;
		}

		updateDateSelects("start-Date", d1);

		if (d1 >= d2) {
			d2 = d1.addDays(1);
			updateDateSelects("end-Date", d2);
		}
	});
	
	$('div#endDate select').bind( 'change', function(){
	
	    var startSelects = $('div#startDate select');
	    var endSelects = $('div#endDate select');
	
		
		var d1 = new Date(startSelects[2].value, startSelects[1].value - 1, startSelects[0].value);
		var d2 = new Date(endSelects[2].value, endSelects[1].value - 1, endSelects[0].value);
		
		var today = new Date();
		var tomorrow = new Date().addDays(1);

        //only prevent ridiculous dates on year otherwise impossible to select dates
		if ($(this).hasClass('y') && (d2 <= tomorrow || d2 > today.addMonths(12))) {
			d2 = d1.addDays(1);
		}
	    
		updateDateSelects("end-Date", d2);

        //update start date
		if (d1 >= d2 && d2 > tomorrow) {
			d1 = d2.addDays(-1);//.addDays(-1);
			updateDateSelects("start-Date", d1);
		}

});
	
//CREATE THE DATEPICKERS WITH DATE RANGE//////////////////	

//need to create strings to represent start (tomorrow) and end (+11 months) dates
//var end = new Date().addMonths(11);
//var d = end.getDate();
//var m = end.getMonth()+1;
//var y = end.getFullYear();
//if(d <10) d = "0"+d+"/";
//var endString =  d+"/";
//if(m <10) endString += "0";
//endString += m+"/"+y;

/*var start = new Date().addDays(1);
d = start.getDate();
m = start.getMonth()+1;
y = start.getFullYear();
var startString =  d+"/";
if(d <10) d = "0"+d+"/";
if(m <10) startString += "0";
startString += m+"/"+y;*/


	$('#start-Date, #end-Date').datePicker({
		createButton:false//,
		//startDate:startString,
		//endDate:endString
		}).bind('click',function(){
			
								$(this).dpDisplay();
								return false;
		
		}).bind('dpClosed',function(e, selectedDates){
			
								if ($(this).dpGetSelected()[0] != null) {
																
									updateDateSelects($(this).attr('id'), $(this).dpGetSelected()[0]);
									
									if ($(this).attr('id') == "start-Date") {
									
										var d = selectedDates[0];
										if (d) {
											d = new Date(d);
											$('#end-Date').dpSetStartDate(d.addDays(1).asString());
											
											if($('#end-Date').dpGetSelected()[0] < $('#start-Date').dpGetSelected()[0]){
											updateDateSelects("end-Date", d);

											}
										}
									}
								}
					 });
		initialValues('#start-Date', '#end-Date');
		
		//seems to be more reliable if end limit of calendars is set last
		var end = new Date().addMonths(12).addDays(-1);
        var d = end.getDate();
        var m = end.getMonth()+1;
        var y = end.getFullYear();
        if(d <10) d = "0"+d;
        var endString =  d+"/";
        if(m <10) endString += "0";
        endString += m+"/"+y;
		$('#start-Date, #end-Date').dpSetEndDate(endString);
});
