/* ************************************************************************ */
//checks the zipcode to make sure it matches the correct format
//for the specified country (country must be uppercase)
/* ************************************************************************ */
function checkZipCode(zip, country) {
    var isValid = false;
    switch (country) {
        case "US":
            var rx1 = /^\d{5}(-\d{4})?$/;
            isValid = rx1.test(zip);
            break;
        case "CA":
            //format is L3L 3L3
            var rx2 = /^[A-Z]\d[A-Z]\s\d[A-Z]\d$/;
            isValid = rx2.test(zip);
            break;
        //TODO: add validation for UK here?  
        //otherwise we dont check the format just say its ok :)  
        default:
            isValid = true;
            break;
    }
    return isValid;
}

/* ************************************************************* */
function HashTable()
{
    this.entries = new Array();
    this.indexOf = function(k)
    {
        var idx = -1;
        for (var i = 0; i < this.entries.length; i++)
        {
            if (this.entries[i].key == k)
            {
                idx = i;
                break;
            }
        }
		return idx;
    };
    this.getValue = function(k)
    {
        var myval = null;
        var idx = this.indexOf(k);
        if (idx > -1)
        {
            myval = this.entries[idx].value;
        }
        return myval;
    };
    this.remove = function(i) {
        if (this.entries.length < i) {
            this.entries.splice(i, 1);
        }
    };
    this.removeByKey = function(k) {
        var i = this.indexOf(k);
        if (i > -1) {
            this.remove(i);
        }
    };
    this.replace = function(k, v) {
        var idx = this.indexOf(k);
        if (idx > -1) {
            var tmp = new Object();
            tmp.key = k;
            tmp.value = v;
            this.entries[idx] = tmp;
        }
        else {
            this.add(k, v);
        }
    };
    this.add = function(k, v)
    {
        var tmp = new Object();
        tmp.key = k;
        tmp.value = v;
        return this.entries.push(tmp);
    };
}
/* ************************************************************** */
Date.prototype.isLeapYear = function() {
    var iYear = this.getFullYear();
    return (iYear % 400 == 0 || (iYear % 100 != 0 && iYear % 4 == 0));
};
Date.prototype.getMonthDayCount = function() {
    var mnthAry = null;
    if (this.isLeapYear() == true) {
        mnthAry = new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    }
    else {
        mnthAry = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    }
    return mnthAry[this.getMonth()];
};
/*
	iDayOfWeek is a number from 0-6, 0=Sun and 6=Sat
*/
Date.getWeekday = function(iDayOfWeek, bAbbreviation) {
    var names = new Array("Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat");
    var namesFull = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
    if (iDayOfWeek < names.length) {
        if (bAbbreviation) {
            return names[iDayOfWeek];
        }
        else {
            return namesFull[iDayOfWeek];
        }
    }
    else {
        return null;
    }
};
Date.getMonthName = function(iMonth, bAbbreviation) {
    var names = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
    var namesFull = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    if (iMonth < names.length) {
        if (bAbbreviation) {
            return names[iMonth];
        }
        else {
            return namesFull[iMonth];
        }
    }
    else {
        return null;
    }
};
Number.tryParseInt = function(value) {
    var numOut = new Number(0);
    try {
        var parVal = parseInt(value, 10);
        if (isNaN(parVal) == false) {
            numOut = parVal;
        }
    }
    catch (ex) {
        numOut = new Number(0);
    }
    return numOut;
};

String.prototype.trim = function() {
    var outVal = this.valueOf();
    var whitespace = new Array("\r", "\n", "\t", " ");
    for (var i = 0; i < whitespace.length; i++) {
        var curChar = whitespace[i];
        outVal = outVal.replace(curChar, "");
    }

    return outVal;
};

String.format = function(format) {
    for (var i = 1; i < arguments.length; i++) {
        format = format.replace("{" + (i - 1) + "}", arguments[i]);
    }

    return format;
};

String.formatEx = function(format, obj) {
    for (var prop in obj) {
        var formatItem = "{" + prop + "}";
        if (format.indexOf(formatItem) > -1) {
            var objProperty = obj[prop];
            if (objProperty && objProperty != null) {
                format = format.replace(formatItem, objProperty.toString());
            }
            else {
                format = format.replace(formatItem, "");
            }
        }
    }

    return format;
};

//finds the index of a specified value, 
//returns: -1 of the value is not found otherwise the index in the array
Array.prototype.indexOf = function(value) {
    var ret = -1;
    for (var idx = 0; idx < this.length; idx++) {
        if (this[idx] == value) {
            ret = idx;
            break;
        }
    }
    return ret;
};

/***************** DHTML related Scripts  *********************/
function SetNodeText(nodeElement, text)
{
	if (nodeElement && nodeElement.childNodes && text)
	{
		var new_txt = document.createTextNode(text);
		if (nodeElement.childNodes.length == 0) {
		    nodeElement.appendChild(new_txt);
		}
		else {
		    nodeElement.replaceChild(new_txt, nodeElement.childNodes[0]);
		}
	}
}

//returns the value of an input or the default
//value if the object is null
function GetInputValue(inputElement, defaultval)
{
	try
	{
	    if (!inputElement || inputElement == null) {
	        inputElement.value = defaultval;
	    }
	    else {
	        inputElement.value = value;
	    }
	}
	catch(ex)
	{
		inputElement.value = defaultval;	
	}
}

