// jwm 2007
// edits: ASP 2008

var is_MSIE = ( document.all ) ? true : false;

// cross-platform DOM element access

function array_diff () {
	// use :  array_diff(['Andrey', 'Shalaenko', 'Hostopia'], ['Shalaenko', 'Hostoipia']);
	// return ['Anmdrey']
 
    var arr_start = arguments[0], retArr = {};
    var key_start = '', i = 1, key = '', next_arr = {};
 
    arr1keys:
    for (key_start in arr_start) {
        for (i = 1; i < arguments.length; i++) {
            next_arr = arguments[i];
            for (key in next_arr) {
                if (next_arr[key] === arr_start[key_start]) {
                    // If it reaches here, it was found in at least one array, so try next value
                    continue arr1keys; 
                }
            }
            retArr[key_start] = arr_start[key_start];
        }
    }
 
    return retArr;
}

//array_map/// ex : array_map(function(a){return a*a*a;}, [1,2,5,15]);
function array_map( callback ) {
    var argc = arguments.length, argv = arguments;
    var j = argv[1].length, i = 0, k = 1, m = 0;
    var tmp = [], tmp_ar = [];

    while (i < j) {
        while (k < argc){
            tmp[m++] = argv[k++][i];
        }

        m = 0;
        k = 1;

        if( callback ){
            if (typeof callback === 'string') {
                callback = this.window[callback];
            }
            tmp_ar[i++] = callback.apply(null, tmp);
        } else{
            tmp_ar[i++] = tmp;
        }

        tmp = [];
    }

    return tmp_ar;
}

//////////////////////////////clean_faxnum///////
function clean_faxnum(faxnum)
{
	var fax = faxnum.replace(/[^0-9]/g, "");
        if (fax.length == 11)
                return fax.substring(1);
        return fax;
}
////////////////////valid character//////////////

function validchar(str, st)
{
		var reg;
                switch (st)
                {
                        case "name" :
                                reg = '[\/~\|\\[\\]\{\}\^%\$\<\>\?\*#=\\\\]';
                                break;
                        case "company" :
                                reg = '[=@\/\|~\<\>\^\\\\\?\{\}\\[\\]]';
                                break;
                        case "phone" :
                        //	  reg = '[^\\w+]|[^\\-\\\\]';
				  reg = '[\<\>,;:\'\"~!@#$%\\^&\\*`()_=\\[\\]\\{\\}\\\\\\/|]';
                               break;
                        case "location" :
                                reg = '[\<\>@~\$%\\\\\/\?\|\^\+\*\{\}\\[\\]=]';
                                break;
                }
		var regobj = new RegExp(reg);	
		return regobj.test(str);
}

////////////////////////////////////////////////


//////search element in array
function in_array(needle, haystack, strict, retIndex) {
    var found = false, key, strict = !!strict, retIndex = !!retIndex;

    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle))
        {
		if (retIndex)		
			found = key;
		else
			found = true;
		
            break;
        }
    }

    return found;
}

function getEl(el)
{
	if ( document.getElementById )
	{
		return( document.getElementById(el) );
	}
	else if (document.all)
	{
		return( document.all[el] );
	}
	
}

function getStyleProperty(el,styleProp)
{
	//var x = document.getElementById(el);
	if (x.currentStyle)
		var y = x.currentStyle[styleProp];
	else if (window.getComputedStyle)
		var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
	return y;
}

// create an array of all elements of a given class
// credit: Dustin Diaz (www.dustindiaz.com)
function getElementsByClass(searchClass,node,tag)
{
	var classElements = new Array();
	if (node == null)
		node = document;
	if (tag == null)
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++)
	{
		if ( pattern.test(els[i].className) )
		{
			classElements[j] = els[i];
			j++;
		}
	}
	return( classElements );
}

// cross-platform document height determination
// Credit: alistapart.com
function getWindowHeight()
{
        var windowHeight = 0;
        if (typeof(window.innerHeight) == 'number') {
                windowHeight = window.innerHeight;
        } else {
                if (document.documentElement && document.documentElement.clientHeight) {
                        windowHeight = document.documentElement.clientHeight;
                } else {
                        if (document.body && document.body.clientHeight) {
                                windowHeight = document.body.clientHeight;
                        }
                }
        }
        return( windowHeight );
}
function getWindowWidth()
{
	return window.innerWidth ? window.innerWidth : document.body.offsetWidth;
}

