function addLoadEvent(func) {
	var ssArray = "";
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}


function addResizeEvent(func) {
	var oldresize = window.onresize;
	if (typeof window.onresize != 'function') {
		window.onresize= func;
	} else {
		window.onresize = function() {
			oldresize();
			func();
		}
	}
}

//Function that takes element ID and pixel offset and changes height of elment.

function e(id) {
      return document.getElementById(id);
}

function autoResizeElement(id,bottomOffset) {
      var topOffset = 0;
      for (var elem = document.getElementById(id);
       elem != null;
       elem = elem.offsetParent) {
            topOffset += elem.offsetTop;
      }
      var windowHeight = getViewportHeight();
      var height = windowHeight - topOffset - bottomOffset;
      if (height >= 0) {
            document.getElementById(id).style.height = height + "px";
      }
}

function getViewportHeight() {
      if (window.self && self.innerHeight) {
            return self.innerHeight;
      }
      if (document.documentElement && document.documentElement.clientHeight) {
            return document.documentElement.clientHeight;
      }
      return 0;
}

function getViewportWidth() {
      if (window.self && self.innerWidth) {
            return self.innerWidth;
      }
      if ( (document.documentElement && document.documentElement.clientWidth) || (document.body && document.body.clientWidth) ) {
          if(document.documentElement.clientWidth > 0)   {
            return document.documentElement.clientWidth;
          }
          else if (document.body.clientWidth > 0) {
            return document.body.clientWidth
          }
      }
      return 0;
}


function getDocumentHeight()    {
    if (document.body && document.body.offsetHeight) {
        return document.body.offsetHeight;
      }
    if (document.body.document && document.body.document.height) {
        return document.body.document.height;
    }
    return 0;
}

function getDocumentWidth()    {
    if (document.body && document.body.offsetWidth) {
            return document.body.offsetWidth;
      }
    if (document.body.document && document.body.document.width) {
        return document.body.document.width;
    }
    return 0;
}

// Function that takes a String URL and sets the parent's location to the URL
function goToPage(obj) {
	if (obj.value != null && obj.value != "void" && obj.value != "") {
		parent.location =obj.value;
	}
}

// Generic pop up window function the window features are passed from the parent page
function openBrWindow(theURL,winName,features) {
	var winObj = window.open(theURL,winName,features);
	if (!winObj.opener) winObj.opener = self;
	winObj.focus();
}

// Function that takes in a name, reads that name from a cookie, and returns the value of that name.
function readCookie(name) {
	var cookies = document.cookie;
	var start = cookies.indexOf(name + "=");
	if (start == -1) return null;
	start = cookies.indexOf("=", start) + 1;
	var end = cookies.indexOf(";", start);
	if (end == -1) end = cookies.length;
	var value = unescape(cookies.substring(start, end));
	return value;
}

// Function that takes a name/value pair and sets them to a cookie
/*
   name - name of the cookie
   value - value of the cookie
   [expires] - expiration date of the cookie in days (defaults to end of current session)
   [path] - path for which the cookie is valid (defaults to path of calling document)
   [secure] - Boolean value indicating if the cookie transmission requires a secure transmission
   [domain] - domain for which the cookie is valid (defaults to domain of calling document)
   * an argument defaults when it is assigned null as a placeholder
   * a null placeholder is not required for trailing omitted arguments
*/
function setCookie(name, value, expires, path, secure, domain) {
	var today = new Date();
	today.setTime(today.getTime());
	
	if (expires) { expires = expires * 1000 * 60 * 60 * 24; }
	var expires_date = new Date( today.getTime() + (expires) );

	var curCookie = name + "=" + escape(value) +
	(( expires ) ? "; expires=" + expires_date.toGMTString() : "") + 
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
	document.cookie = curCookie;
}

