/**
 * This file is for utilities which are not related to the CMS,  but which are more or less specific to TravelCLICK sites
 */

function id(id) {
	return document.getElementById(id);
}

//Mostly for iframe calendar
function setInputValue(inputId, newValue) {
    id(inputId).value = newValue;
}

if (!window.condor) {
	condor = new Object();
}

function toggleDisplay(objectId) {
	if (document.getElementById(objectId).style.display == 'block') {
		document.getElementById(objectId).style.display = 'none';
	} else {
		document.getElementById(objectId).style.display = 'block';
	}
}


function condor_simulateClick(elem) {
	if (typeof(elem) == "string") {
		elem = document.getElementById(elem);
	}
	if ((elem) && (elem.onclick)) {
		elem.onclick();
	}
}


/**
 * Generates a popup window.
 * 
 * @param (String) url the URL of the page to be loaded
 * @param (String) windowTitle the title of the popup
 * @param {int} width the width of the popup, a positive integer, or 0 if browser default required, or null for 400px
 * @param {int} height the height of the popup, a positive integer, or 0 if browser default required, or null for 600px
 * @param {String} windowChromeParams a whitespace-free, comma-separated list of window features (http://developer.mozilla.org/en/docs/DOM:window.open)
 * @param {String} windowPosition a String of the form 'left=x,top=y' specifying the origin of the popup with respect to the operating system desktop.
 * @return a reference to the new Window object
 * @type Window
 */
condor.popPage = function(url, windowTitle, /*optional*/ width, /*optional*/ height, /*optional*/ windowChromeParams, /*optional*/ windowPosition) {
	windowTitle = windowTitle ? windowTitle : "Popup_Window";
	windowTitle = windowTitle.replace(/[^a-zA-Z0-9_]/, "_"); //IE is picky about titles...
	windowChromeParams = windowChromeParams || 'menubar=yes,toolbar=no,location=yes,directories=no,status=yes,scrollbars=yes,resizable=yes';
	width = (width===0) ? '' : ',width=' + (width || 400);
	height = (height===0) ? '' : ',height=' + (height || 600);
	windowPosition = (windowPosition) ? ',' + windowPosition : '';   
	return window.open(url, windowTitle, windowChromeParams + width + height + windowPosition);
} 


/**
 * Generates a URL string representing the form, its target and its values.
 * 
 * @param {Form} form an HTML Form object
 * @return a URL string of the form "http://domain.com/myform.php?value1=2&value2=jorge"
 * @type String
 * 
 * Usage:
 * 	<form [...] onsubmit="window.open(condorjs.getUrlFromForm(this)); return false">
 */
condor.getUrlFromForm = function(form) {
	var parameters = new Array();
	for (var i = 0; i < form.elements.length; i++) {
		parameters.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
	}
	var qs = parameters.join("&");
	var url = form.getAttribute("action");
	var parts = url.split(/\?/);
	url = parts[0]; // The script name part
	if (parts[1]) { // ?appended parameters
		qs = qs + "&" + parts[1]; // Move existing query string parameters to the end
	}
	return (url + "?" + qs);
}


/**
 * Appends hidden INPUT elements to a FORM element corresponding to the name--value pairs of a query string (or the query string part of a URL).
 *
 * @param {Form} form an HTML Form element
 * @param {String} urlOrQs a URL or a query string
 */
condor.addFormFieldsFromQueryString = function(form, urlOrQs) {
	//Extract the part of urlOrQs after the '?' if there is one; otherwise we assume that the whole string is of the form name=value&name2=value2[...]
	var qs = urlOrQs.split(/\?/)[1] ? urlOrQs.split(/\?/)[1] : urlOrQs;
	var fields = qs.split(/&/);
	for (var i = 0; i < fields.length; i++) {
		var pair = fields[i].split(/=/);
		var fieldName = pair.shift();
		var fieldValue = (pair.length > 0) ? decodeURIComponent(pair.join("=")) : "";

		var input = document.createElement("input");
		input.setAttribute("type", "hidden");
		input.setAttribute("name", fieldName);
		input.setAttribute("value", fieldValue);
				
		form.appendChild(input);
	}
}


/**
 * Adds hidden elements to a FORM or modifies the href of an A to mimic the behaviour of Google Analytics' __utmLinkPost function.
 * On submission of the FORM or activation of the A, the GET data or query string is the same as would be generated by __utmLinkPost,
 * however our approach is more flexible because it does not require JavaScript function-wrapping of hrefs, thereby permitting a
 * link to be opened in another browser instance, and it does not disturb other functionality that may be associated with a form.
 *
 * @param {Element} elem an HTML Form or A element
 *
 * Usage:
 * 	<a href="http://reservations.ihotelier.com/istay.cfm?xxx[...]" onfocus="condor.utmLink(this)" onclick="this.onfocus()">
 * OR:
 * 	<form action="http://reservations.ihotelier.com/istay.cfm" onfocus="condorjs.utmLink(this)" onclick="this.onfocus()">
 * Putting it in the onfocus event ensures that it still works on <aux-button>+click and on {right-click}+<context-menu-open>;
 * However, as of Nov 2007, (only) Opera 9 does not trigger onfocus when a link is mouse-clicked, hence we add an onclick handler too.
 * Alas neither of these events are triggered in Opera 9 on {right-click}+<context-menu-open>.
 */
