// ----------------
// Global Vars
// ----------------
var formsSubmitted = Array();

// ----------------------------------------------------------------------------
// Extensions to the prototype framework (inspired by jQuery 1.2.3)
// ----------------------------------------------------------------------------
(function(){
	var newMethods = {
		visible: function(element) {
			return $(element).getStyle('display') != 'none';
		},
		show: function(element){
			$(element).setStyle({ display: $(element).oldblock || '' });
			if ($(element).getStyle('display') == 'none') {
				var newElement = document.createElement($(element).tagName);
				$$('body').first().insert({bottom: newElement});
				$(element).setStyle({ display: $(newElement).getStyle('display')});
				$(newElement).remove();
				if ($(element).getStyle('display') == 'none') $(element).setStyle({ display: 'block'});
			}
			return element;
		},
		hide: function(element){
			$(element).oldblock = $(element).oldblock || $(element).getStyle("display");
			$(element).setStyle({display: 'none'});
			return element;
		}
	};
	Element.addMethods(newMethods);
})();

// ----------------------------------------------------------------------------
// Use a stub object to prevent errors in IE from using console.log() etc.
// ----------------------------------------------------------------------------

(function(){
	// Prevent stray debugging calls from erroring when firebug isn't present
	if (!('console' in window) || !('firebug' in console)) {
		var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
		window.console = {};
		for (var i=0; i<names.length; ++i) {
			window.console[names[i]] = function() {}
		}
	}
})();

// ----------------------------------------------------------------------------
// Show/hide an element, if you also pass it a reference to the clicked link it
// will try and rewrite it from "Show blah" to "Hide blah". Call like so:
// <a href="#" onclick="return toggle('whatever',this);">Show whatever</a>
// ----------------------------------------------------------------------------

function toggleElement(id, link) {
	if (link && link.tagName == 'A') {
		var link = $(link);
		var text = link.innerHTML;
		if (text.match(/(Show|Hide)/)) {
			if ($(id).visible()) {
				link.update(text.replace(/Hide/,'Show'));
			} else {
				link.update(text.replace(/Show/,'Hide'));
			}
		}
		link.blur();
	}
	$(id).toggle();
	return false;
}

// ----------------------------------------------------------------------------
// Onload initialisation functions for page-specific functionality
// ----------------------------------------------------------------------------

function initTabs() {
	if ($('tabs') && $('tabset')) {
		if (TLTabSet) new TLTabSet();
	}
}

// ----------------------------------------------------------------------------
// Attach pop-up calendars to any date input fields
// ----------------------------------------------------------------------------

document.observe('dom:loaded', applyDateSelect);
document.observe('overlay:loaded', applyDateSelect);

function applyDateSelect(){
	$$('.dateField').each(function(el){
		if (el.tagName != 'INPUT') el = el.down('input');
		if (el) {
			el.observe('click',showDateSelect);
			el.setAttribute('autocomplete','off');
			// initDefaultValue(el,'DD/MM/YYYY');
		}
	});
}

function showDateSelect(e) {
	if ($('calendarOverlay')) return;
	e.stop();
	var input = e.element();
	var cal = new TLCalendar(input);
	document.observe('click', function(e){ e.stop(); cal.hide(); });
}

// ----------------------------------------------------------------------------
// Use unobtrusive Javascript as an accessible replacement for target="_blank"
// to optionally open links marked with rel="external" in a new browser window
// ----------------------------------------------------------------------------

document.observe('dom:loaded', function(){
	$$('a').each(function(link){
		if (link.rel == 'external') {
			link.observe('click',function(e){
				window.open(e.findElement('a').href, '_blank');
				e.stop();
			});
		}
	});
});

// ----------------------------------------------------------------------------
// Text input default values
// ----------------------------------------------------------------------------

function initDefaultValue(id, defaultValue) {
	var el = $(id);

	if (!el) return;

	if (el.value == '' || el.value == defaultValue) {
		el.value = defaultValue;
		el.addClassName('defaultText');
	}

	function fieldFocus(e) {
		var self = e.element();
		if (self.getValue() == defaultValue) {
			self.value = '';
			self.removeClassName('defaultText');
		}
	}

	function fieldBlur(e) {
		var self = e.element();
		if (self.getValue() == '') {
			self.value = defaultValue;
			self.addClassName('defaultText');
		}
	}

	el.observe('focus', fieldFocus);
	el.observe('blur', fieldBlur);

	var form = $(el.form);
	if (form) {
		// If the form is submitted, and this field's value is still set to the default,
		// unset it so that the default value doesn't get processed by the back-end code.
		form.observe('submit', function(){
			if (el.value == defaultValue) el.value = '';
		});
	}
}