// Function that deletes a cookie
/*
   name - name of the cookie
   [path] - path of the cookie (must be same as path used to create cookie)
   [domain] - domain of the cookie (must be same as domain used to create cookie)
   * path and domain default if assigned null or omitted if no explicit argument proceeds
*/
function deleteCookie(name, path, domain) {
	if (readCookie(name)) {
		document.cookie = name + "=" +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		"; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}

// Function to switch current display of id between "block" and "none"
function switchDisplay(elementID, swapType) {
	var element = document.getElementById(elementID);
	if (swapType == 'show'){
		element.style.display = 'block';
	} else {
		element.style.display = 'none';
	}
}

// Function to toggle an elements display
// elementID is the name of the element you want to toggle.
// currentDisplay is a boolean that's passed in and represents the elements current display type.
function toggleDisplay(elementID, currentDisplay) {
	var element = document.getElementById(elementID);
	if (currentDisplay){
		element.style.display = "none";
		currentDisplay = false;
	} else {
		element.style.display = "block";
		currentDisplay = true;
	}
	return currentDisplay;
}

var currentClass;
function classSwitcher(el,stateClass) {
	var element = (typeof el == "object") ? el : document.getElementById(el);
	if(currentClass==undefined || currentClass==stateClass) currentClass = element.className;

	if(element.className == currentClass || element.className == "") {
		element.className = stateClass;
	} else {
		element.className = currentClass;
	}
}
// Function to determine if a field is null
function isNull(fieldValue) {
	if (fieldValue == null) {fieldValue=''};
		return (fieldValue.length == 0);	
}

// Function to determine if two fields match each other
function isMatch(field1,field2) {
	if ((field1 != null && field1 != '') && ( field2 != null && field2 != ''))
		return (field1 == field2);
}

// Function to parse the querystring into useable variables
var parsequery_args = new Object();
function parsequery(qs) {
	if (qs.length > 2) {
		var query = qs.substring(1); // get query string (without initial "?")
		var pairs = query.split("&")  //break at ampersand into pairs
		var re = /\+/g; //the unescape() function does not remove +
		for (var i = 0; i < pairs.length; i++) {
			var pos = pairs[i].indexOf('=');  //look for "name=value"
			if (pos == -1) continue;      //if not found skip
			var argname = pairs[i].substring(0,pos);  //extract the name
			var value = pairs[i].substring(pos + 1);  //extract the value
			parsequery_args[argname] = unescape(value.replace(re," "));  //store as a property
		}
	}
}

// Function that takes a string (s) and 1 character (bag) to strip from the string.
// the function returns the string without the 1 character (bag) in it.
function stripCharsInBag (s, bag){
	var i;
	var returnString = "";
	for (i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}

// Function that gives you the screen x and screen y, even after the user has scrolled
var scrOfX = 0, scrOfY = 0;
function getScrollXY() {
	if( typeof( window.pageYOffset ) == 'number' ) {
	//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
	//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
	//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}
	return [ scrOfX, scrOfY ];
}

// Fixes the IE background-image hover bug
try {
    document.execCommand( "BackgroundImageCache", false, true );
} catch( e ) { };


/**
 * Selects all checkboxes under the given parent node.  Set deep to true
 * to recursively set.
 *
 * @param {Node} parentNode     node under which checkboxes can be found
 * @param {boolean} checked     true to set checkboxes, false to clear (Default: true)
 * @param {boolean} deep        true to recursively set children deeper than one level (Default: true)
 */
function setCheckboxes(parentNode, checked, deep) {
    if(parentNode == null)  return;

    // defaults
    checked = (checked == null) ? true : checked;
    deep = (deep == null) ? true : deep;

    // loop through and select boxes
    for(var i=0; i < parentNode.childNodes.length; i++) {
        var node = parentNode.childNodes[i];

        if(deep) {
            // recursively set deeper child nodes
            if(node.hasChildNodes()) {
                setCheckboxes(node, checked, deep);
            }
        }

        // set checkbox
        if(node.nodeType == 1 && node.getAttribute("type") == "checkbox") {
            node.checked = checked;
        }
    }
}

/**
 * Asynchronously fills a select dropdown with properties given a list of
 * property IDs via an XHR call.
 *
 * @param {String} propSelect       select element containing property list
 * @param {String} propIds          comma delimited list of property ids to populate with
 * @param {String} selectedPropId   optional id of pre-selected property when the list is built
 * @param {function} onFailure      optional reference to a failure callback function
 * @param {function} onSuccess      optional reference to a success callback function
 */
function fillPropertySelect(propSelect, propIds, selectedPropId, onFailure, onSuccess) {
    // clear current select options
    while(propSelect.hasChildNodes()) {
        propSelect.removeChild(propSelect.childNodes[0]);
    }

    // remove spaces between properties in property list
    propIds = propIds.replace(/,\s+/g, ',');
    var url = "/whotels/property/propertyInfoAjax.html?propertyIDs=" + propIds;
    var callback = {
        success: _fillPropertySelectSuccess,
        failure: onFailure,
        argument: {'propSelect':propSelect, 'selectedPropId':selectedPropId, 'onSuccess':onSuccess}
    }

    // make the call
    var request = YAHOO.util.Connect.asyncRequest('GET', url, callback);
}

// success handler for fillPropertySelect XHR call
function _fillPropertySelectSuccess(o) {
    var i,j;

    // get prop select element
    var propSelect = o.argument['propSelect'];
    if(propSelect == null) return;

    // get selected property id
    var selectedPropId = o.argument['selectedPropId'];

    // process response
    var yuiJson = YAHOO.lang.JSON;
    var result = yuiJson.parse(o.responseText);
    var propMap = result.data;

    var propIds = propMap['propIds'];
    var propNames = propMap['propNames'];

    // sort alphabetically by property names
    var sortedPropNames = new Array();
    for(i=0; i<propNames.length; i++) {
        sortedPropNames.push(propNames[i]);
    }
    sortedPropNames.sort();

    // sort ids according to sorted property names
    var sortedPropIds = new Array();
    for(i=0; i<propIds.length; i++) {
        for(j=0; j<propNames.length;j++) {
            if(propNames[j] == sortedPropNames[i]) {
                sortedPropIds.push(propIds[j]);
                break;
            }
        }
    }
    // create options for each property
    var option;

    // create a list of prop id => prop name mappings sorted by name
    for(i=0; i<sortedPropIds.length; i++) {
        option = document.createElement('option');
        option.setAttribute("value", sortedPropIds[i]);

        if(selectedPropId == sortedPropIds[i]) {
            option.setAttribute("selected", "selected");
        }
        
        option.appendChild(document.createTextNode(sortedPropNames[i]));
        propSelect.appendChild(option);
    }

    // call callback method
    if(o.argument['onSuccess']) {
        o.argument['onSuccess']();
    }
}

// function to determine the offsetLeft of an element that is passed in
function getElementOffsetLeft (element) {
    var leftOffset = element.offsetLeft;
    while ((element = element.offsetParent) != null){
        leftOffset  += element.offsetLeft;
    }
    var viewPort = document.documentElement.clientWidth;
    return leftOffset;
}
// function to determine the offsetTop of an element that is passed in
function getElementOffsetTop (element) {
    var topOffset = element.offsetTop;
    while ((element = element.offsetParent) != null){
        topOffset +=element.offsetTop;
    }
    var docHeight = document.documentElement.scrollTop;
    var viewPort = document.documentElement.clientHeight;
    return topOffset;
}

//function to keep check box checked even if clicked
function keepChecked(formElement)  {
    
    if(!formElement.checked)    {
        formElement.checked = true;    
    }
}