
function initHelpers() {		
	if ($('ctl00_cphContent_hbSearch_dropArriveDay')) prefix = 'ctl00_cphContent_hbSearch_';
	if ($('ctl00_cphContent_dropArriveDay')) prefix = 'ctl00_cphContent_';
	if ($('ctl00_cphContent_hbQuickbook_dropArriveDay')) prefix = 'ctl00_cphContent_hbQuickbook_';
	if ($('ctl00_cphPopup_hbQuickbook_dropArriveDay')) prefix = 'ctl00_cphPopup_hbQuickbook_';
	if (prefix != '') initDates();
	initPopup(document);	
}

function initDates() {
	addEvent($(prefix + 'dropArriveDay'), 'change', updateDates);
	addEvent($(prefix + 'dropArriveMonth'), 'change', updateDates);
	addEvent($(prefix + 'dropArriveYear'), 'change', updateDates);
	addEvent($(prefix + 'dropLeaveDay'), 'change', updateDates);
	addEvent($(prefix + 'dropLeaveMonth'), 'change', updateDates);
	addEvent($(prefix + 'dropLeaveYear'), 'change', updateDates);		

	if ($('arriveCalPop')) {
		YAHOO.namespace("hb.calendar");
		YAHOO.hb.calendar.init = function() {
			YAHOO.hb.calendar.cal1 = new YAHOO.widget.Calendar("cal1","arriveCalPop", {title:"Arrival date", mindate:"1/1/2008", maxdate:"12/31/2010", close:true});
			YAHOO.hb.calendar.cal1.render();
			YAHOO.hb.calendar.cal1.selectEvent.subscribe(handleSelect1, YAHOO.hb.calendar.cal1, true); 
			YAHOO.util.Event.addListener("arriveCalBtn", "click", YAHOO.hb.calendar.cal1.show, YAHOO.hb.calendar.cal1, true); 
			
			YAHOO.hb.calendar.cal2 = new YAHOO.widget.Calendar("cal2","leaveCalPop", {title:"Leaving date",mindate:"1/1/2008", maxdate:"12/31/2010", close:true});
			YAHOO.hb.calendar.cal2.render();
			YAHOO.hb.calendar.cal2.selectEvent.subscribe(handleSelect2, YAHOO.hb.calendar.cal2, true); 
			YAHOO.util.Event.addListener("leaveCalBtn", "click", YAHOO.hb.calendar.cal2.show, YAHOO.hb.calendar.cal2, true); 
		}
		YAHOO.hb.calendar.init();
	}
	
	updateDates(null);
	stayClicked(null);
	
	if ($(prefix + 'txtLocation') && ($(prefix + 'txtLocation').value == '' | $(prefix + 'txtLocation').value == 'UK')) {	
		$(prefix + 'txtLocation').className = 'watermark';
		$(prefix + 'txtLocation').value = 'location or postcode';		
		addEvent($(prefix + 'txtLocation'), 'click', locationClicked);
	}
	
	if ($(prefix + 'chkStay')) {	
		addEvent($(prefix + 'chkStay'), 'click', stayClicked);
	}
}

function handleSelect1(type,args,obj) {
	var dates = args[0];
	var date = dates[0];
	var year = date[0], month = date[1], day = date[2];

	setSelectedValue(prefix + 'dropArriveYear', year);
	setSelectedValue(prefix + 'dropArriveMonth', month);
	setSelectedValue(prefix + 'dropArriveDay',day);
	YAHOO.hb.calendar.cal1.hide();	
	updateDates(null, 'no');	
}

function handleSelect2(type,args,obj) {
	var dates = args[0];
	var date = dates[0];
	var year = date[0], month = date[1], day = date[2];

	setSelectedValue(prefix + 'dropLeaveYear', year);
	setSelectedValue(prefix + 'dropLeaveMonth', month);
	setSelectedValue(prefix + 'dropLeaveDay',day);
	YAHOO.hb.calendar.cal2.hide();	
	updateDates(null, 'no');
}