// centers a popup window based on its height/width vs screen dimensions
function centerPopup(page,name,wide,tall,features)
{
	locinfo = features + ",width=" + wide + ",height=" + tall;
	if (window.screen) {
		posy = ((screen.availHeight - tall) / 2);
		posx = ((screen.availWidth - wide) / 2);
		locinfo += ",left="+posx+",top="+posy;
	}
	popper = window.open(page,name,locinfo);
	if ( popper && popper.opener == null )
		popper.opener = self;
	popper.focus();	
	return( popper );
}

// center an element vertically and horizontally in the view
function centerElement(elementID,container)
{
	el = getEl(elementID);
	if ( !container )
	{
		xpos = Math.floor((getWindowWidth() - el.offsetWidth) / 2);
		ypos = Math.floor((getWindowHeight() - el.offsetHeight) / 2);
	}
	else
	{
		parentEl = getEl(container);
		pTop = parentEl.offsetTop;
		pLeft = parentEl.offsetLeft;
		pWidth = parentEl.offsetWidth;
		pHeight = parentEl.offsetHeight;
		xpos = Math.floor(pLeft + ((pWidth - el.offsetWidth) / 2));
		ypos = Math.floor(pTop + ((pHeight - el.offsetHeight) / 2 ));
	}
	el.style.left = xpos + "px";
	el.style.top = ypos + "px";
}

// populate a SELECT box with an array of data
function populateSelectBox(selBox,data)
{
	selBox.options.length = 0; // clear existing list
	selBox.options.length = data.length;
	for ( i=0; i<data.length; i++ )
	{
		selBox.options[i] = new Option(data[i],data[i]);
	}
	
}

// select a specific option in a SELECT box based on value
function setSelectOption(selBox,value,fuzzy)
{
	selBox.selectedIndex = 0;
	for ( i=0; i<selBox.options.length; i++ )
	{
		if ( selBox.options[i].value == value || ( fuzzy && selBox.options[i].value.indexOf(value) >= 0) )
			selBox.selectedIndex = i;
	}
}

// abstraction for hiding an element
function hideIt(elID)
{
	if ( getEl(elID) )
		(getEl(elID)).style.display = "none";	
}

function showIt(elID)
{
	if ( getEl(elID) )
		(getEl(elID)).style.display = "block";
}

// must use this function to show a hidden TR
function showItTR(elID)
{
	// setting display to an empty string forces the browser to handle it.
	if ( getEl(elID) )
		(getEl(elID)).style.display = ""; // IE && FF BUG fix
}

function isVisible(elID)
{
	el = getEl(elID);
	if ( el && el.style.display != "none" )
		return( true );
	else
		return( false );
}

function toggleDisplay(elID)
{
	if ( isVisible(elID) )
		hideIt(elID);
	else
		showIt(elID);	
}

// this is different than the showIt()/hideIt() combo
// since an invisible element will still occupy screen space
function setVisibility(elID,canSee)
{
	if ( getEl(elID) && canSee )
		(getEl(elID)).style.visibility = "visible";
	else
		(getEl(elID)).style.visibility = "hidden";
}

function setOpacity(elID,val)
{
	elem = getEl(elID)
	if ( elem )
	{
		if ( is_MSIE )
			elem.style.filter = "alpha(opacity=" + (Math.floor(val * 100)) + ")";
		else
			elem.style.opacity = val;
	}
}