// ----------------------------------------------------------------------------
// Hide any elements with a class of 'jsHide' on page load
// ----------------------------------------------------------------------------

(function(){
	// See: http://yuiblog.com/blog/2007/06/07/style/
	function addCss(cssCode) {
		var styleElement = document.createElement("style");
		styleElement.type = "text/css";
		if (styleElement.styleSheet) {
			styleElement.styleSheet.cssText = cssCode;
		} else {
			styleElement.appendChild(document.createTextNode(cssCode));
		}
		document.getElementsByTagName("head")[0].appendChild(styleElement);
	}
	addCss(".jsHide { display:none; }");
})();

// ----------------------------------------------------------------------------
// Toggle Booking Details - Used on payment details page
// ----------------------------------------------------------------------------
function toggleBookDetails() {
	if (this.value == 'View details') {
		$('bookDetails').show();
		$('bookDetailsSummary').hide();
		this.value = 'Hide details';
	} else {
		$('bookDetails').hide();
		$('bookDetailsSummary').show();
		this.value = 'View details';
	}
}
document.observe('dom:loaded', function(){
	if($('bookDetailsBtn')) $('bookDetailsBtn').observe('click', toggleBookDetails);
});

//Used for the amend search overlay in search and book
document.observe('dom:loaded', function(){
	$$('#amendSearchLink').each(function(el){
		$(el).href='/search_and_book/index.php?action=amendsearch';
	});
});

// ----------------------------------------------------------------------------
// Toggle Travel Agent Details - Used on group booking availability form
// ----------------------------------------------------------------------------
function toggleTravelAgentDetails() {
	if ($('travelAgentChkBox').checked) {
		$('travelAgentContainer').show();
	} else {
		$('travelAgentContainer').hide();
	}
}
document.observe('dom:loaded', function(){
	if ($('travelAgentChkBox')) {
		$('travelAgentChkBox').observe('click', toggleTravelAgentDetails);
		// Run once on page load
		toggleTravelAgentDetails();
	}
});

// ----------------------------------------------------------------------------
// Toggle SMS Conf. Message Details - Used on room extras and room modification
// ----------------------------------------------------------------------------
function toggleSMSConfirmationDetails() {
	var rows = $$('.jssendSmsRow');
	if (!rows) return;
	rows.each(function(row){
		var inputs = row.down('.jsSMSNumberFields');
		if (!inputs) return;
		// If it's a single room
		var radios = row.select('input[type=radio]');
		if (radios) {
			radios.each(function(radio){
				radio.observe('click',function(){
					if (this.id != 'sendSms_0_off') {
						inputs.show();
						$$('.smsWarning').each(function(el){el.show();});
					} else {
						inputs.hide();
						$$('.smsWarning').each(function(el){el.hide();});
					}
				});
			});
		}
		// If there are multiple rooms
		var boxes = row.select('input[type=checkbox]');
		if (boxes) {
			boxes.each(function(box){
				box.observe('click',function(){
					if (this.checked) {
						inputs.show();
					} else {
						inputs.hide();
					}
					var showWarning = false;
					for (var i=0; i<4; ++i) {
						var smsCheckboxes = $('bookMultiRoomForm')['sendSms_'+i];
						if ($(smsCheckboxes) && $(smsCheckboxes)[1].checked) { showWarning = true; }
					}
					if (showWarning) {
						$$('.smsWarning').each(function(el){el.show();});
					} else {
						$$('.smsWarning').each(function(el){el.hide();});
					}
				});
			});
		}
	});
}
document.observe('dom:loaded',toggleSMSConfirmationDetails);

// ----------------------------------------------------------------------------
// Submit Once - Prevents users from submiting the same form multiple times
// ----------------------------------------------------------------------------
document.observe('dom:loaded', function(){
	$$('form.jsSubmitOnce').each(function(form){
		if (form.id) {
			formsSubmitted[form.id] = false;
			form.observe('submit',function(e){
				if (formsSubmitted[this.id]) {
					if(e) e.stop();
					return false;
				} else {
					formsSubmitted[this.id] = true;
					return true;
				}
			});
		}
	});
});