function updateDates(e, updateCal) {	
	var dateArrive = new Date(getSelectedValue(prefix + 'dropArriveYear'), getSelectedValue(prefix + 'dropArriveMonth') - 1, getSelectedValue(prefix + 'dropArriveDay'));
	var oneday = 1000*60*60*24;	// one day in milliseconds
	var dateLeave = new Date();

	var code = '';
	if ($(prefix + 'txtCode')) code = $(prefix + 'txtCode').value;
		
	if (getSelectedValue(prefix + 'dropArriveYear') > 0 && getSelectedValue(prefix + 'dropArriveMonth') > 0 && getSelectedValue(prefix + 'dropArriveDay') > 0) {
	
		if (e) {
			offset = 0;
			var target = getTarget(e);
			if (target.id.indexOf('dropArrive') > 0) {
				if (changedLeave == false && nights > 0 && nights < 100) {				
					dateLeave = new Date(dateArrive);
					dateLeave.setDate(dateLeave.getDate() + nights);				
					setSelectedValue(prefix + 'dropLeaveYear', dateLeave.getFullYear());
					setSelectedValue(prefix + 'dropLeaveMonth', dateLeave.getMonth() + 1);
					setSelectedValue(prefix + 'dropLeaveDay', dateLeave.getDate());
				}
			} else if(target.id.indexOf('dropLeave') > 0) {
				dateLeave = new Date(getSelectedValue(prefix + 'dropLeaveYear'), getSelectedValue(prefix + 'dropLeaveMonth') - 1, getSelectedValue(prefix + 'dropLeaveDay'));
				changedLeave = true;			
			}
			// if ($("mapplaceholder")) ClearAndUpdateMarkers();		
		}
		else { 
			dateLeave = new Date(getSelectedValue(prefix + 'dropLeaveYear'), getSelectedValue(prefix + 'dropLeaveMonth') - 1, getSelectedValue(prefix + 'dropLeaveDay'));
		}
		
		nights = Math.round((dateLeave - dateArrive + 1) / oneday);	// +1 is to avoid dividing by zero
		
		if (nights > 0) {
			if (nights > 1) {
				$('nights').innerHTML = nights + ' nights';
			} else {
				$('nights').innerHTML = nights + ' night';
			}
		} else {
			$('nights').innerHTML = '';
		}	
		
		if ($(prefix + 'hidVendorId') && $('calendar')) {
		  new ajax('/ajax/calendar.aspx?&vendorId=' + $(prefix + 'hidVendorId').value + '&dateArrive=' + standardDate(dateArrive) + '&dateLeave=' + standardDate(dateLeave) + '&code=' + code + '&offset=' + offset + '&allowselect=true', { update: 'calendar' });
		}
		
		if ($('arriveCalPop') && updateCal != 'no') {
			if (dateArrive.getFullYear() > 2001) {
				YAHOO.hb.calendar.cal1.select(dateArrive); 
				YAHOO.hb.calendar.cal1.cfg.setProperty("pagedate", (dateArrive.getMonth() + 1) + "/" + dateArrive.getFullYear()); 
				YAHOO.hb.calendar.cal1.render(); 
			}			
			if (dateLeave.getFullYear() > 2001) {
				YAHOO.hb.calendar.cal2.select(dateLeave); 
				YAHOO.hb.calendar.cal2.cfg.setProperty("pagedate", (dateLeave.getMonth() + 1) + "/" + dateLeave.getFullYear()); 
				YAHOO.hb.calendar.cal2.render(); 
			}
		}
	}
	
	if (e) disableNextButton();
}

function disableNextButton() {
	if ($(prefix + 'btnNext')) $(prefix + 'btnNext').disabled = true;
	if ($('message')) $('message').style.visibility = 'visible';
}

function locationClicked(e) {	
	if ($(prefix + 'txtLocation').value == 'location or postcode') {
		$(prefix + 'txtLocation').value = '';
		$(prefix + 'txtLocation').className = '';
	}
}

