/**
 * 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++) {
		if (form.elements[i].name.length>0) {
			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);
	}
}


/**
 * 
 *
 * @param (String) url
 * @param (String) version one of 'urchin', 'ga'
 * @return a URL string
 * @type String
 *
 */
condor.getFixedUpGoogleAnalyticsTrackingUrl = function(url, version) {
	var utmzIndex = url.indexOf('__utmz=');
	var utmzValueIndex = (utmzIndex >= 0) ? utmzIndex + 7 : url.length;
	var preUtmzValueSubstr = url.substring(0, utmzValueIndex);
	var postUtmzValueIndex = utmzValueIndex + url.substring(utmzValueIndex).indexOf('&');
	var postUtmzValueSubstr = (postUtmzValueIndex >= 0) ? url.substring(postUtmzValueIndex) : url.length;
	var utmzValue = url.substring(utmzValueIndex, postUtmzValueIndex);

	switch (version) {
		case 'urchin' :
			// Percent-encode all reserved characters except parentheses (urchin code is "broken" and requires percent-encoding for non-parentheses despite generating (invalid) non-encoded URLs
			var fixedUtmzValue = encodeURIComponent(utmzValue);
			fixedUtmzValue = fixedUtmzValue.replace(/%28/g, '(');
			fixedUtmzValue = fixedUtmzValue.replace(/%29/g, ')');
		case 'ga' :
		default :
			// No fix-up
			var fixedUtmzValue = utmzValue;
	}

	return preUtmzValueSubstr + fixedUtmzValue + postUtmzValueSubstr;
}


/**
 * 
 *
 * @param (Element) form an HTML form
 * @return true if the browser has been automatically redirected to a new URL, false otherwise
 * @type boolean
 *
 */
condor.finalizeTrackingAndGo = function(form) {
	if (window.__utmLinker)	{
		var url = condor.getUrlFromForm(form);
		url = condor.getFixedUpGoogleAnalyticsTrackingUrl(url, 'urchin');
	} else if (window.pageTracker && pageTracker._getLinkerUrl) {
		var url = pageTracker._getLinkerUrl(condor.getUrlFromForm(form));
		url = condor.getFixedUpGoogleAnalyticsTrackingUrl(url, 'ga');
	}
	if (url) {
		url = url.replace(/%2F/g, '/');
		window.location = url;
		return true;
	}
	return false;
}


/**
 * [!!NEEDS UPDATED DESCRIPTION!!] 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
 * @param {boolean} usingBookingFormGateway if false, forms are not redirected to the booking form gateway; otherwise, they are
 * @return true if the tracking resulted in an automatic browser redirect instead of a form submission, false if tracking completed without a redirect, undefined if tracking did not complete successfully
 * @type boolean or undefined
 *
 * Usage:
 * 	<a href="http://reservations.ihotelier.com/istay.cfm?xxx[...]" onfocus="condor.utmLink(this)" onclick="this.onfocus()">
 * OR:
 * 	<a href="http://reservations.ihotelier.com/istay.cfm?xxx[...]" onfocus="condor.utmLink(this, false)" onclick="this.onfocus()">
 * OR:
 * 	<form action="http://reservations.ihotelier.com/istay.cfm" onsubmit="condor.utmLink(this);return true;">
 * OR:
 * 	<form action="http://reservations.ihotelier.com/istay.cfm" onsubmit="return !condor.utmLink(this, false);">
 *
 * For hyperlinks, 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, /*optional*/ usingBookingFormGateway) {
	usingBookingFormGateway = (typeof usingBookingFormGateway == 'undefined' || usingBookingFormGateway==null) ? true : usingBookingFormGateway;
	if (elem && !elem.utmLinked) {
		var redirectInitiated = false;
		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.)
				//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:
				if (usingBookingFormGateway) {
					//Add a field "engineurl" with the value of the original action attribute
					this.addFormFieldsFromQueryString(elem, "engineurl=" + elem.action.replace(/\?/, "&") + "&gav=1urchin");

					//Replace the action attribute
					elem.action = condor.condorBaseHREF + "modules/ihotelier/reservations.gateway.php";
				} else {
					this.addFormFieldsFromQueryString(elem, elem.action);
					redirectInitiated = condor.finalizeTrackingAndGo(elem);
				}

				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;
			}
		}
		return redirectInitiated;
	}
}