// ----------------------------------------------------------------------------
// Initialise sidebar help box so that answers to questions load in via-ajax
// ----------------------------------------------------------------------------

function initSidebarHelp(){
	var helpQ = $('helpQuestions');
	var helpA = $('helpAnswer');
	if (helpQ && helpA) {
		helpQ.select('.helpQuestion a').each(function(link){
			link.observe('click',function(e){
				var id = this.href.split('#q')[1];
				new Ajax.Request('/help/',{
					parameters:{'id':id},
					onComplete:function(transport){
						helpA.down('#helpAnswerContent').update(transport.responseText);
						helpQ.hide();
						helpA.show();
					}
				});
				e.stop();
			});
		});
		var back = helpA.down('.backLink');
		if (back) {
			back.observe('click',function(e){
				helpA.hide();
				helpQ.show();
				e.stop();
			});
		}
	}
}
document.observe('dom:loaded', initSidebarHelp);

// ----------------------------------------------------------------------------
// Generic window opening function:
// ----------------------------------------------------------------------------
// Last argument is a series of on/off flags to toggle the window properties,
// i.e. '000011' gets you a resizable, scrollable window with no other chrome
// ----------------------------------------------------------------------------
// Keep track of open windows in an associative array, keyed on window name:
// ----------------------------------------------------------------------------

var wins = {};

function openWindow(name, location, w,h, center, props) {

	window.name = 'main';

	if(typeof(wins[name]) != "undefined") wins[name].close();

	p = 'width='+w+',height='+h;

	if(center) {
		screenw = screen.availWidth;
		screenh = screen.availHeight-25;

		if(w>screenw) w = screenw;
		if(h>screenh) h = screenh;
		x = screenw/2 - w/2;
		y = screenh/2 - h/2;

		p += ',left='+x+',top='+y;
	}

	if(parseInt(props.charAt(0))) p += ',menubar';
	if(parseInt(props.charAt(1))) p += ',toolbar';
	if(parseInt(props.charAt(2))) p += ',location';
	if(parseInt(props.charAt(3))) p += ',status';
	if(parseInt(props.charAt(4))) p += ',scrollbars';
	if(parseInt(props.charAt(5))) p += ',resizable';

	wins[name] = window.open(location, name, p);
	wins[name].focus();

	return false;
}

function openMastercardSecurecode() { return openWindow('MasterCardSecureCode', 'http://www.mastercardbusiness.com/mcbiz/index.jsp?template=/orphans&content=securecodepopup', 555,500, false, '000011'); }
function openVerifiedByVisa() 		{ return openWindow('VerifiedByVisa', '/security/verified_by_visa.php', 555,400, false, '000011'); }


// ---------------------------------------------------------------
// SmartAgent help links and form
// ---------------------------------------------------------------

function openSmartAgent(question) {
	var url = "http://travelodge.smartagent.co.uk/";
	if (question && question != 'Help' && question != 'Ask Andrea now.') url += "?question=" + unescape(question);

	openWindow('TravelodgeSmartAgent', url, 543,546, true, '000000');
}

function initSmartAgentActions() {
	$$('.jsSmartAgent').each(function(el){
		switch (el.tagName.toLowerCase()) {

			case 'form':
				var input = el.down('input');
				if (input) {
					el.observe('submit',function(e){
						e.stop();
						openSmartAgent(input.getValue());
					});
				}
				break;

			case 'a':
				el.observe('click',function(e){
					e.stop(); e.element().blur();

					// Pass through the link text as the question if it ends in a question mark.
					// Otherwise it's probably "Help" or "Ask Andrea now" or something similar.
					var q = el.innerHTML;
					if (!/\?$/.test(q)) q = '';

					openSmartAgent(q);
				});
				break;

		}
	});
}

document.observe('dom:loaded',function(){
	initSmartAgentActions();
});


// ---------------------------------------------------------------
// Attach auto complete drop down to location/hotel lookup fields
// ---------------------------------------------------------------
document.observe('dom:loaded',function(){
	$$('.hotelList').each(function(el){
		el.observe('focus',function(e){
			actb(this,e,hotelArray);
		});
	});
});