function stayClicked(e) {	
	if($(prefix + 'chkStay')) {
		if($(prefix + 'chkStay').checked) {
			$('leavingrow').style.visibility = 'visible';  
			$('nightsrow').style.visibility = 'visible'; 		
			$('arrivingcell').innerHTML = 'Arriving:';
		} else {	
			$('leavingrow').style.visibility = 'hidden'; 
			$('nightsrow').style.visibility = 'hidden'; 	
			$('arrivingcell').innerHTML = 'Date:';
		}
	}
}

function setDate(year, month, day) {
	var dateArrive = new Date(year, month - 1, day);
	setSelectedValue(prefix + 'dropArriveYear', year);
	setSelectedValue(prefix + 'dropArriveMonth', month);
	setSelectedValue(prefix + 'dropArriveDay', day);	
	
	if (nights <= 0) nights = 1;
	offset = 0;
	
	dateLeave = new Date(dateArrive);
	dateLeave.setDate(dateLeave.getDate()+nights);				
	setSelectedValue(prefix + 'dropLeaveYear', dateLeave.getFullYear());
	setSelectedValue(prefix + 'dropLeaveMonth', dateLeave.getMonth() + 1);
	setSelectedValue(prefix + 'dropLeaveDay', dateLeave.getDate());

	var code = '';
	if ($(prefix + 'txtCode')) code = $(prefix + 'txtCode').value;
	
	if ($(prefix + 'hidVendorId') && $('calendar')) {
	  new ajax('/ajax/calendar.aspx?&vendorId=' + $(prefix + 'hidVendorId').value + '&dateArrive=' + standardDate(dateArrive) + '&dateLeave=' + standardDate(dateLeave) + '&code=' + code + '&offset=' + offset + '&allowselect=true', { update: 'calendar' });
	}
	else if (currentVendor != '' && $('calendar')) {
	    new ajax('/ajax/calendar.aspx?&vendorId=' + currentVendor + '&dateArrive=' + standardDate(dateArrive) + '&dateLeave=' + standardDate(dateLeave) + '&code=' + code + '&offset=' + offset + '&allowselect=true', { update: 'calendar' });
	    new ajax('/ajax/setdate.aspx?dateArrive=' + standardDate(dateArrive), { });
    }
	
	disableNextButton();
}


function initPopup(target) {		
	var as, popfun;
	as=target.getElementsByTagName('a');
	for (var i=0; i<as.length; i++) {
		if(as[i].target && as[i].target!='_blank') {

			popfun=function() {
		    var width = 700;
        var height = 500;
        var offset = 0;
        var target = this.target;
		    
        if(this.target == 'room') { width = 500; height = 300; }      
        if(this.target == 'vendor') { width = 700; height = 500; }  
        if(this.target == 'photo') { width = 514; height = 420; offset = 40; }         	

        var left = 200 + offset;
        var top = 140 + offset;
        var windowAttributes = 'width='+width+',height='+height+',left='+left+',top='+top+',scrollbars=yes,location=no,toolbar=no,status=yes,resizable=yes';
				
				var theWindow = window.open(this.href,target,windowAttributes);
				theWindow.focus();
				return false;
			}			
			as[i].onclick=popfun;
		}
	}
}

function showBusy(id) {
	$(id).style.display = 'inline';
}

function bookmark() {
	if (navigator.appName == "Microsoft Internet Explorer") {
		var url = window.location;
		var who = "Historic Britain";
		window.external.AddFavorite(url,who);
	} else {
		alert('Please press Ctrl+D to bookmark this page.');
	}
}

function vendorBook(vendorId, type) {	
	if (type == 'Stay') {	  
		window.opener.location = '/book/rooms.aspx?v=' + vendorId;	
	} else {	
		window.opener.location = '/book/tickets.aspx?v=' + vendorId;
	}
	window.close();
}

function jumpWeeks(num) {
	offset += num;
	updateDates();
}

