var searchBox = {
	// These are just place holders for the information that will be retrieved from the XML
	headingText: {
		threeNights: '',
		fourNights: '',
		sixNights: ''
	},
	checkInText: '',
	checkOutText: '',
	disclaimerText: '',
	checkInRestrictions: '',
	dateFormat: '',
	dayNamesMin: '',
	monthNames: '',
	// End place holders.
	
	searchURL: 'https://www.starwoodhotels.com/westin/search/ratelist.html',
	modified: false,
	highlightForward: true,
	
	init: function(xmlSrc){
		var self = this;
		$.ajax({
			type: 'GET',
			url: xmlSrc,
			async: false,
			dataType: 'xml',
			error: function(XMLHttpRequest, textStatus, errorThrown){
				alert('Unable to load XML document.\n\nPlease reload the page to try again.');
			},
			success: function(data, textStatus){
				self.xml = data;
				self.processXML();
			}
		});
	},
	processXML: function(){
		this.headingText.threeNights = $.trim($('threeNights', this.xml).text());
		this.headingText.fourNights = $.trim($('fourNights', this.xml).text());
		this.headingText.sixNights = $.trim($('sixNights', this.xml).text());
		this.checkInText = $.trim($('checkInText', this.xml).text());
		this.checkOutText = $.trim($('checkOutText', this.xml).text());
		this.disclaimerText = $.trim($('disclaimerText', this.xml).text());
		this.checkInRestrictions = $.trim($('checkInRestrictions', this.xml).text());
		this.dateFormat = $.trim($('dateFormat', this.xml).text());
		
		this.dayNamesMin = $('dayNamesMin', this.xml).text().split(',');
		for(var i = 0; i < this.dayNamesMin.length; i++){
			this.dayNamesMin[i] = $.trim(this.dayNamesMin[i]);
		}
		
		this.monthNames = $('monthNames', this.xml).text().split(',');
		for(var i = 0; i < this.monthNames.length; i++){
			this.monthNames[i] = $.trim(this.monthNames[i]);	
		}
	},
	buildSearchBox: function(){
		// console.log('----- buildSearchBox():');
		
		var self = this;
		
		if(typeof(this.$searchBox) == 'undefined'){
			var skeleton = '';
			skeleton += '<div id="searchBox">';
			skeleton += '<div id="verticalRule"></div>';
			skeleton += '<div id="datePicker"></div>';
			skeleton += '<div id="infoDisplay">';
			skeleton += '<h1></h1>';
			skeleton += '<p id="checkIn">' + this.checkInText + ' <span id="checkInDate"></span></p>';
			skeleton += '<p id="checkOut">' + this.checkOutText + ' <span id="checkOutDate"></span></p>';
			skeleton += '<a id="searchButtonLink" href="javascript:;"><img src="../Media/Graphics/Microsites/Westin/WI_PROMO1/cta-search2.gif" width="119" height="22" border="0" alt="Search" /></a>';
			skeleton += '<p id="disclaimer"></p>';
			skeleton += '</div>';
			skeleton += '</div>';
			
			this.$searchBox = $(skeleton);
		} else {
			$('datePicker').datepicker('destory');
		}
		
		$('#datePicker', this.$searchBox).datepicker({
			inline: true,
			altField: '#selectedDate',
			gotoCurrent: true,
			minDate: 1,
			showOtherMonths: true,
			dayNamesMin: this.dayNamesMin,
			monthNames: this.monthNames,
			onChangeMonthYear: function(currentYear, currentMonth, instance){
				self.checkReservation(currentYear, currentMonth, instance);
			},
			onSelect: function(dateText, instance){
				self.updateReservation();
			}
		});
		
		// Only do this stuff if the user has selected a date
		if(this.arrivalDate){
			$('#datePicker', this.$searchBox).datepicker('setDate', this.arrivalDate);
			$('#selectedDate').val($.datepicker.formatDate(this.dateFormat, this.arrivalDate));
			// this.updateReservation();
		}
	},
	attach: function(parent){
		// console.log('----- attach():');
		
		this.buildSearchBox();
		this.$searchBox.prependTo($(parent));
	},
	getDisplayedMonth: function(){
		return parseInt($('.ui-datepicker-year').text());
	},
	getDisplayedYear: function(){
		for(var i = 0; i < this.monthNames.length; i++){
			if(this.monthNames[i] == $('.ui-datepicker-month').text()){
				// 0 based month, Jan = 0 - Dec = 11
				return i;
			}
		}
	},
	updateReservation: function(){
		// console.log('----- updateReservation():');
		
		// Dates MUST be in the YYYY-MM-DD format, and date fragments MUST contain a leading zero if appropriate, or else the booking engine generates an error.
		var lengthOfStay = parseInt($('#lengthOfStay').val());
		this.arrivalDate = new Date($('#selectedDate').val());
		$('#checkInDate').html($.datepicker.formatDate(this.dateFormat, this.arrivalDate));
		$('#arrivalDateYear').val($.datepicker.formatDate('yy', this.arrivalDate));
		$('#arrivalDateMonth').val($.datepicker.formatDate('mm', this.arrivalDate));
		$('#arrivalDateDay').val($.datepicker.formatDate('dd', this.arrivalDate));
		$('#arrivalDate').val($.datepicker.formatDate('yy-mm-dd', this.arrivalDate));
		
		this.departureDate = new Date(this.arrivalDate.getTime() + (lengthOfStay * 86400000));
		$('#checkOutDate').html($.datepicker.formatDate(this.dateFormat, this.departureDate));
		$('#departureDateYear').val($.datepicker.formatDate('yy', this.departureDate));
		$('#departureDateMonth').val($.datepicker.formatDate('mm', this.departureDate));
		$('#departureDateDay').val($.datepicker.formatDate('dd', this.departureDate));
		$('#departureDate').val($.datepicker.formatDate('yy-mm-dd', this.departureDate));
		
		this.modified= true;
		this.checkReservation();
	},
	checkReservation: function(currentYear, currentMonth, instance){
		// console.log('----- checkReservation():');
		
		if(this.modified){
			if(typeof(currentYear) == 'undefined'){
				currentYear = this.getDisplayedYear();
			}
			
			if(typeof(currentMonth) == 'undefined'){
				currentMonth = this.getDisplayedMonth();
			} else {
				// The datepicker generates a month of 1-12, but Date() uses 0-11 so we decrement the month if it was passed in for consistency.
				currentMonth--;
			}
			
			if(this.arrivalDate.getMonth() == currentMonth && this.arrivalDate.getFullYear() == currentYear){
				this.highlightForward = true;
				$('#datePicker').datepicker('setDate', this.arrivalDate);
				
			} else if(this.departureDate.getMonth() == currentMonth && this.departureDate.getFullYear() == currentYear){
				this.highlightForward = false;
				$('#datePicker').datepicker('setDate', this.departureDate);
			}
		}
	},
	highlightReservation: function(){
		// console.log('----- highlightReservation():');
		
		// Only highlight if the calendar has been modified, i.e. had a date selected, otherwise the calendar will hightlight the length of stay starting tomorrow
		if(this.modified){
			var lengthOfStay = parseInt($('#lengthOfStay').val());
			var $theDay = $('.ui-state-active');
			var $days = $('tbody td').find(':fist-child');
			
			// console.log(this.highlightForward);
			if(this.highlightForward){
				// console.log('FORWARD->>>');
				for(var i = $days.index($theDay); i <= $days.index($theDay) + lengthOfStay; i++){
					$($days.get(i)).addClass('occupied');
				}
			} else {
				// console.log('<<<-BACKWARD');
				for(var i = $days.index($theDay); i >= $days.index($theDay) - lengthOfStay; i--){
					$($days.get(i)).addClass('occupied');
				}
				// Reset to forward for the next click.
				this.highlightForward = true;
			}
		}
	},
	reset: function(){
		// console.log('----- reset():');
		
		// Reset the cursor just in case the user aborts the submission, but we already set it to 'wait'.
		$('body').css('cursor','default');
		$('#bookingInfo > input.hardReset').each(function(index){
			$(this).val('');
		});
		// Just incase since we disable it at one point.
		$('#selectedDate').removeAttr('disabled');
		
		// Removing $searchBox errors if it does not exist yet
		try {
			$('#datePicker', this.$searchBox).datepicker('destroy')
			this.$searchBox.remove();
		} catch(error) {}

		this.modified = false;
		this.highlightForward = true;
		this.arrivalDate = '';
		this.departureDate = '';
	},
	search: function(queryString){
		// console.log('----- search():');
		
		// Throw up a wait cursor.
		$('body').css('cursor','wait');
		
		// setTimeout is used to get IE 6 to cooperate.
		var newURL = this.searchURL + '?' + encodeURI(queryString);
		setTimeout(function(){
			window.location = newURL;
		}, 0);
	}
}