// credit: quirksmode.org
function getPosition(elID)
{
	var curleft = curtop = 0;
	var obj = getEl(elID);
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function setPosition(elID,x,y)
{
	elem = getEl(elID);
	if ( elem )
	{
		elem.style.position = "absolute";
		elem.style.left = x + "px";
		elem.style.top = y + "px";
	}
}

// kinda like an indexOf() for arrays
// returns -1 if the search comes up empty
function inArray(needle,haystack)
{
	found = -1;
	for ( x=0; x<haystack.length; x++ )
	{
		if ( needle == haystack[x] )
		{
			found = x;
			break;
		}
	}
	return( found );
}

// breaks a querystring into key/value pairs
// returns an associative array
function parseQueryString(queryString)
{
	var pairs = queryString.split('&');
	var parsed = [];
	
	for ( var i=0; i<pairs.length; i++ )
	{
		var key = pairs[i].slice(0,pairs[i].indexOf('='));
		var val = pairs[i].slice(pairs[i].indexOf('=')+1,pairs[i].length);
		parsed[key] = decodeURIComponent(val);
	}
	
	return( parsed );
}

// return a random number between 0 and max with an option to force ints
function getRandom(max,forceInt)
{
	var num;

	if ( !max )
		max = 10;
	
	if ( forceInt )
		num = Math.floor( Math.random()*max );
	else
		num = Math.random() * max;

	return( num );
}

// remove all the child elements of the given element
function removeAllChildren(elem)
{
	if (!elem)
		return false;

	while (elem.hasChildNodes())
	{
		try {
			elem.removeChild(elem.lastChild);
		} catch (DOMException) { };
	}

	return true;
}

// add a push() method to the Javascript Array object
// (if it doesn't have one already)
if( !Array.prototype.push )
{
	function arrayPush() {
		for( var i=0; i<arguments.length; i++ )
		{
			this[this.length] = arguments[i];
		}
		return this.length;
	}

	Array.prototype.push = array_push;
}

if ('undefined' == typeof String.prototype.ltrim) {
String.prototype.ltrim = function() {
	return this.replace(/^\s+/, '');
}
}

if ('undefined' == typeof String.prototype.rtrim) {
String.prototype.rtrim = function() {
	return this.replace(/\s+$/, '');
}
}

if ('undefined' == typeof String.prototype.trim) {
String.prototype.trim = function() {
	return this.replace(/^\s+/, '').replace(/\s+$/, '');
}
}

// ASP below

// OBJECT
// obtain xml reponse status and error
// data will be any text node only.  Ex: the inserted id
function ajaxResponse(xmldoc)
{
	if (xmldoc)
		this.xmldoc = xmldoc;
	else
		return false;
	this.status = null;
	this.errormsg = null;
	this.errorcode = null;
	this.data = null;

	this.load();
}
ajaxResponse.prototype.load = function()
{
	// status
	var statusContainer = this.xmldoc.getElementsByTagName("status");
	if (statusContainer.length > 0)
		if (statusContainer[0].childNodes.length > 0)
			this.status = statusContainer[0].childNodes[0].nodeValue;

	// error msg and code
	var errormsgContainer = this.xmldoc.getElementsByTagName("errormsg");
	if (errormsgContainer.length > 0)
		if (errormsgContainer[0].childNodes.length > 0)
			this.errormsg = errormsgContainer[0].childNodes[0].nodeValue;
	var errorcodeContainer = this.xmldoc.getElementsByTagName("errorcode");
	if (errorcodeContainer.length > 0)
		if (errorcodeContainer[0].childNodes.length > 0)
			this.errorcode = errorcodeContainer[0].childNodes[0].nodeValue;
	var dataContainer = this.xmldoc.getElementsByTagName("data");
	if (dataContainer.length > 0)
		if (dataContainer[0].childNodes.length > 0)
			this.data = dataContainer[0].childNodes[0].nodeValue;
}
ajaxResponse.prototype.getError = function()
{
	var response = "";
	if (this.errormsg)
		response += this.errormsg;
	if (this.errorcode)
		response += " [" + this.errorcode + "]"
			return response;
}

// VALIDATION
// validate fax number
function valid_faxnumber(faxnum)
{
	faxnum = faxnum.trim();
	var RegExp = /^(1[ \-]?)?[0-9]{3}[ \-]?[0-9]{3}[ \-]?[0-9]{4}$/	;
//	var RegExp = /^(1\-?)?[0-9]{3}\-?[0-9]{3}\-?[0-9]{4}$/;
	if (RegExp.test(faxnum))
		return true;
	return false;
}
function valid_email(str)
{
	// are regular expressions supported?
	var supported = 0;
	if (window.RegExp) {
		var tempStr = "a";
		var tempReg = new RegExp(tempStr);
		if (tempReg.test(tempStr)) supported = 1;
	}
	if (!supported)
		return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);

	var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
	var r2 = new RegExp("^[a-zA-Z0-9\\-\\.\\_]+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,4}|[0-9]{1,4})(\\]?)$");
	return (!r1.test(str) && r2.test(str));
}
function valid_emailcontactname(str)
{
	var RegExp = /["<>`]+/;
	if (RegExp.test(str))
		return false;
	return true;
}

