var caretPos = [];
var lastSelectedTextObj;
function insertText(textObj, insertedText, noSpace) {
	var nav4 = window.Event ? true : false;
	if(!textObj) return;
	var oldval = textObj.value;
	var space = ' ';
	if (noSpace) space='';
	if (nav4) { // NN 4.x
		textObj.value = oldval + (oldval.length ? space : '') + insertedText;
	} else { // IE
		if (textObj.createTextRange && caretPos[textObj.name] && caretPos[textObj.name].offsetLeft!=1) {
			finalText =  space + insertedText + space;
			caretPos[textObj.name].text = caretPos[textObj.name].text.charAt(caretPos[textObj.name].text.length - 1) == ' ' ? finalText + ' ' : finalText;
		} else {
			textObj.value  = oldval + (oldval.length ? space : '') + insertedText;
		}
	}
}

function storeCaret (textObj) {
    if(event.ctrlKey || event.keyCode==17) return false;//Ctrl
	if (textObj.createTextRange) {
		caretPos[textObj.name] = document.selection.createRange().duplicate();
		lastSelectedTextObj=textObj;
	}
    return true;
 }

function getFormElementSelectedIDs(theForm, name) {
	var selectedIDs = [];
	if (theForm.elements[name] || theForm.elements[name + '[]']) {
		var elem = theForm.elements[name] ? theForm.elements[name] : theForm.elements[name + '[]'];
		if (elem.type) {
			switch (elem.type) {
			case 'select-one':
				if (elem.options.selectedIndex >= 0) selectedIDs[selectedIDs.length] = elem.options[elem.options.selectedIndex].value;
				break;
			case 'select-multiple':
				for (var i=0; i<elem.options.length; i++) if (elem.options[i].selected) selectedIDs[selectedIDs.length] = elem.options[i].value;
				break;
			case 'radio':
				if (elem.checked) selectedIDs[selectedIDs.length] = elem.value;
				break;
			}
			return selectedIDs;
		} else if (elem.length) {
			for (var i=0; i<elem.length; i++) if (elem[i].checked) selectedIDs[selectedIDs.length] = elem[i].value;
			return selectedIDs;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

function disableFormElement(theForm, name, flag) {
	for (var i=0; i<theForm.elements.length; i++) {
		if (!name || theForm.elements[i].name == name || theForm.elements[i].name == name + '[]') {
			if(theForm.elements[i].type!='hidden') theForm.elements[i].disabled = flag;
		}
	}
}

function lib_contains(arr, value) {
    if(typeof(value) == 'undefined') return false;
    var len = arr.length,vallen, i, j;
    if (value.sort) {
        vallen = value.length;
        for (i=0; i<len; i++) {
            for (j=0; j<vallen; j++) if (arr[i] == value[j]) return true;
        }
    } else {
        for (i=0; i<len; i++) if (arr[i] == value) return true;
    }
    return false;
}

function lib_getKeys(arr) {
	var keys = [];
	for (var key in arr) {
        if (typeof(arr[key]) != 'function') {
            keys.push(key);
        }
    }
	return keys;
}

var mBrowser = {
    Version: function() {
        var version = 999;
        if (navigator.appVersion.indexOf('MSIE') != -1)
        version = parseFloat(navigator.appVersion.split('MSIE')[1]);
        return version; 
    }
}

function hideShowCovered(tobj, hideMethod) {
    var brVersion = mBrowser.Version();
    if( brVersion == 7 || brVersion == 8) return;
    var hideMethod = hideMethod ? hideMethod : 0; // 0 - w/o delay,  1 - wait browser
    var res=0;
	function getVisib(obj){
		var value = obj.style.visibility;
		if (!value) {
			if (document.defaultView && typeof (document.defaultView.getComputedStyle) == "function") { // Gecko, W3C
                is_khtml = /Konqueror|Safari|KHTML/i.test(navigator.userAgent);
				if (!is_khtml)
					value = document.defaultView.
						getComputedStyle(obj, "").getPropertyValue("visibility");
				else
					value = '';
			} else if (obj.currentStyle) { // IE
				value = obj.currentStyle.visibility;
			} else
				value = '';
		}
		return value;
	};
    function showHideElements() {
        var l = toUpdate.length;
        for(var i=0; i<l; i++) {
            toUpdate[i].obj.style.visibility = toUpdate[i].visibility;
        }
    };
    var tags = new Array("applet", "iframe", "select");
	var el = tobj;

	var p = getAbsolutePos(el);
	var EX1 = p.x;
	var EX2 = el.offsetWidth + EX1;
	var EY1 = p.y;
	var EY2 = el.offsetHeight + EY1;
    var tLen = tags.length;
	var toUpdate = [];
    for (var k = tLen; k > 0; ) {
		var ar = document.getElementsByTagName(tags[--k]);
		var cc = null;
        var arLen = ar.length;
		for (var i = arLen; i > 0;) {
			cc = ar[--i];

			p = getAbsolutePos(cc);
			var CX1 = p.x;
			var CX2 = cc.offsetWidth + CX1;
			var CY1 = p.y;
			var CY2 = cc.offsetHeight + CY1;
			if (this.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) {
				if (!cc.__msh_save_visibility) {
					cc.__msh_save_visibility = getVisib(cc);
				}
                toUpdate.push({'obj': cc, 'visibility': cc.__msh_save_visibility});
			} else {
				if (!cc.__msh_save_visibility) {
					cc.__msh_save_visibility = getVisib(cc);
				}
                toUpdate.push({'obj': cc, 'visibility': 'hidden'});
                res=1;
			}
		}
	}
    if(hideMethod) window.setTimeout(showHideElements, 0);
    else showHideElements();
    return res;
};

function getAbsolutePos(el) {
	var SL = 0, ST = 0;
    var is_div = (el.tagName && el.tagName == 'DIV') ? true : false;
	if (is_div && el.scrollLeft)
		SL = el.scrollLeft;
	if (is_div && el.scrollTop)
		ST = el.scrollTop;
	var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
	if (el.offsetParent) {
		var tmp = getAbsolutePos(el.offsetParent);
		r.x += tmp.x;
		r.y += tmp.y;
	}
	return r;
};

function checkPasswordStrong(pval) {
    theForm=document.forms[0];
    pval=pval.trim();
    if(theForm && theForm.CLIENT_USER_NAME && theForm.CLIENT_USER_NAME.value.trim()==pval) {
        alert('Password should not be the same as the userID.');
        return true;
    }
    if(theForm && theForm.VOL_USER_ID && theForm.VOL_USER_ID.value.trim()==pval) {
        alert('Password should not be the same as the userID.');
        return true;
    }
    if(pval.length<8) {
        alert('Password should be at least 8 characters long.');
        return true;
    }
    newstr=pval.replace(/\d/i , '');
    if(newstr.length==pval.length) {
        alert('Password should contain at least one number.');
        return true;
    }
    newstr=pval.replace(/[A-Za-z]/i , '');
    if(newstr.length==pval.length) {
        alert('Password should contain at least one letter.');
        return true;
    }
}
var bounds_cache = [];
function lib_resetBounds() {
    bounds_cache = [];
}
var isIE = document.all ? true : false;
function lib_getBounds(element, allowCache, isRecursion, mode) {
    if(!isIE || (mode && mode == 2)) {
        var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
        scrollLeft = (scrollLeft ? scrollLeft : document.body.scrollLeft);
        scrollTop = (scrollTop ? scrollTop : document.body.scrollTop);
        var bounds = element.getBoundingClientRect();
        return {left:   bounds.left+scrollLeft,
                top:    bounds.top+scrollTop,
                width:  element.offsetWidth,
                height: element.offsetHeight};
    }
    var left = element.offsetLeft;
    var top = element.offsetTop;
    for (var parent = element.offsetParent; parent; parent = parent.offsetParent) {
        if(allowCache && parent.id) {
            var b = bounds_cache[parent.id];
            if(!b) {
                b = lib_getBounds(parent, true, true);
                bounds_cache[parent.id] =  b;
            }
            left += b.left-parent.scrollLeft;
            top += b.top-parent.scrollTop;
            break;
        } else {
            left += parent.offsetLeft - parent.scrollLeft;
            top += parent.offsetTop - parent.scrollTop;
        }
    }
    if(!isRecursion) {
        left += document.body.scrollLeft;
        top += document.body.scrollTop;
    }
    var height2 = element.offsetHeight || element.scrollHeight;
    var width2 = element.offsetWidth || element.scrollWidth;
    return {left: left, top: top, width: width2, height: height2};
}

function lib_getObjectParams(obj, mode, coord) {
    var params = {'id': obj.id,
                  'x': coord.left,
                  'y': coord.top,
                  'h': obj.clientHeight,
                  'w': obj.clientWidth,
                  'maxX':0,
                  'maxY':0,
                  'mode':mode,
                  'className' : obj.className,
                  'attributes': obj.attributes};
    params.maxX = params.x + params.w;
    params.maxY = params.y + params.h;
    return params;
}

var lib_ajaxPrevRequest = false;
var lib_ajaxCurrRequest = false;
var lib_ajaxRequestSent = false;
var lib_ajaxLastParams = [];

function lib_sendAjaxRequest(act, params, ajaxFillObjId, ajaxResponseFunction, ajaxShowLoadingObjId, _ajaxForm) {
    if(typeof(JsHttpRequest)!='function') {
        alert('Error in library.js: AJAX library is not loaded.');
        return;
    }
    if(!act) {
        alert('Error in library.js: AJAX action is not set.');
        return;
    }
    if(typeof(ajaxResponseFunction) != 'function') {
        alert('Error in library.js: AJAX response function '+ajaxResponseFunction+' is not exist.');
        return;
    }
    if(typeof(document.getElementById(ajaxFillObjId)) != 'object') {
        alert('Error in library.js: AJAX fill object '+ajaxFillObjId+' is not set.'+typeof(ajaxFillObjId));
        return;
    }

    if(lib_ajaxRequestSent) { // another request in progress
        lib_ajaxLastParams = [];
        lib_ajaxLastParams['act'] = act;
        lib_ajaxLastParams['params'] = params;
        lib_ajaxLastParams['ajaxFillObjId'] = ajaxFillObjId;
        lib_ajaxLastParams['ajaxResponseFunction'] = ajaxResponseFunction;
        lib_ajaxLastParams['ajaxShowLoadingObjId'] = ajaxShowLoadingObjId;
        lib_ajaxLastParams['_ajaxForm'] = _ajaxForm;
        return;
    }
    lib_ajaxLastParams = false;
    lib_ajaxRequestSent = true;
    if(!_ajaxForm) _ajaxForm = document.forms['ajaxForm'] && typeof(document.forms['ajaxForm'])=='object' ? document.forms['ajaxForm'] : document.forms[0];
    if(lib_ajaxCurrRequest) lib_ajaxPrevRequest = lib_ajaxCurrRequest;
    lib_ajaxCurrRequest = act;

    lib_showAjaxLoadingIndicator(ajaxShowLoadingObjId, ajaxFillObjId);

    JsHttpRequest.query(
            'backend.php',
            {'q': _ajaxForm, '_backendAct' : act, 'ajaxFillObjId':ajaxFillObjId, 'params': params},
            function (content, errors) {
                if( errors ) {
                    if(typeof(profile_requestSent) != 'undefined') profile_requestSent = false;
                    alert(errors);
                } else if( content ) {
                    ajaxResponseFunction(content, ajaxFillObjId);
                }
                lib_ajaxRequestSent = false;

                lib_hideAjaxLoadingIndicator();

                if(lib_ajaxLastParams) { // make last not handled request
                    lib_sendAjaxRequest(lib_ajaxLastParams['act'], lib_ajaxLastParams['params'], lib_ajaxLastParams['ajaxFillObjId'], lib_ajaxLastParams['ajaxResponseFunction'], lib_ajaxLastParams['ajaxShowLoadingObjId'], lib_ajaxLastParams['_ajaxForm']);
                }
            },
            true
        );
}

function lib_getAjaxLoadingIndicatorID() {
    return 'ajaxLoadingIndicator';
}

function lib_getAjaxLoadingHtml(obj, showBar) {
    var coord = lib_getBounds(obj);
    var indicatorHtml = typeof(COMMON_URL) != 'undefined' ? '<img border=\"0\" src=\"'+COMMON_URL+'images/loading'+(showBar?'-bar':'')+'.gif\"/>' : '';
    var newdivinnerHTML = '<table border=\"0\" width=\"100%\" height=\"100%\" cellpadding=\"0\" cellspacing=\"0\"><tr><td '+(showBar? '': 'bgcolor="white"')+' align=\"center\" width=\"100%\" height=\"100%\">' + indicatorHtml + '</td></tr></table>';
    var addStyle = showBar ? 'background-color: #5a5a5a; opacity: 0.25; filter: alpha(opacity=25);' : 'background-color: white;';
    newdivinnerHTML = '<div id=\"'+lib_getAjaxLoadingIndicatorID()+'\" style=\"'+addStyle+'z-index:13000; position: absolute; left: '+coord.left+'px; top: '+coord.top+'px; width: '+coord.width+'px; height: '+coord.height+'px;\">'+newdivinnerHTML+'</div>';
    return newdivinnerHTML;
}

function lib_showAjaxLoadingIndicator(ajaxShowLoadingObjId, ajaxFillObjId, showBar) {
    var _ajaxShowLoadingObj;
    if(ajaxShowLoadingObjId) {
        _ajaxShowLoadingObj=document.getElementById(ajaxShowLoadingObjId);
    }
    if(typeof(_ajaxShowLoadingObj) != 'object') {
        ajaxShowLoadingObjId = ajaxFillObjId;
        _ajaxShowLoadingObj=document.getElementById(ajaxShowLoadingObjId);
    }
    if(_ajaxShowLoadingObj && typeof(_ajaxShowLoadingObj)=='object') {
        var indObj = document.getElementById(lib_getAjaxLoadingIndicatorID());
        if(!indObj) {
            indObj = document.createElement('div');
            try {
                document.getElementById(ajaxShowLoadingObjId).appendChild(indObj);
            } catch(e) {
                document.body.appendChild(indObj);
            }
        }
        try {
            if(indObj) indObj.outerHTML = lib_getAjaxLoadingHtml(_ajaxShowLoadingObj, showBar);
        } catch(e) {}
    }
}

function lib_hideAjaxLoadingIndicator() {
    var indObj = document.getElementById(lib_getAjaxLoadingIndicatorID());
    if(indObj && typeof(indObj)=='object') indObj.style.display = 'none';
}

function lib_getElementsByAttribute(oElm, strTagName, strAttrName ) {
    var arrElements = (strTagName == '*' && document.all)? document.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    var oElement;
    var len = arrElements.length;
    for(var i=0; i<len; i++){
        oElement = arrElements[i];
        lib_putObjectCache(oElement);
        if(oElement.attributes[strAttrName]) {
            arrReturnElements.push(oElement);
        }
    }
    return (arrReturnElements)
}
function lib_prepareEreg(str) {
    var reg;
    if( str != '*' ) {
        str = str.replace(/\-/g, '\\-');
        reg = new RegExp('(^|\\s)' + str + '(\\s|$)');
    } else {
        reg = new RegExp('.*');
    }
    return reg;
}
function lib_getElementsByClassName(parentElm, strTagName, strClassName, strClassName2) {
    var arrElements = (strTagName == '*' && document.all)? document.all : parentElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    var eregs = new Array();
    var len, elen, oElement, i, j;
    if(typeof(strClassName) == 'string') {
        eregs.push(lib_prepareEreg(strClassName));
        if(strClassName2) eregs.push(lib_prepareEreg(strClassName2));
    } else {
        len = strClassName.length;
        for(var i=0; i<len; i++) {
            eregs.push(lib_prepareEreg(strClassName[i]));
        }
    }
    len = arrElements.length;
    elen = eregs.length;
    for(var i=0; i<len; i++){
        oElement = arrElements[i];
        lib_putObjectCache(oElement);
        for(var j=0; j<elen; j++) {
            if( eregs[j].test(oElement.className) ){
                arrReturnElements.push(oElement);
                break;
            }
        }
    }
    return arrReturnElements.slice()
}

var lib_switchingInProgress=false;
function lib_switchTab(togglerObj, execAfterFinish) {
    if(lib_switchingInProgress) return;
    lib_switchingInProgress=true;
    closeIt=togglerObj.style.display!='none' ? 1 : 0;
    c = lib_getBounds(togglerObj);
    togglerObj.style.height = c.height;
    togglerObj.style.overflowY = 'hidden';
    onFinish = function(){
        if(closeIt) {
            togglerObj.style.display='none';
        }
        togglerObj.style.height='auto';
        togglerObj.style.overflowY='visible';
        lib_switchingInProgress=false;
        if(execAfterFinish) {
            window.setTimeout( execAfterFinish, 200);
//            eval(execAfterFinish);
        }
    };
    if(closeIt) {
        lib_expand(togglerObj, 1, -(c.height/5), 0, onFinish);
    } else {
        togglerObj.style.display='';
        c = lib_getBounds(togglerObj);
        lib_expand(togglerObj, c.height, (c.height/5), 0, onFinish);
    }
    return closeIt;//true=tab is closed
}

function lib_expand(obj, minMax, step, timeout, onFinish, iterations) {
    timeout = timeout ? timeout : 50;
    h = parseInt(obj.style.height) > 1 ? parseInt(obj.style.height) : 1;
    iterations = iterations ? iterations : 0;
    iterations++;
    if( (step > 0 && h >= minMax) || (step < 0 && h <= minMax) || (h+step <=0) || iterations >=20 ) {
        obj.style.height = minMax;
        onFinish();
        return;
    }
    try {
        h += step;
        if(h<1) h=1
        obj.style.height = h;
        if(step > 15 && minMax-h>step && minMax-h<step*2) {
            step = step/3;
        } else if(step < -15 && h-minMax>-step && h-minMax<-step*2) {
            step = step/3;
        }
        window.setTimeout( function(){lib_expand(obj, minMax, step, timeout, onFinish, iterations)}, timeout);
    } catch(e) {
        obj.style.height = minMax;
        onFinish();
    }
}

function lib_alignTables(table1, table2, mode) {
    if(!table1 || !table2 ||
       !table1.rows[0] || !table2.rows[0] ||
       !table1.rows[0].cells.length || 
       ( mode!=2 && table1.rows[0].cells.length != table2.rows[0].cells.length)) return;
    table1.aligned = false;
    startFrom = mode == 2 ? 0 : 1;
    var len = table1.rows[0].cells.length;
    if(mode != 2) {
        for(var i = startFrom; i< len-startFrom; i++) {
            table1.rows[0].cells[i].style.width='auto';
            table1.rows[0].cells[i].width=table1.rows[0].cells[i].attributes['defaultWidth'].value;
            if( table1.rows[0].cells[i].childNodes[0]) table1.rows[0].cells[i].childNodes[0].style.width = 'auto';
        }
    }
    var shouldBe = [];
    var t2Len = table2.rows.length;
    for(var i = startFrom; i< len; i++) {
        if(!table2.rows[0].cells[i]) continue;
        var additionalWidth = 0;
        if(mode != 2) {
            additionalWidth = i ? -1 : 0;
            if(i == len-1) additionalWidth -= 19;
        } else {
            if(i == 0) {
                additionalWidth = -3;
            } else if(i == len-startFrom-2) {
                additionalWidth = 0;
            } else {
                additionalWidth = -1;
            }
        }
        var oldW = parseInt(table1.rows[0].cells[i].offsetWidth);
        var newW = oldW;
        if(mode == 2) {
            newW = oldW*1.15;
            table1.rows[0].cells[i].style.width = newW+'px';
        }
        shouldBe[i] = newW + additionalWidth;
        if(mode!=2) shouldBe[i] = shouldBe[i] < 120 ? 120 : shouldBe[i];
        to = mode!=2 ? 1 : t2Len;
        var w = shouldBe[i]-1;
        if(w > 0) {
            for(var j=0; j<to; j++) {
                if( table2.rows[j].cells[i].childNodes[0] && table2.rows[j].cells[i].childNodes[0].tagName == 'DIV' ) table2.rows[j].cells[i].childNodes[0].style.width = w;
            }
            table2.rows[0].cells[i].style.width = (w+1)+'px';
        } else {
            return -1;
        }
        shouldBe[i] = parseInt(table2.rows[0].cells[i].offsetWidth);
    }
    if(mode!=2) {
        for(var i = startFrom; i< len-startFrom; i++) {
             if( table1.rows[0].cells[i].childNodes[0] ) {
                table1.rows[0].cells[i].style.width = shouldBe[i];
                table1.rows[0].cells[i].childNodes[0].style.width = shouldBe[i] -1;
             }
        }
    }
    table1.aligned = true;
    return 0;
}

// get css class object via className
function lib_findStyleRule(styleName) {
    var ereg = lib_prepareEreg(styleName);
    var rules = [], ret = false;
    if( document.styleSheets && document.styleSheets.length && document.styleSheets[0] && document.styleSheets[0].cssRules ) { // opera or firefox
        var styleSheetsLength = document.styleSheets.length;
        for (var i = 0; i < styleSheetsLength; i++) {
            var col = 0;
            var cssRulesLength = document.styleSheets[0].cssRules.length;
            if (cssRulesLength > 0 ) {
                col = cssRulesLength; // Opera 7
            } else {
                for (var kkk in document.styleSheets[0].cssRules) col++; // firefox 2
            }
            for (var j = 0; j < col; j++) {
                if (document.styleSheets[i].cssRules[j] && lib_checkCssRule(ereg, document.styleSheets[i].cssRules[j].selectorText)) {
                    rules.push(document.styleSheets[i].cssRules[j].selectorText);
                    if(styleName != '*') {
                        return document.styleSheets[i].cssRules[j];
                    }
                }
            }
        }
    } else { // IE
        var styleSheetsLength = document.styleSheets.length;
        for (var i = 0; i < styleSheetsLength; i++) {
            var styleSheetsRuleLength = document.styleSheets(i).rules.length;
            for (var j = 0; j < styleSheetsRuleLength; j++) {
                if (lib_checkCssRule(ereg, document.styleSheets(i).rules(j).selectorText)) {
                    rules.push(document.styleSheets(i).rules(j).selectorText);
                    if(styleName != '*') {
                        return document.styleSheets(i).rules(j);
                    }
                }
            }
        }
    }
    return (styleName == '*'? rules: ret);
}
function lib_checkCssRule(ereg, rule) {
    var rules = rule.split(',');
    var rlen = rules.length;
    if(rlen == 1) {
        if( ereg.test(rule) ) {
            return true;
        }
    } else {
        for(var i = 0; i<rlen; i++) {
            if( ereg.test(rules[i]) ) {
                return true;
            }
        }
    }
    return false;
}
// get style property from object
function lib_getStyleProperty(obj, prop) {
    if(obj && obj.style[prop]) {
        return obj.style[prop];
    }
    return false;
}

function lib_getCssProperty(styleName, prop) {
    var cssObj = lib_findStyleRule(styleName);
    if(cssObj) {
        return lib_getStyleProperty(cssObj, prop);
    }
    return false;
}

var _lib_objCache={};
function lib_getElementById(ID) {
    if(!_lib_objCache[ID] ) {
        lib_putObjectCache(document.getElementById(ID));
    } else if(_lib_objCache[ID] && !_lib_objCache[ID].parentNode) {
        lib_clearObjectCache();
        lib_putObjectCache(document.getElementById(ID));
    }
    return _lib_objCache[ID];
}
function lib_clearObjectCache() {
    for(var objID in _lib_objCache) {
        _lib_objCache[objID] = null;
        delete _lib_objCache[objID];
    }
    _lib_objCache = {};
}
function lib_putObjectCache(obj) {
    if(obj && obj.id && obj.parentNode) {
        _lib_objCache[obj.id] = obj;
    }
}

var addressInfoChanged = false;

function lib_addressInfoChange(cType, prefix, obj) {
    addressInfoChanged = true;
    var theForm = obj.form;
    var countryObj = theForm.elements[prefix+'country'];
    var stateObj = theForm.elements[prefix+'state'];
    var countyObj = theForm.elements[prefix+'county'];
    if(cType == 'country') {
        if(obj.value == 'US' || obj.value == 'CA') {
            if(stateObj) {
                lib_loadAddressInfo('state', obj, stateObj);
            }
            if(countyObj) {
                countyObj.disabled = true;
                lib_clearDropDown(countyObj);
            }
        } else {
            if(stateObj) {
                stateObj.disabled = true;
                lib_clearDropDown(stateObj);
            }
            if(countyObj) {
                countyObj.disabled = true;
                lib_clearDropDown(countyObj);
            }
        }
    } else if(cType == 'state') {
        if(countyObj && obj.value != '') {
            lib_loadAddressInfo('county', obj, countyObj);
        }
    }
}

var _addInfoCache = new Array();

function lib_loadAddressInfo(cType, obj, fillObj, onAdressLoad) {
    fillObj.disabled = true;
    fillObj.options[0] = new Option('...Loading...', 0, false, true);
    var v = obj.value ? obj.value : 'empty_value';
    if(cType == 'state' && v != 'US' && v != 'CA') {
        lib_fillAddressInfo(false, fillObj, onAdressLoad);
        return;
    }
    if(typeof(_addInfoCache[cType]) != 'undefined' && typeof(_addInfoCache[cType][v]) != 'undefined') {
        lib_fillAddressInfo(_addInfoCache[cType][v], fillObj, onAdressLoad);
        return true;
    }
    JsHttpRequest.query(
            'backend.php',
            {'q': fillObj.form, '_backendAct':'loadAddressInfo', 'ctype': cType, 'objvalue': v},
            function(result, errors) {
                if(result) {
                    if(!_addInfoCache[cType]) _addInfoCache[cType] = new Array();
                    _addInfoCache[cType][v] = result['list'];
                    lib_fillAddressInfo(_addInfoCache[cType][v], fillObj, onAdressLoad);
                } else {
                    alert(errors);
                }
            },
            true  // do not disable caching
        );
}

function lib_clearDropDown(obj, leaveItem) {
    leaveItem = leaveItem? leaveItem: 0;
    while(obj.childNodes[leaveItem]) {
        obj.removeChild(obj.childNodes[leaveItem]);
    }
}

function lib_fillAddressInfo(list, fillObj, onAdressLoad) {
    lib_fillDropDown(fillObj, list);
    fillObj.disabled = (fillObj.childNodes.length == 0);
    if(typeof(onAdressLoad) == 'function') onAdressLoad();
}

function lib_fillDropDown(fillObj, list, leaveItem, selectedItem, setID) {
    leaveItem = leaveItem? leaveItem: 0;
    if(fillObj) {
        lib_clearDropDown(fillObj, leaveItem);
        if(list) {
            var i = leaveItem;
            var selected = false;
            for(var c in list) {
                selected = selectedItem == c? true: false;
                if(typeof(list[c]) != 'function') {
                    fillObj.options[i] = new Option(list[c], c, false, selected);
                    if(setID) fillObj.options[i].id = c;
                    i++;
                }
            }
        }
    }
}
function __debug(txt, append) {
    var obj;
    if(!__debug._debugObj) {
        obj = document.createElement('DIV');
        obj.style.position        = 'absolute';
        obj.style.top             = '100px';
        obj.style.left            = '100px';
        obj.style.zIndex          = 13000;
        obj.style.backgroundColor = '#FFFFFF';
        obj.style.border          = '1px solid #000000';
        obj.style.padding         = '5px';
        if(typeof(DragHandler) != 'undefined') {
            DragHandler.attach(obj, false, true);
            obj.style.cursor = 'move';
        }
        document.body.appendChild(obj);
        __debug._debugObj = obj;
    } else {
        obj = __debug._debugObj;
    }
    window.setTimeout(function() {
        if(append) {
            obj.innerHTML += txt;
        } else {
            obj.innerHTML = txt;
        }
    }, 0);
}
function lib_getPHPSessionID() {
	if( !lib_getPHPSessionID.recruiterSessionID ) {
        if(typeof(lib_PHPSESSID) != 'undefined') {
            lib_getPHPSessionID.recruiterSessionID = lib_PHPSESSID;
        } else {
            var fl = document.forms.length;
            var phpsObj;
            for(var i=0;i<fl;i++) {
                if(document.forms[i].elements['PHPSESSID']) {
                    phpsObj = document.forms[i].elements['PHPSESSID'].length? document.forms[i].elements['PHPSESSID'][0]: document.forms[i].elements['PHPSESSID'];
                    if(phpsObj) {
                        lib_getPHPSessionID.recruiterSessionID = phpsObj.value;
                        break;
                    }
                }
            }
        }
    }
    return lib_getPHPSessionID.recruiterSessionID;
}
function lib_sendFastAjaxRequest( params, callBackFn ) {
    if(lib_sendFastAjaxRequest.requestSent) return false;
    lib_sendFastAjaxRequest.requestSent = true;

    if(!params.PHPSESSID) params.PHPSESSID = lib_getPHPSessionID();
    if(!lib_sendFastAjaxRequest.fastAjaxObj) lib_sendFastAjaxRequest.fastAjaxObj = new FastAjax();
    var fa = lib_sendFastAjaxRequest.fastAjaxObj;
    fa.send('fastbackend.php', params, function(err, result) {
        lib_sendFastAjaxRequest.requestSent = false;
        if(!err) {
            callBackFn(result);
        } else {
            lib_hideAjaxLoadingIndicator();
            if(result != '') alert(result);
//            else alert('Unknown error while performing FastAjax request.');
        }
    });
    return true;
}

function lib_evalScript(script) {
    if(window.execScript) {
        window.execScript(script);
    } else {
        eval.call(null,script);
    }
}

function lib_getTableBody(tableObj) {
    if(!tableObj || !tableObj.childNodes) return tableObj;
    var tBody = false;
    var cLen = tableObj.childNodes.length;
    for(var i=0; i<cLen; i++) {
        if(tableObj.childNodes[i].tagName == 'TBODY') {
            tBody = tableObj.childNodes[i];
            break;
        }
    }
    return tBody ? tBody: tableObj;
}

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

String.prototype.trimZeros = function() {
	var hasMinus = false;
	var str = this;
	if (str.charAt(0) == '-') {
		hasMinus = true;
		str = str.replace(/^-/, '');
	}
	str = str.replace(/^0+([1-9]|0\.)/, '$1').replace(/(\.[0-9]*[1-9]|\.0)0+$/, '$1').replace(/([0-9])\.$/, '$1').replace(/^\.([0-9])/, '0.$1');
	str = str.replace(/^0+$/, '0');
	if (hasMinus) str = '-' + str;
	return str;
}

String.prototype.addslashes = function(){
	return this.replace(/(["\\\.\|\[\]\^\*\+\?\$\(\)])/g, '\\$1');
}

function showModalDialogNew(sURL, vArguments, sFeatures) {
    if(typeof(inactivityLogoutTime) != 'undefined' && !sURL.match(/inactivity=/)) {
        if(!sURL.match(/\?/)) {
            sURL = sURL + '?inactivity=' + inactivityLogoutTime;
        } else {
            sURL = sURL + '&inactivity=' + inactivityLogoutTime;
        }
    }
    return window.showModalDialogOld(sURL, vArguments, sFeatures);
}

if(typeof(showModalDialog) != 'undefined' && typeof(window.showModalDialogOld) == 'undefined') {
// define for the first time
    window.showModalDialogOld = window.showModalDialog;
    window.showModalDialog = showModalDialogNew;
}