condor.utmLink = function(elem) {
	if (elem && !elem.utmLinked) {
		if (elem.submit) { //Element is a form
			if (window.__utmLinkPost) { //(Google's function for passing cookies from one site to another via a form post.)
				var action = elem.action;

				//Add the _utm parameters to the end of the action attribute
				__utmLinkPost(elem);

				//Take the _utm parameters from the action attribute and create hidden input fields instead
				//Add a field "engineurl" with the value of the original action attribute
				this.addFormFieldsFromQueryString(elem, "engineurl=" + elem.action.replace(/\?/, "&") + "&gav=1urchin");
				
				//Restore the action attribute
				elem.action = condor.condorBaseHREF + "modules/ihotelier/reservations.gateway.php";

				elem.utmLinked = true;
			}
		} else if (elem.href) { //Element is a hyperlink
			if (window.__utmLinker) { //(Google's function for passing cookies from one site to another via normal hyperlink.)
				/**
				 * urchin.js defines two global variables:
				 * 	_udl - a reference to document.location
				 * 	_ubd - a reference to document
				 * __utmLinker modifies the value of _udl, thus redirecting the browser to a new document.
				 * We prevent this by breaking its reference, and we then capture its value.
				 */

				//Break the reference to document.location
				_udl = new Array();

				//Add the __utm parameters to the end of the href attribute
				__utmLinker(elem.href);

				//Capture the new value of _udl.href
				elem.href = _udl.href;

				//Restore the original value of _udl
				_udl = _ubd.location;

				elem.utmLinked = true;
			}
		}
	}
}


condor.trackLink = function(elem) {
	if (window.__utmLinker)
	{
		condor.utmLink(elem);
		return;
	}
	if (!window.pageTracker)
		return;
	if (elem && !elem.trackLinked) {
		if (elem.submit) { //Element is a form
			var trackingUrl = pageTracker._getLinkerUrl(elem.action);
			this.addFormFieldsFromQueryString(elem, "engineurl=" + trackingUrl.replace(/\?/, "&") + "&gav=2ga");
			elem.action = condor.condorBaseHREF + "modules/ihotelier/reservations.gateway.php";
			elem.trackLinked = true;			
		} else if (elem.href) { //Element is a hyperlink
			elem.href =  pageTracker._getLinkerUrl(elem.href);
			elem.trackLinked = true;
		}
	}
}


/**
 * Looks for hyperlinks (A-tags) and forms -- either based on the value of their href and action attributes
 * or on their class name -- and attaches tracking to the onclick, onfocus and submit events.
 *
 * @param {String} method the value 'by_class' or 'by_url' specifying the method by which to filter links that should be tracked.
 *                         Default is by_class.
 * @param {String} hook either the class name prefix (for the by_class method; default is "tracking", which matches the class names
 *                       "tracking-link" for A tags and "tracking-form" for FORM tags) or the domain name (for the by_url method;
 *                       default is "ihotelier.com") that determines which elements should have tracking attached.
 *
 * USAGE:
 * 		<a class="tracking-link"...
 * OR
 *		<form class="tracking-form"...
 * 
 */
condor.addTracking = function(method, /*optional*/ hook) {
	if (!method)
	{
		method = 'by_class';
	}
	if (method == 'by_class' && !hook)
	{
		hook = 'tracking';
	}
	else if (method == 'by_url' && !hook)
	{
		hook = 'ihotelier.com'
	}

	var hyperlinks = document.getElementsByTagName('a');
	for (var i = 0; i < hyperlinks.length; i++)
	{
		var elem = hyperlinks[i];
		if ( ( (method == 'by_class') && hasClass(elem, hook + '-link') ) ||
		     ( (method == 'by_url') && elem.href.match(new RegExp(hook, 'i')) )
		   )
		{
			if (elem.onfocus)
				elem.onfocusOrig = elem.onfocus;
			elem.onfocus = function()
			{
				condor.trackLink(this);
				return this.onfocusOrig ? this.onfocusOrig(this) : true;
			}
			if (elem.onclick)
				elem.onclickOrig = elem.onclick;
			elem.onclick = function()
			{
				condor.trackLink(this);
				return this.onclickOrig ? this.onclickOrig(this) : true;
			}
		}
	}

	var forms = document.getElementsByTagName('form');
	for (var i = 0; i < forms.length; i++)
	{
		var elem = forms[i];
		if ( ( (method == 'by_class') && hasClass(elem, hook + '-form') ) ||
		     ( (method == 'by_url') && elem.action.match(new RegExp(hook, 'i')) )
		   )
		{
			if (elem.onsubmit)
				elem.onsubmitOrig = elem.onsubmit;
			elem.onsubmit = function()
			{
				try {
					condor.trackLink(this);
				}
				catch(e) {
				}
				return this.onsubmitOrig ? this.onsubmitOrig(this) : true;
			}
		}
	}
}


condor.passUTMCookies = function(url) {
	var iframe = document.createElement("iframe");
	iframe.style.display = "none";
	document.body.appendChild(iframe);
	_udl = new Array();
	__utmLinker(url);
	iframe.src = _udl.href;
	_udl = _ubd.location;
}


// Dummy console object for IE not to throw an error
if (!window.console) {
	console = new Object();
	console.error = function(){}
}
