var resultsObj = {
	xml: Object,
	// These are just place holders for the information that will be retrieved from the XML
	xmlSrc: '',
	selectEl: '',
	resultEl: '',
	displaying: '',
	ctaText: {
		threeNights: '',
		fourNights: '',
		sixNights: '',
		bookNow: '',
		viewPhotos: ''
	},
	errors: {
		calError: '',
		arrivalDateError: ''
	},
	form: {
		selectRegion: '',
		selectState: '',
		selectCity: ''
	},
	terms: '',
	checkInText: '',
	checkOutText: '',
	disclaimerText: '',
	checkInRestrictions: '',
	dateFormat: '',
	dayNamesMin: '',
	monthNames: '',
	copydeck: {
		subhead: ''
	},
	// End place holders.
	searchURL: 'https://www.starwoodhotels.com/westin/search/ratelist.html',
	modified: false,
	highlightForward: true,
	init: function(resultContainer, initSrc) {
		var self = this;
		this.xml = $.ajax({
			async: false,
			type: 'GET',
			url: initSrc,
			dataType: 'xml',
			success: function(xml) {
				resultsObj.xmlSrc = initSrc;
				self.xml = xml;
				self.processXML();
			},
			error: function(e) {
				resultsObj.xmlSrc = false;
				console.log(e);
				alert($('#errorBox').html());
			}
		}).responseXML;
		this.resultEl = resultContainer;
		if (this.resultEl.indexOf('#') == -1) {
			this.resultEl = '#' + this.resultEl;
		} // when you change the value for the region drop down
		$('#select-region').change(function() {
			self.resetEvents();
			var selectedRegion = $('#select-region').val();
			$('#select-state').empty(); //$('#select-city').empty();
			$('#select-city').attr('disabled', 'disabled');
			resultsObj.populateState(selectedRegion);
		}); // when you change the value for the state drop down
		$('#select-state').change(function() {
			self.resetEvents();
			var selectedRegion = $('#select-region').val();
			var selectedState = $('#select-state').val();
			resultsObj.populateCity(selectedRegion, selectedState);
		}); // when you change the value for the city drop down
		$('#select-city').change(function() {
			self.resetEvents();
			var selectedCity = $('#select-city').val();
			resultsObj.showAllEvents(selectedCity);
			this.blur();
		});
	},
	populateRegion: function() {
		regionNode = $(this.xml).find('region');
		regionName = $(regionNode).find('regionName');
		$('#select-region').empty();
		$('#select-region').append('<option value="">' + this.form.selectRegion + '</option>');
		for (var i = 0; i < regionNode.length; i++) {
			$('#select-region').append('<option value="' + $(regionNode[i]).attr('name') + '">' + $(regionName[i]).text() + '</option>');
		}
	},
	populateState: function(selectedRegion) {
		$('#select-state').removeAttr('disabled');
		regionNode = $(this.xml).find('region').filter('[name=' + selectedRegion + ']');
		countryNode = $(regionNode).find('country');
		countryName = $(countryNode).find('countryName');
		$('#select-state').empty();
		$('#select-state').append('<option value="">Country</option>');
		for (var i = 0; i < countryName.length; i++) {
			$('#select-state').append('<option value="' + $(countryName[i]).text() + '">' + $(countryName[i]).text() + '</option>');
		}
	},
	populateCity: function(selectedRegion, selectedState) {
		selectedRegion = $.trim(selectedRegion);
		selectedState = $.trim(selectedState);
		$('#select-city').removeAttr('disabled');
		var regionNode = $('region', this.xml).filter('[name="' + selectedRegion + '"]');
		var countryName = $('countryName', $(regionNode));
		for (var i = 0; i < countryName.length; i++) {
			if ($.trim($(countryName[i]).text()) == selectedState) {
				var selectedCountry = $(countryName[i]).parent();
				var cityNode = $(selectedCountry).find('city');
				var cityName = $(cityNode).find('cityName'); //populate city drop down
				$('#select-city').empty();
				$('#select-city').append('<option value="">City/Area</option>');
				for (var j = 0; j < cityName.length; j++) {
					$('#select-city').append('<option value="' + $(cityName[j]).text() + '">' + $(cityName[j]).text() + '</option>');
				}
			}
		}
		if ($('#select-city').children().length == 2) {
			$('#select-city').val($('#select-city > option:last').val());
			$('#select-city > option:last').attr('selected', 'selected');
			$('#select-city').trigger('change');
		}
	},
	resetEvents: function() {
		$(this.resultEl).find('.eventContainer').remove();
		$('#results-header').fadeOut('fast');
		this.reset();
	},
	processXML: function() {
		this.copydeck.subhead = $.trim($('subhead', this.xml).text());
		this.ctaText.threeNights = $.trim($('threeNights', this.xml).text());
		this.ctaText.fourNights = $.trim($('fourNights', this.xml).text());
		this.ctaText.sixNights = $.trim($('sixNights', this.xml).text());
		this.ctaText.bookNow = $.trim($('bookNow', this.xml).text());
		this.ctaText.viewPhotos = $.trim($('viewPhotos', 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.errors.calError = $.trim($('calError', this.xml).text());
		this.errors.arrivalDateError = $.trim($('arrivalDateError', this.xml).text());
		this.form.selectRegion = $.trim($('selectRegion', this.xml).text());
		this.form.selectState = $.trim($('selectState', this.xml).text());
		this.form.selectCity = $.trim($('selectCity', this.xml).text());
		this.terms = $.trim($('terms', 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 j = 0; j < this.monthNames.length; j++) {
			this.monthNames[j] = $.trim(this.monthNames[j]);
		}
		$('#form-container').append('<p>' + this.copydeck.subhead + '</p>');
		$('#terms-container').html('<p>' + this.terms + '</p>'); //console.log(this.terms);
		this.populateRegion();
	},
	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(), 10);
	},
	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(), 10);
		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(), 10);
			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 k = $days.index($theDay); k >= $days.index($theDay) - lengthOfStay; k--) {
					$($days.get(k)).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);
	},
	showAllEvents: function(selectedCity) {
		selectedCity = $.trim(selectedCity);
		$('#results-header').fadeIn();
		selectedCityNode = $(this.xml).find('cityName');
		for (var i = 0; i < selectedCityNode.length; i++) {
			if ($.trim($(selectedCityNode[i]).text()) == selectedCity) {
				selectedCity = $(selectedCityNode[i]).parent();
				locationsNode = $(selectedCity).find('location');
				thumbnailNode = $(locationsNode).find('thumbnail');
				nameNode = $(locationsNode).find('name');
				propIDNode = $(locationsNode).find('propID');
				$('#results-header').html('<p>' + $(selectedCityNode[i]).text() + '</p></a>'); // Empty the result container so we're starting with a clean slate.
				$(this.resultEl).empty();
				for (var l = 0; l < locationsNode.length; l++) {
					locationType = $(locationsNode[l]).attr('type');
					$(this.resultEl).append('<div class="eventContainer" id="event' + l + '"></div>');
					$('#event' + l).hide();
					$('#event' + l).append('<div class="calendarContainer"></div>'); // thumbnail
					$('#event' + l).append('<div class="eventImage"><a target="_blank" href="http://www.starwoodhotels.com/westin/property/overview/index.html?propertyID=' + $(propIDNode[l]).text() + '"><img src="../Media/Graphics/Microsites/Westin/WI_PROMO1/' + $(thumbnailNode[l]).text() + '" alt="' + $(nameNode[l]).text() + '" title="' + $(nameNode[l]).text() + '" /></</div>'); // title
					$('#event' + l).append('<div class="eventTitle"><a target="_blank" href="http://www.starwoodhotels.com/westin/property/overview/index.html?propertyID=' + $(propIDNode[l]).text() + '">' + $(nameNode[l]).text() + '</a></div>'); // check if the location is a resort or hotel, and then adjust the URLs accordingly
					if (locationType == 'resort') {
						dreCode = 'R';
					} else {
						dreCode = 'H';
					} // cta 1
					//$('#event' + i).append('<div class="cta1"><p>Stay three nights. The last night is our treat.</p><a class="threeNights bookNow" rel="' + $(propIDNode[i]).text() + ' Z3' + dreCode + '" href="javascript:;">BOOK NOW</a><div class="clear" /></div>');			
					$('#event' + l).append('<div class="cta1"><p>' + this.ctaText.threeNights + '</p><a class="threeNights bookNow" rel="' + $(propIDNode[l]).text() + ' Z3' + dreCode + '" href="javascript:;">' + this.ctaText.bookNow + '</a><div class="clear" /></div>'); // cta 2					
					$('#event' + l).append('<div class="cta2"><p>' + this.ctaText.fourNights + '</p><a class="fourNights bookNow" rel="' + $(propIDNode[l]).text() + ' Z4' + dreCode + '" href="javascript:;">' + this.ctaText.bookNow + '</a><div class="clear" /></div>'); // cta 3
					$('#event' + l).append('<div class="cta3"><p>' + this.ctaText.sixNights + '</p><a class="sixNights bookNow" rel="' + $(propIDNode[l]).text() + ' Z6' + dreCode + '" href="javascript:;">' + this.ctaText.bookNow + '</a><div class="clear" /></div>'); 
					$('#event' + l).append('<div class="cta4"><a class="Show photos" rel="' + $(propIDNode[l]).text() + ' Z6' + dreCode + '" href="javascript:void window.open(\'https://www.starwoodhotels.com/westin/property/photos/popup.html?&showBookNow=false&propertyID='+$(propIDNode[l]).text()+'\',\'popup\',\'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=591,height=420\');">' + this.ctaText.viewPhotos + '<div class="arrow"></div></a><div class="clear" /></div><div class="clear" />');					
				}
				$(this.resultEl).find('.eventContainer').slideFadeToggle('normal');
			}
		}
	}
}; // end resultsObj

