/** declarations for module level variables used in this script **/
var phonecookiename = "phone";
var phonespanid;

/**
* Sets module level variables and loops through the phone number checking.
*
* cookiename Name of the cookie
* spanid Span id of the span around the telephone number to change
* takes a dynamic array of search engine phone number array pairs 
* to feed into the setPhoneNumber function
*/
function setPhoneNumbers(spanid){
	phonespanid = spanid;
	for(var i=1; i<arguments.length; i=i+2) {
		setPhoneNumber(arguments[i], arguments[i+1]);
	}
}

/**
* Sets phone number from cookie value if it exists.
*
* searchengine Name of the search engine
* phonenumber Value of the phone number to set if the search engine cookie is set
*/
function setPhoneNumber(searchengine, phonenumber){
	if (getCookie(phonecookiename) == searchengine){
		document.getElementById(phonespanid).innerHTML = phonenumber;
	}
}

/**
* 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));
}

/**
* 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(phonecookiename);
if (phone != "default"){
	setCookie(phonecookiename, phone);
}