function goClick() {
	if (nights <= 0 && $(prefix + 'chkStay').checked) { 
		$('nights').innerHTML = '<b>Please check your dates.</b>';
		return false;
	} else {		
		return true;
	}
}


// Let's go

var prefix = '';
var offset = 0;
var changedLeave = false;
var nights = 1;
addEvent(window, 'load', initHelpers);



// Utility functions - mostly pinched from elsewhere // 

var Class = {
  create: function() {
    return function() { 
      this.initialize.apply(this, arguments);
    }
  }
}

Object.extend = function(destination, source) {
  for (property in source) {
    destination[property] = source[property];
  }
  return destination;
}

Function.prototype.bind = function(object) {
  var __method = this;
  return function() {
    return __method.apply(object, arguments);
  }
}

   
function addEvent(elm, evType, fn, useCapture) {
  if (elm.addEventListener){
    elm.addEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.attachEvent){
    var r = elm.attachEvent('on'+evType, fn);
    return r;
  }
} 

function getTarget(e) {
  var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
  return targ;
}

function $(id) {
  return document.getElementById(id);
}

function getSelectedValue(id) {	
	var dropdown = $(id);
	if (dropdown.options.length > 0) {
		return dropdown.options[dropdown.selectedIndex].value;
	} else {
		return null;
	}
}

function setSelectedValue(id, value) {
	var dropdown = $(id);
	if (dropdown.options.length > 0) {
		for (var i = 0; i < dropdown.options.length; i++) {
			if (dropdown.options[i].value == value) {
				dropdown.selectedIndex = i;
				break;
			}
		}
	}
}

function standardDate(d) {
	var theMonth = d.getMonth() + 1;	
  return (d.getFullYear() + '-' + theMonth + '-' + d.getDate());
} 

document.getElementsByClassName = function(className) {
  var children = document.getElementsByTagName('*') || document.all;
  var elements = new Array();
  
  for (var i = 0; i < children.length; i++) {
    var child = children[i];
    var classNames = child.className.split(' ');
    for (var j = 0; j < classNames.length; j++) {
      if (classNames[j] == className) {
        elements.push(child);
        break;
      }
    }
  }  
  return elements;
}

if(!Array.indexOf){
  Array.prototype.indexOf = function(obj) {
    for(var i=0; i<this.length; i++){
      if(this[i]==obj){
         return i;
      }
    }
    return -1;
  }
}


//-------------------------

ajax = Class.create();
ajax.prototype = {
	initialize: function(url, options){
		this.transport = this.getTransport();
		this.postBody = options.postBody || '';
		this.method = options.method || 'post';
		this.onComplete = options.onComplete || null;
		this.update = $(options.update) || null;
		this.request(url);
	},

	request: function(url){
		this.transport.open(this.method, url, true);
		this.transport.onreadystatechange = this.onStateChange.bind(this);
		if (this.method == 'post') {
			this.transport.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
			if (this.transport.overrideMimeType) this.transport.setRequestHeader('Connection', 'close');
		}
		this.transport.send(this.postBody);
	},

	onStateChange: function(){
		if (this.transport.readyState == 4 && this.transport.status == 200) {
			if (this.onComplete) 
				setTimeout(function(){this.onComplete(this.transport);}.bind(this), 10);
			if (this.update)
				setTimeout(function(){
				  var response = this.transport.responseText;
				  // Remove form tag from response or IE throws a wobbly
				  response = response.replace(/<\/?form[^>]*?>/ig, '')
				  // Remove viewstate tags to be kind to .Net
				  response = response.replace(/<input type="hidden" name="__[^>]*?>/ig,'')
				  // Update the target element
				  this.update.innerHTML = response;
				}.bind(this), 10);
			this.transport.onreadystatechange = function(){};
		}
	},

	getTransport: function() {
		if (window.ActiveXObject) return new ActiveXObject('Microsoft.XMLHTTP');
		else if (window.XMLHttpRequest) return new XMLHttpRequest();
		else return false;
	}
};