/** declarations for module level variables used in this script **/
var _phoneParameterName = "phone";
var _tagName, _parentElement;

/**
* Gets the value of the given parameter from the query string
*
* name The parameter name
*
* Return value The value of the parameter
*/
function getParameter(parameterName) 
{
    var querystring = location.search.substring(1, location.search.length);
    var args = querystring.split("&");
    var toReturn = "default";

    for (var i = 0; i < args.length; i++) {
        var pair = args[i].split("=");
        currentName = unescape(pair[0]);
        temp = unescape(pair[1]).split("!");
        currentValue = temp[0];
        if (parameterName == currentName) {
            toReturn = currentValue;
        }
    }
    return toReturn;
}

/**
* Sets a Cookie with the given name and value.
*
* name Name of the cookie
* value Value of the cookie
* [expires] Expiration date of the cookie (default: end of current session)
*/
function setCookie(name, value, expires)
{
	var defaultExpireDate = new Date();
	defaultExpireDate.setFullYear(defaultExpireDate.getFullYear()+1,defaultExpireDate.getMonth(),defaultExpireDate.getDate());

	document.cookie = name + "=" + escape(value) + "; expires=" + defaultExpireDate.toGMTString() + "; path=/";
}

/**
* Gets the value of the specified cookie.
*
* name Name of the desired cookie.
*
* Returns a string containing value of specified cookie,
* or null if cookie does not exist.
*/
function getCookie(name)
{
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1)
	{
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	}
	else
	{
		begin += 2;
	}
	var end = document.cookie.indexOf(";", begin);
	if (end == -1)
	{
		end = dc.length;
	}
	return unescape(dc.substring(begin + prefix.length, end));
}

/**
* Gets an array of elements in the html document based on class names.
*
* oElm Parent element of all the desired cookie.
* strTagName The Tag name the class is associated with or * for all tags.
* oClassNames A string or an array of class names to be returned.
*
* Returns an array of elements.
*/
function getElementsByClassName(oElm, strTagName, oClassNames){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	var arrRegExpClassNames = new Array();
	if(typeof oClassNames == "object"){
		for(var i=0; i<oClassNames.length; i++){
			arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)"));
		}
	}
	else{
		arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)"));
	}
	var oElement;
	var bMatchesAll;
	for(var j=0; j<arrElements.length; j++){
		oElement = arrElements[j];
		bMatchesAll = true;
		for(var k=0; k<arrRegExpClassNames.length; k++){
			if(!arrRegExpClassNames[k].test(oElement.className)){
				bMatchesAll = false;
				break;
			}
		}
		if(bMatchesAll){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}

/**
* Loops through the phone numbers checking if a corresponding cookie value is set
* and if it is it then calls the setNumber function.
*
* className Either a string or array of class names of elements that contain phone numbers to change
* takes a dynamic array of search engine phone number array triplets 
* to feed into the setNumber function.
*/
function changeNumber(className){
	for(var i=1; i<arguments.length; i=i+3) {
		if (getCookie(_phoneParameterName) == arguments[i])
			setNumber(className, arguments[i+1], arguments[i+2]);
	}
}

/**
* Sets phone numbers.
*
* className Either a string or array of class names of elements that contain phone numbers to change
* phoneNumber Value of the phone number to set
* src The source of the phone number image to set or a blank string
*/
function setNumber(className, phoneNumber, src)
{
	var a=getElementsByClassName(_parentElement, _tagName, className);
	for (var i = 0; i < a.length; i++)
	{
		a[i].title = 'Telephone: ' + phoneNumber;
		a[i].alt = 'Telephone: ' + phoneNumber;
		
		if (src != '')
		{
			a[i].src = arguments[2];
			a[i].style.backgroundImage = "url(" + arguments[2] + ")";
		}
		else
		{
			// for maximum compatibility always set everything
			a[i].innerHTML = phoneNumber;
			a[i].innerText = phoneNumber;
		}
	}
}

/**
* Sets a cookie value based on a value from the querystring.
*
* don't set a cookie if no value was in the querystring.
*
*/
var phone = getParameter(_phoneParameterName);
if (phone != "default"){
	setCookie(_phoneParameterName, phone);
}

/**
* Sets up an event that fires a function either 
* on DOMContentLoaded for browsers that support it 
* or when the page has loaded for other browsers.
*
*/
var Behaviour = {
	
	start : function(){
		Behaviour.addLoadEvent(function(){
			fn_onload();
		});
	},

	addLoadEvent : function(func){
		//Enable application of Behaviours when just the DOM is loaded 
		//  (by Weston Ruter <http://linguiste.org>).
		//   See Dean Edwards's blog: http://dean.edwards.name/weblog/2005/09/busted/
		//Only Gecko supports DOMContentLoaded
		if(document.addEventListener && navigator.userAgent.indexOf('Gecko/') != -1){
			document.addEventListener("DOMContentLoaded", function(){func()}, false);
		}
		//Only MSIE defers execution of scripts until DOM loaded
		else if(/MSIE/.test(navigator.userAgent) && !window.opera){
		
			document.write('<script id="__init_script" defer="true" src="//[]"></script>');

			var deferScript = document.getElementById('__init_script');
			if (deferScript) {
				deferScript.onreadystatechange = function() {
					if (this.readyState == 'complete') {
						fn_onload();
					}
				};

				/* check whether script has already completed */
				deferScript.onreadystatechange();

				/* clear reference to prevent leaks in IE */
				deferScript = null;
			}
		}
		//fall back to using onload (original Behaviour code)
		else {
			var oldonload = window.onload;
			
			if (typeof window.onload != 'function') {
				window.onload = func;
			} else {
				window.onload = function() {
					oldonload();
					func();
				}
			}
		}
	}
}

Behaviour.start();

/**
* This is the function that fires when the page has loaded.
*
* it contains the logic for changing the telephone number appropriately.
*
* it also contains some code that can be left or optionally tailored
* to make the script more efficient.
*
*/



function fn_onload () {

	// for performance these variable should be changed 
	// from their defaults to more specific values
	_tagName="*";
	_parentElement=document.body;



	/*
	Html changes are required to set a phone number dynamically. Example html 
	for an image: <img src="/standard_number.gif" class="phoneimage" /> 
	If the querystring has a item phone=google this image will be changed to 
	<img src="/google_number.gif" class="phoneimage" />
	
	Example html for text <span class="phonenumber">0870 850 7200</span>
	If the querystring has a item phone=google this number will be changed to 
	<span class="phonenumber">0870 850 7270</span>
	
	In both cases the image or text will remain changed for 30 days unless a yahoo 
	ppc link is clicked during that 30 day period. Then the number would then be changed to
	<img src="/yahoo_number.gif" class="phoneimage" /> for an image or
	<span class="phonenumber">0870 850 7271</span> for text, for 30 days.
		
	Below as an example we are changing some text and an image. If only one of 
	these is on the page then only one function call is required and the unused 
	function will need to be deleted. 

	Two query string parameters have been used for the page of google and yahoo. 
	You can add more or less depending on your needs by adding triplets to the functions arguments. 
	*/


	changeNumber("phoneSpan",

			"google", "+44(0)207 616 9185", "",
			"alaskacruise", "+44(0)207 616 9969", "",
			"rockymountaineer", "+44(0)207 616 9198", "",
			"motorhomes", "+44(0)207 616 9912", "",
			"escorted", "+44(0)207 616 9908", "",
			"yahoo", "+44(0)207 616 9179", "",
			"msn", "+44(0)207 616 9182", "",
			"ski", "+44(0)207 616 9186", "");
}