//set the value of an input to either the object value 
//or to empty if the object is null
function SetInputValue(inputElement, value, defaultval)
{
	try
	{
	    if (value == null) {
	        inputElement.value = defaultval;
	    }
	    else {
	        inputElement.value = value;
	    }
	}
	catch(ex)
	{
		inputElement.value = defaultval;	
	}
}
function SetChildTagsDisabled(theobj, tagname, isdisabled)
{
	if (theobj)
	{
	    var oChildren = theobj.getElementsByTagName(tagname);
	    for (var i = 0; i < oChildren.length; i++) 
	    {
            var child = oChildren[i];
            SetElementDisabled(child, isdisabled);
	    }
	}
}
function SetElementDisabled(theobj, isdisabled)
{
    theobj.disabled = isdisabled;
}

function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent) {
	    while (obj.offsetParent) {
	        curleft += obj.offsetLeft;
	        obj = obj.offsetParent;
	    }
	}
	else if (obj.x) {
	    curleft += obj.x;
	}
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent) {
	    while (obj.offsetParent) {
	        curtop += obj.offsetTop;
	        obj = obj.offsetParent;
	    }
	}
	else if (obj.y) {
	    curtop += obj.y;
	}
	return curtop;
}
function GetTopLeftPosition(element)
{
    var oPos = new Object();
	oPos.x = 0;
    oPos.y = 0;

    while (element.offsetParent)
    {
        oPos.x += element.offsetLeft;
        oPos.y += element.offsetTop;
        element = element.offsetParent;
    }

    if (element.x) {
        oPos.x = element.x;
    }
    if (element.y) {
        oPos.y = element.y;
    }
    return oPos;
}
/* cross browser method to get the 
    exact mouse position.
*/
function getMousePosition(e)
{
	var oPos = new Object();
    oPos.x = 0;
	oPos.y = 0;
	if (e.pageX || e.pageY)
	{
		oPos.x = e.pageX;
		oPos.y = e.pageY;
	}
	else if (e.clientX || e.clientY)
	{
		oPos.x = e.clientX + document.body.scrollLeft;
		oPos.y = e.clientY + document.body.scrollTop;
	}

    return oPos;	
}
function getEventTarget(e)
{
    var targ;
    if (e.target) {
        targ = e.target;
    }
    else if (e.srcElement) {
        targ = e.srcElement;
    }
    // defeat Safari bug
    if (targ.nodeType == 3) {
        targ = targ.parentNode;
    }
    return targ;
}

function getScrollXY() 
{
    //courtesy of www.howtocreate.co.uk
    var scrollObj = new Object();
    scrollObj.x = 0;
    scrollObj.y = 0;
    
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrollObj.y = window.pageYOffset;
    scrollObj.x = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrollObj.y = document.body.scrollTop;
    scrollObj.x = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrollObj.y = document.documentElement.scrollTop;
    scrollObj.x = document.documentElement.scrollLeft;
  }
  return scrollObj;
}

function getAvailableSize()
{
    //courtesy of www.howtocreate.co.uk
    var sizeObj = new Object();
    sizeObj.height = 0;
    sizeObj.width = 0;

  if (typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    sizeObj.width = window.innerWidth;
    sizeObj.height = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    sizeObj.width = document.documentElement.clientWidth;
    sizeObj.height = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    sizeObj.width = document.body.clientWidth;
    sizeObj.height = document.body.clientHeight;
  }
  return sizeObj;
}
/* clearDefaultText is used onfocus on a textbox to clear the default text */
function clearDefaultText(evt, defaultText)
{
    evt = (evt) ? evt : ((window.event) ? window.event : "");
    if (evt)
    {
        var tgt = getEventTarget(evt);
        if (tgt != null && tgt != undefined)
        {
            if (tgt.value == defaultText) {
                tgt.value = "";
            }
        }
    }                            
}
/* restoreDefaultText is used onblur on a textbox to restore the default text */
function restoreDefaultText(evt, defaultText)
{
    evt = (evt) ? evt : ((window.event) ? window.event : "");
    if (evt)
    {
        var tgt = getEventTarget(evt);
        if (tgt != null && tgt != undefined)
        {
            if (tgt.value == "") {
                tgt.value = defaultText;
            }
        }
    }                            
}

// prevents more than "count" characters from being entered into a text box (single or multi-line)
// add this to the textarea  onkeyup="LimitCount(this,1000)" onchange="LimitCount(this,1000)"
function LimitCount(inputEl, count) {
    var maxlength = new Number(count); // Change number to your max length.
    if (inputEl.value.length > maxlength) {
        inputEl.value = inputEl.value.substring(0, maxlength);
    }
}

function setCookie(name, value, exp_y, exp_m, exp_d, path, domain, secure) {
    var cookie_string = name + "=" + escape(value);

    if (exp_y) {
        var expires = new Date(exp_y, exp_m, exp_d);
        cookie_string += "; expires=" + expires.toGMTString();
    }

    if (path)
        cookie_string += "; path=" + escape(path);

    if (domain)
        cookie_string += "; domain=" + escape(domain);

    if (secure)
        cookie_string += "; secure";

    document.cookie = cookie_string;
}

function getSessionCookie(name) {
    var re = new RegExp(name + "=[^;]+", "i");  //construct RE to search for target name/value pair
    if (document.cookie.match(re)) //if cookie found
        return document.cookie.match(re)[0].split("=")[1];  //return its value
    else
        return null;
}

//name is the event without the "on" at the beginning
function addEventHandler(name, handler) {
    //register for the unload event so that any child dialogs can be closed
    if (window.addEventListener) {
        window.addEventListener(name, handler, false);
    }
    else if (window.attachEvent) {
        window.attachEvent("on" + name, handler);
    }
}

//looks up the element heirarchy until it either finds a node with the given tagname or runs out
//of parents
function getParentByTagName(element, tagname) {
    var parent = (element !== null && element.parentNode) ? element.parentNode : null;
    while (parent !== null) {
        if (parent.tagName.toUpperCase() == tagname.toUpperCase()) {
            break;
        }
        else {
            parent = parent.parentNode;
        }
    }
    return parent;
}

