function initHelpers() {		
	initDates();
	initPopup();	
}

function initDates() {
  if ($('ctl00_cphContent_dropLeaveDay')) prefix = 'ctl00_cphContent_';
	if ($('ctl00_cphContent_urQuickCheck_dropLeaveDay')) prefix = 'ctl00_cphContent_urQuickCheck_';
	
	if (prefix.length > 1) {
		// We've found the dropdowns, so let's go
		
		if ($(prefix + 'dropLocation')) addEvent($(prefix + 'dropLocation'), 'change', updateDates);
		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);
		updateDates(null);
	}
}

function updateDates(e) {	
	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();
	
	if (e) {
		offset = 0;
		var target = getTarget(e);
		if (target.id.indexOf('dropArrive') > 0) {
		  if (changedLeave == false) {
		    dateLeave = new Date(dateArrive);
		    dateLeave.setDate(dateLeave.getDate() + 1);
		    setSelectedValue(prefix + 'dropLeaveYear', dateLeave.getFullYear());
		    setSelectedValue(prefix + 'dropLeaveMonth', dateLeave.getMonth() + 1);
		    setSelectedValue(prefix + 'dropLeaveDay', dateLeave.getDate());
			}
		} else if(target.id.indexOf('dropLeave') > 0) {
			changedLeave = true;
		}
  }

	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';
		}
		$(prefix + 'btnGo0').disabled = false;
	} else {
		$('nights').innerHTML = '';
		$(prefix + 'btnGo0').disabled = true;	
	}	
	
	var locationId = '';
	var vendorId = '';
	if ($(prefix + 'dropLocation')) locationId = getSelectedValue(prefix + 'dropLocation');
	if ($(prefix + 'hidVendor')) vendorId = $(prefix + 'hidVendor').value;


	if ($('calendar')) {
		new ajax('/ajaxcalendar.aspx?locationId=' + locationId + '&vendorId=' + vendorId + '&dateArrive=' + standardDate(dateArrive) + '&dateLeave=' + standardDate(dateLeave) + '&offset=' + offset + '', {update: 'calendar'});
	}
}

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 locationId = '';
  var vendorId = '';
  if ($(prefix + 'dropLocation')) locationId = getSelectedValue(prefix + 'dropLocation');
  if ($(prefix + 'hidVendor')) vendorId = $(prefix + 'hidVendor').value;

  if ($('calendar')) {
    new ajax('/ajaxcalendar.aspx?locationId=' + locationId + '&vendorId=' + vendorId + '&dateArrive=' + standardDate(dateArrive) + '&dateLeave=' + standardDate(dateLeave) + '&offset=' + offset + '', { update: 'calendar' });
  }
}


function initPopup() {		
	var as, popfun;
	as=document.getElementsByTagName('a');
	for (var i=0; i<as.length; i++) {
		if(as[i].target && as[i].target!='_blank') {

			popfun=function(){
		    var width = 560;
        var height = 400;
        var offset = 0;
        var target = this.target;
		    
        if(this.target == 'room') { height = 350; }      
        if(this.target == 'vendor') { offset = 30;  }  
        if(this.target == 'photo') { width = 514; height = 420; }         	

        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 jumpWeeks(num) {
	offset += num;
	updateDates();
}


// Let's go

var prefix = '';
var offset = 0;
var nights = 1;
var changedLeave = false;
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) {	
	return $(id).options[$(id).selectedIndex].value;

}

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;
}


//-------------------------

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;
	}
};