var CHb = CHb || {};

CHb.Global = (function (window, document) {
	
	"use strict";
	
	// Widget localization
	var chb_localization = {
		
		'de': {
			'rates': 'Raten einsehen',
			'interstitial': 'Sie werden auf eine sichere buchungsseite der Choice Hotels weitergeleitet',
			'checkin': 'Anreisedatum',
			'checkout': 'Abreisedatum',
			'adults': 'Erwachsene',
			'children': 'Kinder',
			'rooms': 'Zimmer',
			'guarantee': 'Internet Bestpreis-Garantie',
			'book': 'Zimmer buchen'
		},
		'en': {
			'rates': 'View Rates',
			'interstitial': 'You are being taken to a secure booking page powered by Choice Hotels ',
			'checkin': 'Check-in Date',
			'checkout': 'Check-out Date',
			'adults': 'Adults',
			'children': 'Children',
			'rooms': 'Rooms',
			'guarantee': 'Best Internet Rate Guarantee',
			'book': 'Book a Room'
		},
		'es': {
			'rates': 'Ver Tarifas',
			'interstitial': 'Lo estamos redireccionando a una pagina segura de reservaciones de Choice Hotels M&eacute;xico',
			'checkin': 'Fecha de registro',
			'checkout': 'Fecha de salida',
			'adults': 'Adultos',
			'children': 'Ni&ntilde;os',
			'rooms': 'Habitaciones',
			'guarantee': 'Mejor Tarifa Garantizada en Internet',
			'book': 'Reserve una habitaci&oacute;n'
		},
		'fr_CA': {
			'rates': 'R&eacute;server',
			'interstitial': 'Vous allez etre redirige vers une page securisee de Choice Hotels',
			'checkin': 'Date d\'arriv&eacute;e',
			'checkout': 'Date de d&eacute;part',
			'adults': 'Adultes',
			'children': 'Enfants',
			'rooms': 'Chambres',
			'guarantee': 'Garantie du meilleur tarif en ligne',
			'book': 'R&eacute;server'
		},
		'fr_FR': {
			'rates': 'R&eacute;server',
			'interstitial': 'Vous allez etre redirige vers une page securisee de Choice Hotels',
			'checkin': 'Date d\'arriv&eacute;e',
			'checkout': 'Date de d&eacute;part',
			'adults': 'Adultes',
			'children': 'Enfants',
			'rooms': 'Chambres',
			'guarantee': 'Meilleur Tarif Internet Garanti',
			'book': 'R&eacute;server'
		},
		'it': {
			'rates': 'Visualizza tariffe',
			'interstitial': 'Stai per essere trasferito ad una pagina sicura per prenotazioni con Choice Hotels',
			'checkin': 'Data di arrivo',
			'checkout': 'Data di partenza',
			'adults': 'Adulti',
			'children': 'Bambini',
			'rooms': 'Camere',
			'guarantee': 'Garanzia della miglior tariffa Internet',
			'book': 'Prenota una camera'
		},
		'country': {
			'AU': {
				'country': 'Australia',
				'logos': [ 'australasia', '170', '32' ]
			},
			'CA': {
				'country': 'Canada',
				'logos': [ 'canada', '185', '70' ]
			},
			'CZ': {
				'country': 'Czech Republic',
				'logos': [ 'europe', '148', '32' ]
			},
			'FR': {
				'country': 'France',
				'logos': [ 'europe', '148', '32' ]
			},
			'DE': {
				'country': 'Germany',
				'logos': [ 'europe', '148', '32' ]
			},
			'IE': {
				'country': 'Ireland',
				'logos': [ 'europe', '148', '32' ]
			},
			'IT': {
				'country': 'Italy',
				'logos': [ 'europe', '148', '32' ]
			},
			'MX': {
				'country': 'Mexico',
				'logos': [ 'mexico', '150', '32' ]
			},
			'NZ': {
				'country': 'New Zealand',
				'logos': [ 'australasia', '170', '32' ]
			},
			'UK': {
				'country': 'UK',
				'logos': [ 'europe', '148', '32' ]
			}
		}
		
	},
	
	Self = {
		
		// Init
		'init': function() {
			
			// Add stylesheet
			var d = new Date(),
			css = document.createElement('link');
			css.type = 'text/css';
			css.rel = 'stylesheet';
			css.href = chb_config.filepath + 'css/chb-styles.css';
			document.getElementsByTagName('head')[0].appendChild(css);
			
			// Add orientation class (vert or horz) to widget container
			document.getElementById('CHb-widget').className += ' ' + chb_config.orientation;
			
			// Check if jquery is already loaded
			if (!window.jQuery) {
				
				// Load jquery
				Self.loadScript(chb_config.filepath + 'js/jquery-1.6.2.min.js',function(){
					Self.scriptsLoaded();
				});
			} else {
				
				// Check for version of jQuery and load newer if necessary
				if (parseInt(jQuery.fn.jquery,10) < 1.5) {
					
					// Update jquery
					Self.loadScript(chb_config.filepath + 'js/jquery-1.6.2.min.js',function(){
						Self.scriptsLoaded();
					});
				
				// Everything is ok, just run the scriptsLoaded function
				} else {
					
					Self.scriptsLoaded();
				}
				
			}
			
		},
		
		// Main function that runs after jQuery is loaded
		'scriptsLoaded': function() {
			
			// Load jQuery UI
			Self.loadScript(chb_config.filepath + 'js/jquery-ui-1.8.16.custom.min.js',function() {
				
				// Load jQuery datepicker language file
				Self.loadScript(chb_config.filepath + 'js/jquery.ui.datepicker-' + chb_config.language + '.js',function() {
					
					// Reservation form with localization
					jQuery('#CHb-widget').html('<form action="' + chb_config.bookingurl + '" method="get" style="background-color: ' + chb_config.background_color + '; color: ' + chb_config.text_color + '"><h4 style="border-color: ' + chb_config.divider_color + ';">' + chb_localization[chb_config.language].book + '</h4><fieldset id="CHb-widget-dates"><p class="first" style="border-color: ' + chb_config.divider_color + ';"><label for="checkin">' + chb_localization[chb_config.language].checkin + '</label><br /><input type="text" name="checkin" class="picker" id="checkin" value="" placeholder="dd-mm-yyyy"/></p><p style="border-color: ' + chb_config.divider_color + ';"><label for="checkout">' + chb_localization[chb_config.language].checkout + '</label><br /><input type="text" name="checkout" class="picker" id="checkout" value="" placeholder="dd-mm-yyyy"/></p></fieldset><fieldset id="CHb-widget-details"><p><label for="adults">' + chb_localization[chb_config.language].adults + '</label><br /><select name="adults" id="adults"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option></select></p><p><label for="children">' + chb_localization[chb_config.language].children + '</label><br /><select name="children" id="children"><option value="0">0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option></select></p><p><label for="rooms">' + chb_localization[chb_config.language].rooms + '</label><br /><select name="rooms" id="rooms"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option></select></p><input type="hidden" id="promo" name="promo" value="'+chb_config.promo+'"></fieldset><p id="CHb-widget-submit"><button type="submit" style="background-color: ' + chb_config.button_background_color + '; color: ' + chb_config.button_text_color + '; text-shadow: 0 -1px 0 ' + chb_config.button_background_color + ';">' + chb_localization[chb_config.language].rates + '</button><br/><b>' + chb_localization[chb_config.language].guarantee + '</b></p></form>');
					
					// Build interstitial message and logo string
					var interstitialMsg = chb_localization[chb_config.language].interstitial;
					if (chb_config.language === 'en') { interstitialMsg += chb_localization.country[chb_config.country].country; }
					
					// Add interstitial loader to body and hide
					jQuery('<div id="CHb-interstitial"><div id="CHb-interstitial-content"><p><img src="' + chb_config.filepath + 'img/logos.' + chb_localization.country[chb_config.country].logos[0] + '.png" height="' + chb_localization.country[chb_config.country].logos[2] + '" width="' + chb_localization.country[chb_config.country].logos[1] + '" /></p><p>' + interstitialMsg + '</p><img src="' + chb_config.filepath + 'img/choice-loader.gif" height="32" width="32" /></div></div>')
					.appendTo('body')
					.css({
						'left': -9999,
						'top': -9999
					});
					
					// Bind date picker
					var dates = jQuery('.picker').attr('readonly','readonly').datepicker({
						'minDate': 0,
						'numberOfMonths': 2,
						'showAnim': 'slideDown',
						'dateFormat': 'dd-mm-yy',
						onSelect: function(selectedDate) {
							var option = this.id === 'checkin' ? 'minDate' : 'maxDate',
							instance = jQuery(this).data('datepicker'),
							date = jQuery.datepicker.parseDate(instance.settings.dateFormat || jQuery.datepicker._defaults.dateFormat, selectedDate, instance.settings);
							dates.not(this).datepicker('option', option, date);
						}
					});
					
					// Trigger interstitial popup on form submit
					jQuery('#CHb-widget form').submit(function() {
						Self.BlockUI();
						
						// Show interstitial loader
						jQuery('#CHb-interstitial').css({
							'left': '50%',
							'margin-top': (parseInt(jQuery('#CHb-interstitial').outerHeight(),10)/2) * -1,
							'top': '50%'
						});
						
						// Build url
						var url = jQuery(this).attr('action') + '?checkin=' + jQuery('#checkin').val() + '&checkout=' + jQuery('#checkout').val() + '&adults=' + jQuery('#adults').val() + '&children=' + jQuery('#children').val() + '&rooms=' + jQuery('#rooms').val() + '&promo=' + jQuery('#promo').val();
						
						// Pause load of next window for several seconds
						window.setTimeout(function() {
							window.location = url;
						},2000);
						
						// Block default action of form submit
						return false;
					});
				});
			});
		},
		
		// dynamically load a javascript file
		'loadScript': function(url, callback){

			var script = document.createElement('script');
			script.type = 'text/javascript';

			if (script.readyState) {  //IE
				script.onreadystatechange = function(){
					if (script.readyState === 'loaded' || script.readyState === 'complete') {
						script.onreadystatechange = null;
						callback();
					}
				};
			} else {  //Others
			    script.onload = function(){
			        callback();
			    };
			}

			script.src = url;
			document.getElementsByTagName('head')[0].appendChild(script);
		},
		
		// Function to add event to window.load
		'addLoadEvent': function(func) {
			var oldonload = window.onload;
			if (typeof window.onload !== 'function') {
				window.onload = func;
			} else {
				window.onload = function() {
					if (oldonload) {
						oldonload();
					}
					func();
				};
			}
		},
		
		// Functions to block and unblock the UI
		'BlockUI': function() {
			if (jQuery("#UIBlock").length === 0) {
				jQuery('<div id="UIBlock" />').css({
					background: '#000',
					cursor: 'wait',
					height: '100%',
					left: 0,
					opacity: 0.6,
					position: 'fixed',
					top: 0,
					width: '100%',
					zIndex: 10000
				}).appendTo('body');
				if (jQuery.browser.msie && (jQuery.browser.version < 7)) {
					jQuery('#UIBlock').css({
						position: 'absolute',
						top: jQuery(window).scrollTop()
					});
				}
			}
		},
		'unBlockUI': function() {
			jQuery('#UIBlock').fadeOut(100,function() {
				jQuery(this).remove();
			});
		}
		
	};
	return Self;

})(this, this.document);

CHb.Global.addLoadEvent(CHb.Global.init);

// usage: log('inside coolFunc',this,arguments);
// http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function() {
	log.history = log.history || [];   // store logs to an array for reference
	log.history.push(arguments);
	if(this.console){
		console.log( Array.prototype.slice.call(arguments) );
	}
};
