/*
offers.js

version: 1.0
created: 10/1/2009
requires: jQuery 1.3
author: Kevin Kilcher for Domain Studios

functionality: The object retrieves and filters the specified xml file based on the currently selected tab, region and country, then displays the appropriate offerrs.
*/
var offers = {
	xmlPath: 'Media/offers.xml',
	imgPath: 'Media/',
	regionRow: '#regionRow',
	countryRow: '#countryRow',
	breakfastURL: 'http://www.starwoodhotels.com/lemeridien/search/preDecider.html?propertyID=%PROPERTYID%&ratePlanName=BREAK&ES=LM_LP_PACKAGE_BREAK',
	discountURL: 'http://www.starwoodhotels.com/lemeridien/search/preDecider.html?propertyID=%PROPERTYID%&ratePlanName=DAILYR&ES=LM_LP_PACKAGE_PERCENTOFF',
	thirdNightURL: 'http://www.starwoodhotels.com/lemeridien/search/preDecider.html?propertyID=%PROPERTYID%&promoCode=%FNCODE%&ES=LM_LP_PACKAGE_Z3',
	fourthNightURL: 'http://www.starwoodhotels.com/lemeridien/search/preDecider.html?propertyID=%PROPERTYID%&promoCode=%FNCODE%&ES=LM_LP_PACKAGE_Z4',
	twoNightsURL: 'http://www.starwoodhotels.com/lemeridien/search/preDecider.html?propertyID=%PROPERTYID%&promoCode=%FNCODE%&ES=LM_LP_PACKAGE_Z6',
	readMoreURL: 'http://www.starwoodhotels.com/lemeridien/property/overview/index.html?propertyID=%PROPERTYID%',
	emptyRegion: '<option value="">-- Select a Region --</option>',
	emptyCountry: '<option value="">-- Select a Country --</option>',
	offerGroup: ['all', 'breakfast', 'discount', 'freenight'],
	scrollDownTop: 450,
	scrollUpTop: 0,
	scrollDownSpeed: 750,
	scrollUpSpeed: 750,
	slideUpSpeed: 500,
	slideDownSpeed: 1000,
	
	init: function(){
		// Prep the dropdowns to accept data.
		$(this.regionRow).find('select').empty().append($(this.emptyRegion));
		$(this.countryRow).addClass('disabled').find('select').attr('disabled','disabled').empty().append($(this.emptyCountry));
		
		// load the XML file.
		this.loadXML();
		
		// Create a handy reference to the offers
		this.$offers = $('offer', this.xml);
		
		// Copy some information from text nodes to attributes of the <offer> items.
		this.$offers.each(
			function(index){
				$(this).attr('id', $('id', this).text());
				$(this).attr('country', $('country', this).text());
				$(this).attr('region', $('region', this).text());
				$(this).attr('freenight', $('freenight', this).text() == '1');
				$(this).attr('breakfast', $('breakfast', this).text() == '1');
				$(this).attr('discount', $('discount', this).text() != '');
			}
		);
		
		// Detect IE 6/7 and change the slide speeds to 0 because content of #properties becomes visible before animation
		if(navigator.userAgent.indexOf('MSIE 6') > -1 || navigator.userAgent.indexOf('MSIE 7') > -1){
			this.slideUpSpeed = 0;
			this.slideDownSpeed = 0;
		}
		
		// Populate the Country Dropdown
		this.populateRegionDropdown();
	},
	
	loadXML: function(){
		var myThis = this;
		$.ajax({
			type: 'GET',
			url: this.xmlPath,
			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){
				myThis.xml = data;
			}
		});
	},
	
	getRegions: function(){
		var myThis = this;
		var regionObject = new Object();
		var regionArray = new Array();
		
		if(this.offerGroup[window.currentTab] == 'all' || this.offerGroup[window.currentTab] == 'breakfast'){
			$('[breakfast="true"]', this.xml).each( function(index){ regionObject[$('region', this).text()] = null; } );
		}
		
		if(this.offerGroup[window.currentTab] == 'all' || this.offerGroup[window.currentTab] == 'discount'){
			$('[discount="true"]', this.xml).each( function(index){ regionObject[$('region', this).text()] = null; } );
		}
		
		if(this.offerGroup[window.currentTab] == 'all' || this.offerGroup[window.currentTab] == 'freenight'){
			$('[freenight="true"]', this.xml).each( function(index){ regionObject[$('region', this).text()] = null; } );
		}
		
		for(region in regionObject){
			regionArray.push(region);
		}
		regionArray.sort();
		this.regions = regionArray;
	},
	
	populateRegionDropdown: function(){
		var myThis = this;
		var $regionDropdown = $(this.regionRow).find('select');
		$regionDropdown.empty().append(this.emptyRegion);
		$(this.countryRow).addClass('disabled').find('select').attr('disabled','disabled').empty().append($(this.emptyCountry));

		this.getRegions();
		
		for(var i = 0; i < this.regions.length; i++){
			$regionDropdown.append('<option value="' + this.regions[i] + '">' + this.regions[i] + '</option>');
		}
		
		$regionDropdown.change(
			function(event){
				offers.populateCountryDropdown(event.currentTarget.value);
			}
		);
	},
	
	getCountries: function(){
		var myThis = this;
		var countryObject = new Object();
		var countryArray = new Array();
		
		if(this.offerGroup[window.currentTab] == 'all' || this.offerGroup[window.currentTab] == 'breakfast'){
			$('[region="' + this.region + '"]', this.xml).filter('[breakfast="true"]').each(
				function(index){ countryObject[$('country', this).text()] = null; }
			);
		}
		
		if(this.offerGroup[window.currentTab] == 'all' || this.offerGroup[window.currentTab] == 'discount'){
			$('[region="' + this.region + '"]', this.xml).filter('[discount="true"]').each(
				function(index){ countryObject[$('country', this).text()] = null; }
			);
		}
		
		if(this.offerGroup[window.currentTab] == 'all' || this.offerGroup[window.currentTab] == 'freenight'){
			$('[region="' + this.region + '"]', this.xml).filter('[freenight="true"]').each(
				function(index){ countryObject[$('country', this).text()] = null; }
			);
		}
			
		for(var country in countryObject){
			countryArray.push(country);	
		}
		
		countryArray.sort();
		this.countries = countryArray;
	},
	
	populateCountryDropdown: function(findRegion){
		this.region = findRegion;
		
		var myThis = this;
		var $countryDropdown = $(this.countryRow).find('select');
		$countryDropdown.empty().append(this.emptyCountry);
		
		this.getCountries();
		
		for(var i = 0; i < this.countries.length; i++){
			$countryDropdown.append('<option value="' + this.countries[i] + '">' + this.countries[i] + '</option>');
		}
		
		$countryDropdown.removeAttr('disabled');
		$(this.countryRow).removeClass('disabled');
	},
	
	getSelected: function(){
		this.region = $(this.regionRow).find('select').val();
		this.country = $(this.countryRow).find('select').val();
	},
	
	buildProperty: function(currentOffer){
		var $currentOffer = $(currentOffer);
		var skeleton = '<div id="%PROPERTYID%" class="propertyWrapper">';
		skeleton += '<img src="%IMGSRC%" width="300" alt="%IMGALT%" title=""/>';
		skeleton += '<a href="javascript:;">Book Now ></a>';
		skeleton += '<h1>%PROPERTY%</h1>';
		skeleton += '<p>%DESCRIPTION%<a href="' + this.readMoreURL + '">Read&#160;More</a></p>';
		skeleton += '<div class="offerWrapper">';
		skeleton += '<h2>OFFERS:</h2>';
		skeleton += '<div class="offers">';
		skeleton += '<div class="column1">';
		skeleton += '</div><!-- end column1 -->';
		skeleton += '</div><!-- end offers -->';
		skeleton += '</div><!-- end offerWrapper -->';
		skeleton += '</div><!-- end propertyWrapper -->';
		
		skeleton = skeleton.replace(/%PROPERTYID%/g, $currentOffer.attr('id'));
		skeleton = skeleton.replace(/%IMGSRC%/g, this.imgPath + $currentOffer.attr('id') + '.jpg');
		skeleton = skeleton.replace(/%IMGALT%/g, $currentOffer.find('property').text());
		skeleton = skeleton.replace(/%PROPERTY%/g, $currentOffer.find('property').text());
		skeleton = skeleton.replace(/%DESCRIPTION%/g, $currentOffer.find('description').text());
		return skeleton;
	},
	
	buildProperties: function(){
		var myThis = this;
		var $properties = $('#properties');
		$properties.empty();
		
		this.getSelected();
		
		// Get all the offers for the country then filter them based on the current tab.
		var $countryOffers = $('[country="' + this.country + '"]', this.xml);
		if(this.offerGroup[window.currentTab] != 'all'){
			$countryOffers = $countryOffers.filter('[' + this.offerGroup[window.currentTab]+ '="true"]');
		}
		
		$countryOffers.each(
			function(index){
				$properties.append(myThis.buildProperty(this));
			}
		);

		$('.propertyWrapper > a', $properties).addClass('bookNowLink').click(
			function(event){
				myThis.validateBooking(event);
			}
		);
		$('.propertyWrapper > p > a', $properties).addClass('readMoreLink');
		$('.propertyWrapper > img', $properties).addClass('propertyImage');
		
		this.addOffers();
		
		$('#properties').slideDown(myThis.slideDownSpeed, function(){ $.scrollTo({top: myThis.scrollDownTop, left: 0}, myThis.scrollDownSpeed); });
	},
	
	addOffers: function(){
		var myThis = this;
		$('#properties .propertyWrapper').each(
			function(index){
				var offerCount = 0;
				var restrictionText = $('[id="' + this.id + '"]', $(myThis.xml)).find('restrictions').text();
				var restrictionStar = restrictionText != '' ? ' *' : '' ;

				// Tell me how many offers this location has so I can determine if I should use radio buttons or not
				if(myThis.offerGroup[window.currentTab] == 'all') {
					offerCount = $('[id="' + this.id + '"]', $(myThis.xml)).filter('[breakfast="true"]').size() 
										+ $('[id="' + this.id + '"]', $(myThis.xml)).filter('[discount="true"]').size() 
										+ $('[id="' + this.id + '"]', $(myThis.xml)).filter('[freenight="true"]').size();
				} else if(myThis.offerGroup[window.currentTab] == 'breakfast') {
					offerCount = $('[id="' + this.id + '"]', $(myThis.xml)).filter('[breakfast="true"]').size();
				} else if(myThis.offerGroup[window.currentTab] == 'discount') {
					offerCount = $('[id="' + this.id + '"]', $(myThis.xml)).filter('[discount="true"]').size();
				} else if(myThis.offerGroup[window.currentTab] == 'freenight') {
					offerCount = $('[id="' + this.id + '"]', $(myThis.xml)).filter('[freenight="true"]').size();
				}

				if((myThis.offerGroup[window.currentTab] == 'all' || myThis.offerGroup[window.currentTab] == 'breakfast') && $('[id="' + this.id + '"]', $(myThis.xml)).filter('[breakfast="true"]').size()){
					$('.column1', this).append($('<div id="offerItem_' + this.id + '_breakfast"></div>'));

					if(offerCount > 1) {
						$('#offerItem_' + this.id + '_breakfast', this).append('<input type="radio" name="offerRadio' + this.id + '" value="breakfast" /><label>Breakfast package</label>');
					} else {
						$('#offerItem_' + this.id + '_breakfast', this).append('<input type="hidden" name="offerRadio' + this.id + '" value="breakfast" /><label>Breakfast package</label>');
					}
				} 
				
				if((myThis.offerGroup[window.currentTab] == 'all' || myThis.offerGroup[window.currentTab] == 'discount') && $('[id="' + this.id + '"]', $(myThis.xml)).filter('[discount="true"]').size()){
					$('.column1', this).append($('<div id="offerItem_' + this.id + '_discount"></div>'));

					if(offerCount > 1) {
						$('#offerItem_' + this.id + '_discount', this).append('<input type="radio" name="offerRadio' + this.id + '" value="discount" /><label>'
							+ $('[id="' + this.id + '"][discount="true"]', myThis.xml).find('discount').text() + restrictionStar + '</label>');
					} else {
						$('#offerItem_' + this.id + '_discount', this).append('<input type="hidden" name="offerRadio' + this.id + '" value="discount" /><label>'
							+ $('[id="' + this.id + '"][discount="true"]', myThis.xml).find('discount').text() + restrictionStar + '</label>');
					}
				} 
				
				if((myThis.offerGroup[window.currentTab] == 'all' || myThis.offerGroup[window.currentTab] == 'freenight') && $('[id="' + this.id + '"]', $(myThis.xml)).filter('[freenight="true"]').size()){
					var fncodeArray = $('[id="' + this.id + '"][freenight="true"]', myThis.xml).find('fncode').text().split(',');
					for(var i = 0; i < fncodeArray.length; i++){
						fncodeArray[i] = fncodeArray[i].replace(' ', '');
						var label;
						if(fncodeArray[i].toUpperCase().indexOf('Z3') > -1){
							label = 'Buy 2 get 3rd night free';
						} else if(fncodeArray[i].toUpperCase().indexOf('Z4') > -1){
							label = 'Buy 3 get 4th night free';
						} else if(fncodeArray[i].toUpperCase().indexOf('Z6') > -1){
							label = 'Buy 4 get 2 nights free';
						}
						
						$('.column1', this).append($('<div id="offerItem_' + this.id + '_discount_' + fncodeArray[i] + '"></div>'));

						if(fncodeArray.length > 1 || offerCount > 1) {
						$('#offerItem_' + this.id + '_discount_' + fncodeArray[i], this).append('<input type="radio" name="offerRadio' + this.id +
							'" value="fncode" rel="' + fncodeArray[i] +'" /><label>' + label + '</label>');
						} else {
						$('#offerItem_' + this.id + '_discount_' + fncodeArray[i], this).append('<input type="hidden" name="offerRadio' + this.id +
							'" value="fncode" rel="' + fncodeArray[i] +'" /><label>' + label + '</label>');
						}
					}
					
					if($(this).find('.column1').children().size() > 3){
						$(this).find('.column1').parent().append('<div class="column2"></div>');
						$(this).find('.column1').children(':gt(2)').appendTo($(this).find('.column2'));
					}
				}
				
				if(restrictionText != '' && (myThis.offerGroup[window.currentTab] == 'all' || myThis.offerGroup[window.currentTab] == 'discount')){
					$('#' + this.id).find('.offerWrapper').append('<div>* ' + restrictionText + '</div>').find('div:last').addClass('restrictions');
				}
			}
		);
	},
	
	validateBooking: function(event){
		var id = $(event.currentTarget).parent().attr('id');
		var $selectedOffer = $(event.currentTarget).parent().find(':checked');
		var $selectedOfferHidden = $(event.currentTarget).parent().find('input[type="hidden"]');
		var destinationURL;
	

		if($selectedOffer.size() > 0){
			if($selectedOffer.val() == 'breakfast'){
				destinationURL = this.breakfastURL.replace('%PROPERTYID%', id);
			} else if($selectedOffer.val() == 'discount'){
				destinationURL = this.discountURL.replace('%PROPERTYID%', id);
			} else if($selectedOffer.val() == 'fncode'){
				var fncode = $selectedOffer.attr('rel').toUpperCase();
				if(fncode.indexOf('Z3') > -1){
					destinationURL = this.thirdNightURL.replace('%PROPERTYID%', id);
				} else if(fncode.indexOf('Z4') > -1){
					destinationURL = this.fourthNightURL.replace('%PROPERTYID%', id);
				} else if(fncode.indexOf('Z6') > -1){
					destinationURL = this.twoNightsURL.replace('%PROPERTYID%', id);
				}
				destinationURL = destinationURL.replace('%FNCODE%', fncode);
			}
			// The timeout is used to get IE 6 to execute the location change properly.
			setTimeout(function(){ window.location = destinationURL; }, 0);
			
		} else if($selectedOfferHidden.size() > 0){

			if($selectedOfferHidden.val() == 'breakfast'){
				destinationURL = this.breakfastURL.replace('%PROPERTYID%', id);
			} else if($selectedOfferHidden.val() == 'discount'){
				destinationURL = this.discountURL.replace('%PROPERTYID%', id);
			} else if($selectedOfferHidden.val() == 'fncode'){
				var fncode = $selectedOfferHidden.attr('rel').toUpperCase();
				if(fncode.indexOf('Z3') > -1){
					destinationURL = this.thirdNightURL.replace('%PROPERTYID%', id);
				} else if(fncode.indexOf('Z4') > -1){
					destinationURL = this.fourthNightURL.replace('%PROPERTYID%', id);
				} else if(fncode.indexOf('Z6') > -1){
					destinationURL = this.twoNightsURL.replace('%PROPERTYID%', id);
				}
				destinationURL = destinationURL.replace('%FNCODE%', fncode);
			}

			// The timeout is used to get IE 6 to execute the location change properly.
			setTimeout(function(){ window.location = destinationURL; }, 0);
			
		} else {
			alert('Please select an offer before booking your trip.');
		}
	},
	
	tabChange: function(){
		var myThis = this;
		
		// Timeout is for IE 6/7 to stop white bg from disappearing just before #properties content does
		$.scrollTo({top: myThis.scrollUpTop, left: 0}, myThis.scrollUpSpeed, {onAfter: function(){ $('#properties').slideUp(myThis.slideUpSpeed, function(){ setTimeout('offers.populateRegionDropdown()', 100); }); }});
	},
	
	search: function(event){
		var myThis = this;
		
		if($(this.regionRow).find('select').val() != '' && $(this.countryRow).find('select').val() != ''){
			$('body').css('cursor','wait');
			$.scrollTo({top: myThis.scrollUpTop, left: 0}, myThis.scrollUpSpeed, { onAfter:
				function(){ 
					$('#properties').slideUp(myThis.slideUpSpeed, function(){ 
						offers.buildProperties();
						$('body').css('cursor','auto');
					});
				}
			});
		} else {
			alert('Please select both a region and country for your search and try again.');
		}
	}
}
