/*
	search.js
	
	Author: Kevin Kilcher for Domani Stuidos
	Created: 3/12/2010
	
	Objective:
		1.	Load properties.xml and settings.xml on page load.
		2.	Filter properties.xml based on the values the user selects from the dropdowns and display
			available hotel offers for that location.
		3.	Allow the user to select an offer and check-in/check-out dates before being directed
			to the main Starwood booking engine.

	Requires:
		Date Picker Plugin from: http://keith-wood.name/datepick.html NOTE: This is NOT the jQuery UI Datepicker.
*/
 
var stwSearch = {
	settings: {
		assetPath: '/Media/Graphics/Microsites/Promotions/AP/AP_PROMO2/',
		
		animation: {
			inDuration: 750,
			outDuration: 500
		},
		
		autoDisplayResults: false,
		
		brands: {
			'le meridien': 'lemeridien',
			'le m\u00E9ridien': 'lemeridien',
			'lm': 'lemeridien',
			'four points': 'fourpoints',
			'fp': 'fourpoints',
			'westin': 'westin',
			'the luxury collection': 'luxury',
			'luxury collection': 'luxury',
			'luxury': 'luxury',
			'lc': 'luxury',
			'aloft': 'aloft',
			'sheraton': 'sheraton',
			'element': 'element',
			'st. regis': 'stregis',
			'st regis': 'stregis',
			'w': 'whotels',
			'w hotels': 'whotels'
		},
		
		lengthOfStay: {
			APRSRT: 'select',
			Z3R: 3,
			Z4R: 4,
			Z6R: 6
		},
		
		datepick: {
			defaultOptions: {
				constrainInput: true,
				gotoCurrent: false,
				showDefault: false,
				rangeSelect: true,
				yearRange: '0:+2',
				altField: '#selectedDate',
				nextText: '&#9658;',
				prevText: '&#9668;',
				showOtherMonths: true,
				selectOtherMonths: true,
				changeMonth: false,
				changeYear: false,
				showStatus: true,
				mandatory: true
			}
		},
		
		dropDowns: {
			region: '#select-region',
			country: '#select-country',
			city: '#select-city',
			autoSelect: false
		},
		
		elements: {
			bookingInfo: '.bookingInfo',
			container: '#results-container',
			dp: '#dp',
			goButton: '#goButtonLink',
			hardReset: '.hardRest',
			header: '#results-header',
			individual: '.result-container',
			prefix: '#result',
			searchButton: '#searchButtonLink'
		},
		
		ident: {
			APRSRT: 'CREDIT',
			Z3R: 'DR3',
			Z4R: 'DR4',
			Z6R: 'DR6'
		},
		
		millisecondsPerDay: 86400000,
		
		urls: {
			propertyDetail: 'http://www.starwoodhotels.com/%BRAND%/property/overview/index.html?propertyID=%PROPID%',
			search: 'https://www.starwoodhotels.com/%BRAND%/search/ratelist.html',
			imString: 'IM=LP_APRESORTS10_%IDENT%_EN_AP_%PROPID%'
		}
	}, // END settings {}
	
	
	//
	//	init()
	//
	init: function() {
		// console.log('-----init():');
		var that = this;
		var searchImg;
		
		// Move results header and container to the end of the DOM to eliminate footer jiggle while elements are being added
		$(that.settings.elements.header).hide().appendTo('body');
		$(that.settings.elements.container).hide().appendTo('body');
		
		// Disable the dropdown menus until they are populated
		$(that.settings.dropDowns.region).attr({ disabled: 'disabled' });
		$(that.settings.dropDowns.country).attr({ disabled: 'disabled' });
		$(that.settings.dropDowns.city).attr({ disabled: 'disabled' });
		
		// Reset specified fields
		$(that.settings.elements.hardReset).each(function(){ $(this).val(''); });
		
		// Create live event handlers for the dropdowns
		that.createHandlers();
		
		// Load the XML files.
		that.loadProperties();
		that.loadCopy();
		
		// Copy some data out of the nodes into attributes, and give each property a unique number
		that.processProperties();
		
		// Set the default settings for the datepicker
		$.datepick.setDefaults(that.getDpOptions({
			minDate: new Date(that.today().getTime() + that.settings.millisecondsPerDay),
			maxDate: new Date(that.today().getTime() + (540 * that.settings.millisecondsPerDay)),
			onSelect: function(){ that.checkDates(); }, // Need the closure since the value of this is assigned to something else
			statusForDate: that.statusSelectCheckIn,
			initStatus: $('checkIn dpStatus', that.copy).text()
		}));
		
		$.datepick.setDefaults($.datepick.regional[window.datepickLanguage]);
		
		// Preload the search button image for IE6
		searchImg = new Image();
		searchImg.src = that.settings.assetPath + $('searchButton', that.copy).text();
		
		// Fix for IE6 bg image issue
		if($.browser.msie && $.browser.version == 6){
			document.execCommand("BackgroundImageCache",false,true);
		}

	}, // END init()
	
	
	//
	//	checkDates()
	//
	checkDates: function(){
		var that = this;
		var dateArray = $(that.settings.datepick.defaultOptions.altField).val().split(' - ');
		
		// Sort the array so the earliest date is first	
		dateArray.sort();
		
		if (that.settings.lengthOfStay[that.current.promocode.toUpperCase()] !== 'select') {
			var departureDate = new Date(new Date(dateArray[0]).getTime() + (that.settings.lengthOfStay[that.current.promocode.toUpperCase()] * that.settings.millisecondsPerDay));
			
			// Set the datepick date using the selected check in date and calculated check out date
			$('.hasDatepick').datepick('setDate', dateArray[0], $.datepick.formatDate('mm/dd/yy', departureDate));
			$('#checkInDate').text(' ' + dateArray[0]);
			$('#checkOutDate').text(' ' + $.datepick.formatDate('mm/dd/yy', departureDate));
			
			// Change the status message
			$('.hasDatepick').datepick('option', that.getDpOptions({
				initStatus: ''
			}));
			
		} else {
			if (dateArray[0] === dateArray[1]) {
				// Change status message
				$('.hasDatepick').datepick('option', that.getDpOptions({
					statusForDate: that.statusSelectCheckOut,
					initStatus: $('checkOut dpStatus', that.copy).text()
				}));
				
				$('#checkInDate').text(' ' + dateArray[0]);
				
			} else {
				$('.hasDatepick').datepick('setDate', dateArray[0], dateArray[1]);
				$('.hasDatepick').datepick('option', that.getDpOptions({
					statusForDate: that.statusSelectCheckIn,
					initStatus: ''
				}));
				
				$('#checkInDate').text(' ' + dateArray[0]);
				$('#checkOutDate').text(' ' + dateArray[1]);
			}
		}
	}, // END checkDates()
	
	
	//
	//	createHandlers()
	//
	createHandlers: function() {
		// console.log('-----createHandlers():');
		var that = this;
		
		// Region Dropdown - change
		if (that.settings.dropDowns.region) {
			$(that.settings.dropDowns.region).live('change', function(event){
				if ($(this).val() && $(this).val() !== that.region) {
					that.region = $(this).val();
					
					that.hideResults(that.populateCountries);
				}
			});
		}
		
		// Country Dropdown - change
		if (that.settings.dropDowns.country) {
			$(that.settings.dropDowns.country).live('change', function(event){
				if ($(this).val() && $(this).val() !== that.country) {
					that.country = $(this).val();
					
					// Set the region dropdown to match the selected region in case it was changed to a non-value option
					$(that.settings.dropDowns.region).val(that.region);
					
					that.hideResults(that.populateCities);
				}
			});
		}
		
		// City Dropdown - change
		if (that.settings.dropDowns.city) {
			$(that.settings.dropDowns.city).live('change', function(event){
				if ($(this).val() && $(this).val() !== that.city) {
					that.city = $(this).val();
					
					// Set the region/country dropdowns to match the selected region/country in case it was changed to a non-value option
					$(that.settings.dropDowns.region).val(that.region);
					$(that.settings.dropDowns.country).val(that.country);
					
					if (that.settings.autoDisplayResults) {
						that.hideResults(that.showResults);
					}
				}
			});
		}
		
		$('#goButtonLink').live('click', function(event){
			var notEmpty = $(that.settings.dropDowns.region).val() != '' && $(that.settings.dropDowns.country).val() != '' && $(that.settings.dropDowns.city).val() != '';
			var notSame = that.city !== $('p:first', that.settings.elements.header).text();
			
			if (notEmpty && ($(that.settings.elements.header).is(':hidden') || notSame)) {
				that.hideResults(that.showResults);
			}
		});
		
		// .cta Link - click
		$('.cta').live('click', function(event){
			var relArray = $(this).attr('rel').split(' ');
			var property = $('[id="' + relArray[0] + '"]', that.xml);
			
			// Traverse up the DOM to find the place to attach the datepicker
			var target = $(this).parent().parent().parent().find('.calendarContainer');
			
			// Copy the selected offer's details onto the main object
			that.current = {
				id: relArray[0],
				promocode: relArray[1],
				key: relArray[2],
				brand: that.settings.brands[$('brand', property).text().toLowerCase()],
				begins: new Date($('promocode:contains("' + relArray[1] + '")', property).parent().find('begins').text()),
				expires: new Date($('promocode:contains("' + relArray[1] + '")', property).parent().find('expires').text())
			};
			
			// If there is a datepick instance, remove it
			if ($('.hasDatepick').length) {
				$('.hasDatepick').removeAttr('id').datepick('destroy');
			}
			
			// Clear the field that datepick uses
			$(that.settings.datepick.defaultOptions.altField).val('');
			
			// Instantiate the DatePicker
			$(target).datepick();
			
			// Set the datepicker language, defaults to en_US
			if(window.datepickLanguage !== undefined && window.datepickLanguage !=='') {
				$(target).datepick($.datepick.regional[window.datepickLanguage]);
			}
			
			// Add the information display skeleton to the datepicker's container
			// If there is a booking info div, remove it
			if ($(that.settings.elements.bookingInfo).length) {
				$(that.settings.elements.bookingInfo).remove();
			}
			
			$('<div>')
				.addClass(that.stripPrefix(that.settings.elements.bookingInfo))
				.append(
					$('<h1>')
						.text($(that.current.key, that.copy).find('heading').text())
				)
				.append(
					$('<p>')
						.attr({ id: 'checkIn' })
						.text($('checkIn booking', that.copy).text())
						.append(
							$('<span>')
								.attr({ id: 'checkInDate' })
						)
				)
				.append(
					$('<p>')
						.attr({ id: 'checkOut' })
						.text($('checkOut booking', that.copy).text())
						.append(
							$('<span>')
								.attr({ id: 'checkOutDate' })
						)
				)
				.append(
					$('<a>')
						.attr({
							id: 'searchButtonLink',
							href: 'javascript:;'
						})
						.css({
							// This is for IE6
							backgroundImage: 'url(' + that.settings.assetPath + $('searchButton', that.copy).text() + ')'
						})
						.append(
							$('<img>')
								.attr({
									id: 'searchButton',
									src: that.settings.assetPath + 'cta-search.gif',
									alt: $('search', that.copy).text(),
									border: 0
								})
								.css({
									position: 'relative'
								})
						)
				)
				.append(
					$('<p>')
						.attr({ id: 'disclaimer' })
				)
				.prependTo(target.parent());
			
			// Add disclaimer if necessary
			if (parseInt(that.settings.lengthOfStay[that.current.promocode], 10)) {
				$('#disclaimer').text('* ' + that.settings.lengthOfStay[that.current.promocode] + ' ' + $('nightsDisclaimer', that.copy).text());
			}
			
			// Add eligibility dates
			if (!isNaN(that.current.begins) && !isNaN(that.current.expires)) {
				$('#disclaimer').append($('dateDiscliamer both', that.copy).text() + ' ' + $.datepick.formatDate('mm/dd/yy', that.current.begins) + ' - ' + $.datepick.formatDate('mm/dd/yy', that.current.expires) + '.');
			} else if (!isNaN(that.current.begins)) {
				$('#disclaimer').append($('dateDisclaimer begins', that.copy).text() + ' ' + $.datepick.formatDate('mm/dd/yy', that.current.begins) + '.');
			} else if (!isNaN(that.current.expires)) {
				$('#disclaimer').append($('dateDisclaimer expires', that.copy).text() + ' ' + $.datepick.formatDate('mm/dd/yy', that.current.expires) + '.');
			}
			
			// Add restrictions if specified
			if ($.trim( $('promocode:contains("' + that.current.promocode + '")', property).parent().find('restrictions').text() ) !== '') {
				$('#disclaimer').append( '** ' + $('restrictions', property).text() );
			}
			
		}); // END cta Link - click
		
		// search button - click
		$(that.settings.elements.searchButton).live('click', function(){
			var dateArray = $(that.settings.datepick.defaultOptions.altField).val().split(' - ');
			// Check to make sure dates have been selected
			if ($(that.settings.datepick.defaultOptions.altField).val()) {
				if (dateArray[0] === dateArray[1]) {
					alert($('errors noCheckOut', that.copy).text().replace(/%NL%/g, '\n'));
				} else {
					that.populateSearchFields();
				}
			} else {
				alert($('errors noDates', that.copy).text().replace(/%NL%/g, '\n'));
			}
		});
		// END search button - click
		
	}, // END createHandlers()
	
	
	//
	//	getDpOptions()
	//
	getDpOptions: function(settingsObj) {
		var that = this;
		return $.extend({}, that.settings.datepick.defaultOptions, settingsObj);
	}, // END getDpOptions()
	
	
	//
	//	hideResults()
	//
	hideResults: function(finishedFunction) {
		var that = this;
		
		$.scrollTo(0, {
			// Only set a duration if the window is not at the top
			duration: $(document).scrollTop() === 0 ? 0 : that.settings.animation.outDuration / 2,
			onAfter: function(){
				if ($.browser.msie) {
					$(that.settings.elements.header).hide().empty().appendTo('body');
					$(that.settings.elements.container).hide().appendTo('body');
					$(that.settings.elements.individual).remove();
					finishedFunction.apply(that);
					
				} else {
					$(that.settings.elements.header).slideUp(that.settings.animation.outDruation);
					$(that.settings.elements.container).slideFadeToggle(that.settings.animation.outDuration, function(){
						$(that.settings.elements.header).hide().empty().appendTo('body');
						$(that.settings.elements.container).appendTo('body');
						$(that.settings.elements.individual).remove();
						finishedFunction.apply(that);
					});
				}
			}
		});
		
	}, // END hideResults()
	
	
	//
	//	loadCopy()
	//
	loadCopy: function() {
		// console.log('-----loadCopy():');
		var that = this;
		
		var copyRequest = $.ajax({
			url: that.settings.assetPath + 'copy.xml',
			async: false,
			dataType: 'xml',
			error: function() {
				if (confirm(window.preXMLerrors.noXML)) {
					window.location = window.location;
				}
			}
		});
		
		that.copy = copyRequest.responseXML;
	}, // END loadCopy()
	
	
	//
	//	loadProperties()
	//
	loadProperties: function() {
		// console.log('-----loadProperties():');
		var that = this;
		
		var dataRequest = $.ajax({
			url: that.settings.assetPath + 'properties.xml',
			async: false,
			dataType: 'xml',
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				if (confirm(window.preXMLerrors.noXML)) {
					window.location = window.location;
				}
			}
		});
		
		that.xml = dataRequest.responseXML;
	}, // END loadProperties()
	
	
	//
	//	now()
	//
	now: function() {
		return new Date();
	}, // END now()
	
	
	//
	//	populateCities()
	//
	populateCities: function() {
		// console.log('-----populateCities():');
		var that = this;
		var selectedCountry = $('[country="' + that.country + '"]', this.xml);
		var cityKey;
		var cityObj = {};
		var cityArray = [];
		
		if (that.settings.dropDowns.city) {
			// Get a unique list of cities for the selected country.
			$(selectedCountry).each(function(index){
				cityObj[$(this).attr('city')] = '';
			});
			
			for (cityKey in cityObj) {
				if (cityObj.hasOwnProperty(cityKey)) {
					cityArray.push(cityKey);
				}
			}
			cityArray.sort();
			
			// Empty the menu and add a hint element
			$(that.settings.dropDowns.city).empty().append(
				$('<option>')
					.attr({
						value: ''
					})
					.text('City')
			);
			
			for (var i = 0; i < cityArray.length; i++) {
				$(that.settings.dropDowns.city).append(
					$('<option>')
						.attr({
							value: cityArray[i]
						})
						.text(cityArray[i])
				);
			}
			$(that.settings.dropDowns.city).removeAttr('disabled');
			
			if (that.settings.dropDowns.autoSelect && cityArray.length == 1) {
				// Select the lone option, setTimeout to get IE6 to play nice.
				setTimeout(function(){
					$(that.settings.dropDowns.city).val(cityArray[0]);
				}, 0);
				
				that.city = cityArray[0];
				that.showResults();
			}
		}
	}, // END populateCities()
	
	
	//
	//	populateCountries()
	//
	populateCountries: function() {
		// console.log('-----populateCountries():');
		var that = this;
		var selectedRegion = $('[region="' + that.region + '"]', this.xml);
		var countryKey;
		var countryObj = {};
		var countryArray = [];
		
		if (that.settings.dropDowns.country) {
			// Get a unique list of countries for the selected region.
			$(selectedRegion).each(function(index) {
				countryObj[$(this).attr('country')] = '';
			});
			
			for (countryKey in countryObj) {
				if (countryObj.hasOwnProperty(countryKey)) {
					countryArray.push(countryKey);
				}
			}
			countryArray.sort();
			
			// Empty the menu and add a hint element
			$(that.settings.dropDowns.country).empty().append(
				$('<option>')
					.attr({
						value: ''
					})
					.text('Country')
			);
			
			// Create an option for each country in the array.
			for (var i = 0; i < countryArray.length; i++) {
				$(that.settings.dropDowns.country).append(
					$('<option>')
						.attr({
							value: countryArray[i]
						})
						.text(countryArray[i])
				);
			}
			$(that.settings.dropDowns.country).removeAttr('disabled');
		}
		
		if (that.settings.dropDowns.autoSelect && countryArray.length == 1) {
			// Select the lone option, setTimeout to get IE6 to play nice.
			setTimeout(function(){
				$(that.settings.dropDowns.country).val(countryArray[0]);
			}, 0);
			
			that.country = countryArray[0];
			that.populateCities();
		}
	}, // END populateCountries()
	
	
	//
	//	populateRegions()
	//
	populateRegions: function() {
		// console.log('-----populateRegions():');
		var that = this;
		
		// If the region info is in a hidden field, then just grab the info and go.
		if ($(that.settings.dropDowns.region).attr('type') === 'hidden') {
			that.region = $(that.settings.dropDowns.region).val();
			that.populateCountries();

		} else {
			if (that.settings.dropDowns.region) {
				// Empty the menu and append a hint element
				$(that.settings.dropDowns.region).empty().append(
					$('<option>')
						.attr({
							value: ''
						})
						.text('Region')
				);
				
				// Create one option for each region
				for (var i = 0; i < that.regionArray.length; i += 1) {
					$(that.settings.dropDowns.region).append(
						$('<option>')
							.attr({
								value: that.regionArray[i]
							}).text(that.regionArray[i])
					);
				}
				$(that.settings.dropDowns.region).removeAttr('disabled');
			}
			
			if (that.settings.dropDowns.autoSelect && that.regionArray.length == 1) {
				// Select the lone option, setTimeout is to get IE6 to play nice.
				setTimeout(function() {
					$(that.settings.dropDowns.region).val(that.regionArray[0]);
				}, 0);
				
				that.region = that.regionArray[0];
				that.populateCountries();
			}
		}
	}, // END populateRegions()
	
	
	//
	//	populateSearchFields()
	//
	populateSearchFields: function() {
		var that = this;
		var dateArray = $(that.settings.datepick.defaultOptions.altField).val().split(' - ');
		dateArray.sort();
		
		var inDate = new Date(dateArray[0]);
		var outDate = new Date(dateArray[1]);
		
		// Fill in the fields using the information we already have
		$('#arrivalDate').val($.datepick.formatDate('mm/dd/yy', inDate));
		$('#arrivalDateYear').val($.datepick.formatDate('yy', inDate));
		$('#arrivalDateMonth').val($.datepick.formatDate('m', inDate));
		$('#arrivalDateDay').val($.datepick.formatDate('d', inDate));
		$('#departureDate').val($.datepick.formatDate('mm/dd/yy', outDate));
		$('#departureDateYear').val($.datepick.formatDate('yy', outDate));
		$('#departureDateMonth').val($.datepick.formatDate('m', outDate));
		$('#departureDateDay').val($.datepick.formatDate('yy', outDate));
		$('#propertyID').val(that.current.id);
		$('#promotionCode').val(that.current.promocode);
		
		// Changes input name from promocode to ratePlanName for specific codes.
		if (that.current.promocode === 'APRSRT') {
			// This particular code is a rate plan so we need to change some info for the input
			$('#promotionCode').attr({ name: 'ratePlanName' });
		} else {
			$('#promotionCode').attr({ name: 'promotionCode' });
		}
		
		// Can't use lengthOfStay lookup because we need to know for credit offers too
		$('#lengthOfStay').val(Math.ceil((outDate.getTime() - inDate.getTime()) / that.settings.millisecondsPerDay));
		
		// Validate the form, just in case
		that.validateSearchFields();
	},
	
	//
	//	processProperties()
	//
	processProperties: function() {
		// console.log('-----processProperties():');
		var that = this;
		var regionKey;
		var regionObj = {};
		var regionArray = [];
		
		$('property', that.xml).each(function(index){
			// Parse offer availability
			// Daily Credit
			if ($('credit daily available', this).text() == 1) {
				$(this).attr({ dailyCredit: 1 });
			}
			
			// Three Nights
			if ($('nights three available', this).text() == 1) {
				$(this).attr({ threeNights: 1 });
			}
			
			// Four Nights
			if ($('nights four available', this).text() == 1) {
				$(this).attr({ fourNights: 1 });
			}
			
			// Six Nights
			if ($('nights six available', this).text() == 1) {
				$(this).attr({ sixNights: 1 });
			}
			
			// Copy data from nodes to attributes to allow attribute searches
			$(this).attr({
				id: $('id', this).text(),
				region: $('region', this).text(),
				country: $('country', this).text(),
				city: $('city', this).text(),
				unique: index
			});
			
			// By adding the data as the key we end up with only unique keys
			regionObj[$('region', this).text()] = '';
		});
		
		// We do this here because we need to know the region info, and we're alredy in a .each() loop.
		// Add each region as an key.
		for (regionKey in regionObj) {
			if (regionObj.hasOwnProperty(regionKey)) {
				regionArray.push(regionKey);
			}
		}
		that.regionArray = regionArray.sort();
		
		that.populateRegions();
	}, // END processProperties()
	
	
	//
	//	showResults()
	//
	showResults: function(){
		// console.log('-----showResults():');
		var that = this;
		var selectedCity;
		var imageName;
		
		// Move focus away from the dropdowns so the scroll wheel scrolls the page and not the dropdown
		$('body').focus();
		
		// Put up a wait cursor so the user knows we didn't die
		that.cursorWait();
		
		// Put the selected city name in the header
		$(that.settings.elements.header).empty().append($('<p>' + that.city + '</p>'));
		
		// Remove any offers that may be attached, can't use empty() because header is in same element
		$(that.settings.elements.individual).remove();
		
		// Try to get a set based on the city name.
		try {
			selectedCity = $('[city="' + that.city + '"]', that.xml);
		} catch(e) {}
		
		// If selectedCity is undefined then try a wild card search
		if (selectedCity === undefined) {
			selectedCity = $('[city*="' + that.city.replace("'","") + '"]', that.xml);
		}
		
		// BEGIN Dynamic HTML Generation
		//		It is likely that you will need to change the following code to reflect the layout for your project.
		selectedCity.each(function(index){
			// Container
			$('<div>')
				.addClass(that.stripPrefix(that.settings.elements.individual) + ' prop' + $('id', this).text())
				.attr({
					id: that.settings.elements.prefix + index
				})
				.append(
					$('<div>')
						.addClass('bookingContainer')
						.append(
							$('<div>')
								.addClass('calendarContainer')
						)
				)
				.append(
					$('<div>')
						.addClass('infoContainer')
				)
				.appendTo($(that.settings.elements.container).hide());
			
			// Use the specified file if one is provided, otherwise auto generate the name
			imageName = $('image', this).text() ? $('image', this).text() : $('id', this).text() + '.jpg' ;
			
			// Image
			$('<div>')
				.addClass('result-image')
				.append(
					$('<a>')
						.attr({
							target: '_blank',
							href: that.settings.urls.propertyDetail
								.replace('%BRAND%', that.settings.brands[$('brand', this).text().toLowerCase()])
								.replace('%PROPID%', $('id', this).text())
						})
						.append(
							$('<img>')
								.attr({
									src: that.settings.assetPath + imageName,
									alt: $('hotel', this).text()
								})
						)
				)
				.appendTo($('div.infoContainer:last', $(that.settings.elements.container)));
				
			// Property Title
			$('<div>')
				.addClass('hotel')
				.append(
					$('<a>')
						.attr({
							target: '_blank',
							href: that.settings.urls.propertyDetail
								.replace('%BRAND%', that.settings.brands[$('brand', this).text().toLowerCase()])
								.replace('%PROPID%', $('id', this).text())
						})
						.text($('hotel', this).text())
				)
				.appendTo($('div.infoContainer:last', $(that.settings.elements.container)));
			

			// Daily Credit
			if ($(this).attr('dailyCredit')) {
				$('<div>')
					.addClass('offer dailyCredit')
					.append(
						$('<p>')
							.text	($('dailyCredit listing', that.copy).text())
					)
					.append(
						$('<a>')
							.addClass('cta')
							.attr({
								rel: $('id', this).text() + ' ' + $('credit daily promocode', this).text() + ' dailyCredit',
								href: 'javascript:;'
							})
							.text($('cta', that.copy).text())
					)
					.appendTo($('div.infoContainer:last', $(that.settings.elements.container)));
			} // END Daily Credit
				

			// Three Nights
			if ($(this).attr('threeNights')) {
				$('<div>')
					.addClass('offer threeNights')
					.append(
						$('<p>')
							.text($('threeNights listing', that.copy).text())
					)
					.append(
						$('<a>')
							.addClass('cta')
							.attr({
								rel: $('id', this).text() + ' ' + $('nights three promocode', this).text() + ' threeNights',
								href: 'javascript:;'
							})
							.text($('cta', that.copy).text())
					)
					.appendTo($('div.infoContainer:last', $(that.settings.elements.container)));
			} // END Three Nights

			// Four Nights
			if ($(this).attr('fourNights')) {
				$('<div>')
					.addClass('offer fourNights')
					.append(
						$('<p>')
							.text($('fourNights listing', that.copy).text())
					)
					.append(
						$('<a>')
							.addClass('cta')
							.attr({
								rel: $('id', this).text() + ' ' + $('nights four promocode', this).text() + ' fourNights',
								href: 'javascript:;'
							})
							.text($('cta', that.copy).text())
					)
					.appendTo($('div.infoContainer:last', $(that.settings.elements.container)));
			} // END Four Nights
				
			// Six Nights
			if ($(this).attr('sixNights')) {
				$('<div>')
					.addClass('offer sixNights')
					.append(
						$('<p>')
							.text($('sixNights listing', that.copy).text())
					)
					.append(
						$('<a>')
							.addClass('cta')
							.attr({
								rel: $('id', this).text() + ' ' + $('nights six promocode', this).text() + ' sixNights',
								href: 'javascript:;'
							})
							.text($('cta', that.copy).text())
					)
					.appendTo($('div.infoContainer:last', $(that.settings.elements.container)));
			} // END Six Nights
				
			// END Dynamic HTML Generation
			
		}); // END selectedCity.each()
		
		$('<div>')
			.css({ clear: 'both' })
			.appendTo($(that.settings.elements.container));
			
		$.scrollTo(0, {
			// Only set a duration if the window is not at the top
			duration: $(document).scrollTop() === 0 ? 0 : that.settings.animation.outDuration / 2,
			onAfter: function(){
				setTimeout(function(){
					// Move the elements back to the propper position just in time
					$(that.settings.elements.header).insertBefore($('#bestRate-container'));
					$(that.settings.elements.container).insertBefore($('#bestRate-container'));
					$(that.settings.elements.header).slideFadeToggle(that.settings.animation.inDuration);
					$(that.settings.elements.container).slideFadeToggle(that.settings.animation.inDuration, that.cursorAuto);
				}, 0);
			}
		});
	
	}, // END showResults()
	
	
	//
	//	statusSelectCheckIn()
	//
	statusSelectCheckIn: function() {
		var that = window.stwSearch;
		return $('checkIn dpStatus', that.copy).text();
	}, // END statusSelectCheckIn()
	
	
	//
	//	statusSelectCheckOut()
	//
	statusSelectCheckOut: function() {
		var that = window.stwSearch;
		return $('checkOut dpStatus', that.copy).text();
	}, // END statusSelectCheckOut()
	
	
	//
	//	cursorAuto()
	//
	cursorAuto: function(){
		$('body').css({ cursor: '' });
	},
	
	
	//
	//	cursorWait()
	//
	cursorWait: function() {
		$('body').css({ cursor: 'wait' });
	},
	
	
	//
	//	stripPrefix();
	//
	stripPrefix: function(identifier) {
		return identifier.replace(/[#.]/g,'');
	}, // END stripPrefix()
	
	
	//
	//	submitSearch()
	//
	submitSearch: function() {
		var that = this;
		
		// setTimeout so IE6 plays nice
		setTimeout(function(){
			window.location = that.settings.urls.search.replace('%BRAND%', that.current.brand) + '?' +
				$('#bookingForm').serialize() + '&' + that.settings.urls.imString.replace('%IDENT%', that.settings.ident[that.current.promocode.toUpperCase()]).replace('%PROPID%', that.current.id);
		}, 0);
	}, // END submitSearch()
	
	
	//
	//	today()
	//
	today: function() {
		var that = this;
		return new Date(that.now().getMonth() + 1 + '/' + that.now().getDate() + '/' + that.now().getFullYear());
	}, // END today()
	
	
	//
	//	validateSearchFields()
	//
	validateSearchFields: function() {
		var that = this;
		var valid = true;
		
		$('#bookingForm input').each(function(){
			if (!$(this).val()) {
				valid = false;
			}
		});
		
		if (valid) {
			that.submitSearch();
		}
	} // END validateSearchFields()
	
}; // END stwSearch
 
$(document).ready(function(){
	if ($.browser.msie && $.browser.version == 6) {
		$('img').attr({ galleryimg: 'no' });
	}
	stwSearch.init();
});

jQuery.fn.slideFadeToggle = function(speed, callback) {
  return this.animate({opacity: 'toggle', height: 'toggle'}, speed, callback);
};