/**
 * 
 *
 * @param {Element} elem an HTML Form or A element
 * @param {boolean} usingBookingFormGateway if false, forms are not redirected to the booking form gateway; otherwise, they are
 * @return true if the tracking resulted in an automatic browser redirect instead of a form submission, false if tracking completed without a redirect, undefined if tracking did not complete successfully
 * @type boolean or undefined
 *
 * Usage:
 * 	<a href="http://reservations.ihotelier.com/istay.cfm?xxx[...]" onfocus="condor.trackLink(this)" onclick="this.onfocus()">
 * OR:
 * 	<a href="http://reservations.ihotelier.com/istay.cfm?xxx[...]" onfocus="condor.trackLink(this, false)" onclick="this.onfocus()">
 * OR:
 *  <a href="http://booking.ihotelier.com/istay/istay.jsp?xxx[...]" onfocus="condor.trackLink(this)" onclick="this.onfocus()">
 * OR:
 *  <a href="http://booking.ihotelier.com/istay/istay.jsp?xxx[...]" onfocus="condor.trackLink(this, false)" onclick="this.onfocus()">
 * OR:
 * 	<form action="http://reservations.ihotelier.com/istay.cfm" onsubmit="condor.trackLink(this);return true;">
 * OR:
 * 	<form action="http://reservations.ihotelier.com/istay.cfm" onsubmit="condor.trackLink(this, false);return true;">
 * OR:
 * 	<form action="http://booking.ihotelier.com/istay/istay.jsp" onsubmit="condor.trackLink(this);return true;">
 * OR:
 * 	<form action="http://booking.ihotelier.com/istay/istay.jsp" onsubmit="return !condor.trackLink(this, false);">
 *
 * For hyperlinks, 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.trackLink = function(elem, usingBookingFormGateway) {
	usingBookingFormGateway = (typeof usingBookingFormGateway == 'undefined' || usingBookingFormGateway==null) ? true : usingBookingFormGateway;
	if (window.__utmLinker)
	{
		return condor.utmLink(elem, usingBookingFormGateway);
	}
	if (!window.pageTracker || !pageTracker._getLinkerUrl) {
		return;
	}
	if (elem && !elem.trackLinked) {
		var redirectInitiated = false;
		if (elem.submit) { //Element is a form
			//Take the _utm parameters from the tracking URL and create hidden input fields instead:
			if (usingBookingFormGateway) {
				//Get the tracking URL formed by adding the _utm parameters to the end of the action attribute
				var trackingUrl = pageTracker._getLinkerUrl(elem.action);

				//Add a field "engineurl" with the value of the original action attribute
				this.addFormFieldsFromQueryString(elem, "engineurl=" + trackingUrl.replace(/\?/, "&") + "&gav=2ga");

				//Replace the action attribute
				elem.action = condor.condorBaseHREF + "modules/ihotelier/reservations.gateway.php";
			} else {
				redirectInitiated = condor.finalizeTrackingAndGo(elem);
			}
		} else if (elem.href) { //Element is a hyperlink
			elem.href = pageTracker._getLinkerUrl(elem.href);
		}
		elem.trackLinked = true;
		return redirectInitiated;
	}
}


/**
 * 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.  Modifies the
 * onsubmit events so that they return false if the tracking resulted in an automatic browser redirect instead
 * of a form submission, else true if there was no original onsubmit event, else the return value of the
 * original onsubmit event.
 *
 * @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.
 * @param {boolean} usingBookingFormGateway if false, forms are not redirected to the booking form gateway; otherwise, they are
 *
 * USAGE:
 * 		<a class="tracking-link"...
 * OR
 *		<form class="tracking-form"...
 * 
 */
condor.addTracking = function(method, /*optional*/ hook, usingBookingFormGateway) {
	if (condor.trackingAdded) {
		return;
	}
	condor.trackingAdded = true;

	usingBookingFormGateway = (typeof usingBookingFormGateway == 'undefined' || usingBookingFormGateway==null) ? true : usingBookingFormGateway;

	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, usingBookingFormGateway);
				return this.onfocusOrig ? this.onfocusOrig(this) : true;
			}
			if (elem.onclick) {
				elem.onclickOrig = elem.onclick;
			}
			elem.onclick = function() {
				condor.trackLink(this, usingBookingFormGateway);
				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() {
				var returnValue = (this.onsubmitOrig) ? this.onsubmitOrig(this) : true;
				return (condor.trackLink(this, usingBookingFormGateway)) ? false : returnValue;
			}
		}
	}
}


// Is this function actually used anywhere??
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(){}
	console.warn = function(){}
	console.log = function(){}
}
