/*******************************************************************************
 GLOBALS VARIABLES
*******************************************************************************/		
var MAX_DUMP_DEPTH = 10;

/*******************************************************************************
 KEYBOARD FUNCTIONS
*******************************************************************************/		
function getKeyDown(e) // handles keypress
{ 
    var keynum;

    if(window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }

    k = keynum;
    return k;
}

/*******************************************************************************
 AJAX FUNCTIONS
*******************************************************************************/		
function GetXmlHttpObject()
{
	var xmlHttp = null;
	try
	{
		// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
	}
	catch (e)
	{
		// Internet Explorer
		try
		{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}

/*******************************************************************************
 DIVERS MESSAGE FUNCTIONS
*******************************************************************************/		
function urlencode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
                                     
    var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];
    var ret = str.toString();
    
    // The histogram is identical to the one in urldecode.
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);
    
    for (search in histogram) {
        replace = histogram[search];
        tmp_arr = ret.split(search); // Custom replace
        ret = tmp_arr.join(replace); 
    }
    
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
    
    return ret;
}

function urldecode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin van Zonneveld!'
    // *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
    
    var histogram = {}, histogram_r = {}, code = 0, str_tmp = [];
    var ret = str.toString();
    
    // The histogram is identical to the one in urlencode.
    histogram['!']   = '%21';
    histogram['%20'] = '+';
 
    for (replace in histogram) {
        search = histogram[replace]; // Switch order when decoding
        tmp_arr = ret.split(search); // Custom replace
        ret = tmp_arr.join(replace);   
    }
    
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = decodeURIComponent(ret);
 
    return ret;
}

/*******************************************************************************
GENERAL FUNCTIONS
*******************************************************************************/		
function trim( str, charlist ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: mdsjack (http://www.mdsjack.bo.it)
    // +   improved by: Alexander Ermolaev (http://snippets.dzone.com/user/AlexanderErmolaev)
    // +      input by: Erkekjetter
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: DxGx
    // +   improved by: Steven Levithan (http://blog.stevenlevithan.com)
    // +   improved by: Jack
    // *     example 1: trim('    Kevin van Zonneveld    ');
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: trim('Hello World', 'Hdle');
    // *     returns 2: 'o Wor'
 
    var whitespace, l = 0;
    
    if (!charlist) {
        whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
    } else {
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');
    }
    
    l = str.length;
    for (var i = 0; i < l; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }
    
    l = str.length;
    for (i = l - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    
    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

function str_replace(search, replace, subject) {
    var f = search, r = replace, s = subject;
    var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;
 
    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    };
 
    return sa ? s : s[0];
}


/*******************************************************************************
 DIV MESSAGE FUNCTIONS
*******************************************************************************/		
function CenterDiv(strDiv)
{
    var elem = document.getElementById(strDiv);    
	var IpopTop = (document.body.clientHeight - elem.offsetHeight) / 2;
	var IpopLeft = (document.body.clientWidth - elem.offsetWidth) / 2;
	elem.style.left = IpopLeft + document.body.scrollLeft;
	elem.style.top = IpopTop + document.body.scrollTop;
}
		
function HideDiv(pass) {
	var divs = document.getElementsByTagName('div');
	for(i=0;i<divs.length;i++){ 
		if(divs[i].id.match(pass)){//if they are 'see' divs 
			if (document.getElementById) // DOM3 = IE5, NS6
				divs[i].style.visibility="hidden";// show/hide
			else
				if (document.layers) // Netscape 4 
					document.layers[divs[i]].display = 'hidden'; 
				else // IE 4 
					document.all.hideshow.divs[i].visibility = 'hidden'; 
		} 
	} 
} 

function ShowDiv(pass) { 
	var divs = document.getElementsByTagName('div');
	for(i=0;i<divs.length;i++){
		if(divs[i].id.match(pass)){
			if (document.getElementById)
				divs[i].style.visibility="visible";
			else
				if (document.layers) // Netscape 4 
					document.layers[divs[i]].display = 'visible'; 
				else // IE 4 
					document.all.hideshow.divs[i].visibility = 'visible'; 
		} 
	} 
}

function HideRow(pass) {
	var trs = document.getElementsByTagName('tr');
	for(i=0;i<trs.length;i++){
		if(trs[i].id.match(pass))//if they are 'see' divs
			trs[i].style.display="none";// show/hide
	}
}

function ShowRow(pass) {
	var trs = document.getElementsByTagName('tr');
	for(i=0;i<trs.length;i++){
		if(trs[i].id.match(pass))
			trs[i].style.display="";
	}
}

function PopWindow(url, title, swidth, sheight){
    var left = Math.floor( (screen.width - swidth) / 2);
    var top = Math.floor( (screen.height - sheight) / 2);
    alert(title);
	window.open(url, title, "width="+swidth+", height="+sheight+", status=no, resizable=yes, scrollbars=yes, left="+left+", top="+top);
}

function ProcessCancel(thisform, strValue){
	thisform.action.value=strValue ;
	return true;
}

function CheckFolderName(inputName,alerttext){
	var newRegExp = /^[a-zA-Z0-9_]+$/ ;

	if ( newRegExp.test(inputName.value) ){
		return true;
	}else{
		alert(alerttext);
		return false;
	}
}

function passdatevalidation(indate, alerttext){
	// handle pass date
	var td=indate.value.split('-');
	var newdate=td[1] + '/' + td[0] + '/' + td[2];
	var x=new Date(newdate);

	// get today date
	var today=new Date();
	tdmon=today.getMonth()+1;
	stripped=tdmon+'/'+today.getDate()+'/'+today.getYear();
	today=new Date(stripped);

	//alert(newdate + '<'+ stripped);

	if (x.valueOf()<today.valueOf()){
		alert(alerttext);
		return false;
	}
	return true;
}

function Confirm_Delete(mylink){
	if(confirm('Are you sure?')){
		document.location=mylink;
	}
}

function isnumbervalidation(entered, alertbox){
	s = entered.value;
	if ( (s == "") || (isNaN(Math.abs(s)) && (s.charAt(0) != '#'))){
		alert( alertbox );
		return false;
	}
	return true;
}

function emptyvalidation(entered, alertbox){
	with (entered){
		if (value==null || value==""){
			if (alertbox!=""){
				alert(alertbox);
			}
			return false;
		}else{
			return true;
		}
	}
}

function digitvalidation(entered, min, max, alertbox, datatype){
	with (entered){
		checkvalue=parseFloat(value);
		if (datatype){
			smalldatatype=datatype.toLowerCase();
			if (smalldatatype.charAt(0)=="i"){
				checkvalue=parseInt(value);
				if (value.indexOf(".")!=-1){
					checkvalue=checkvalue+1;
				}
			}
		}
		if ((parseFloat(min)==min && value.length<min) || (parseFloat(max)==max && value.length>max) || value!=checkvalue){
			if (alertbox!=""){
				alert(alertbox);
			}
			return false;
		}else{
			return true;
		}
	}
}

function valuevalidation(entered, dmin, dmax, alertbox, datatype){
	with (entered){
		checkvalue=parseFloat(value);
		if (datatype){
			smalldatatype=datatype.toLowerCase();
			if (smalldatatype.charAt(0)=="i"){
				checkvalue=parseInt(value);
			}
		}
		if ((parseFloat(dmin)==dmin && checkvalue<dmin) || (parseFloat(dmax)==dmax && checkvalue>dmax) || value!=checkvalue){
			if (alertbox!="") {
				alert(alertbox);
			}
			return false;
		} else {
			return true;
		}
	}
}

function lengthvalidation(entered, dmin, dmax, alertbox){
	with (entered){
		mylength=value.length;
		if(mylength<dmin || mylength>dmax){
			if (alertbox) {
				alert(alertbox);
			}
			return false;
		}else{
			return true;
		}
	}
}

function emailvalidation(entered, alertbox){
	with (entered){
		apos=value.indexOf("@");
		dotpos=value.lastIndexOf(".");
		lastpos=value.length-1;
		if (apos<1 || dotpos-apos<2 || lastpos-dotpos>3 || lastpos-dotpos<2){
			if (alertbox) {
				alert(alertbox);
			}
			return false;
		} else {
			return true;
		}
	}
}

function identicalvalidation(value1, value2, alertbox){
	if(value1.value != value2.value){
		if (alertbox) {
			alert(alertbox);
		}
		return false;
	} else {
		return true;
	}
}

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

// email
function checkEmail (strng, strlabel) {
	var error="";

    var emailFilter=/^.+@.+\..{2,3}$/;
    if (!(emailFilter.test(strng))) { 
		error = "Please enter a valid " + strlabel + " address.\n";
    } else {
		//test email for illegal characters
		var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/
        if (strng.match(illegalChars)) {
			error = "The " + strlabel + " address contains illegal characters.\n";
       	}
	}
	return error;    
}

// phone number - strip out delimiters and check for 10 digits
function checkPhone (strng) {
	var error = "";
	if (strng == "") {
	   error = "You didn't enter a phone number.\n";
	}
	
	var stripped = strng.replace(/[\(\)\.\-\ ]/g, ''); //strip out acceptable non-numeric characters
    if (isNaN(parseInt(stripped))) {
       error = "The phone number contains illegal characters.";
    }
	
    if (!(stripped.length == 10)) {
		error = "The phone number is the wrong length. Make sure you included an area code.\n";
    } 
	return error;
}

// password - between 4-12 chars, uppercase, lowercase, and numeral
function checkPassword(strng) {
	var error = "";
	var illegalChars = /[\W_]/; // allow only letters and numbers

    if ((strng.length < 4) || (strng.length > 12)) {
		error = "The password is the wrong length.\n";
    } 
	
	if (illegalChars.test(strng)) {
		error = "The password contains illegal characters.\n";
    } 
    //else if (!((strng.search(/(a-z)+/)) && (strng.search(/(A-Z)+/)) && (strng.search(/(0-9)+/)))) {
    //  error = "The password must contain at least one uppercase letter, one lowercase letter, and one numeral.\n";
    //}
    
    if(error.length>0){
    	alert(error);
		return false;    
    }else{
		return true;
    }
	
}    

// username - 4-20 chars, uc, lc, and underscore only.
function checkUsername (strng) {
	var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores

    if ((strng.length < 4) || (strng.length > 20)) {
       error = "The username is the wrong length.\n";
    }
    else if (illegalChars.test(strng)) {
    	error = "The username contains illegal characters.\n";
    } 
	return error;
}       


// non-empty textbox
function isEmpty(strng) {
	var error = "";
	if (strng.length == 0) {
		error = "The mandatory text area has not been filled in.\n"
	}
	return error;	  
}

// was textbox altered
function isDifferent(strng) {
	var error = ""; 
	if (strng != "Can\'t touch this!") {
		error = "You altered the inviolate text area.\n";
	}
	return error;
}

// exactly one radio button is chosen
function checkRadio(checkvalue) {
	var error = "";
	if (!(checkvalue)) {
		error = "Please check a radio button.\n";
	}
	return error;
}

// valid selector from dropdown list
function checkDropdown(choice) {
	var error = "";
	if (choice == 0) {
		error = "You didn't choose an option from the drop-down list.\n";
	}    
	return error;
}    

/*******************************************************************************
 DEBUG FUNCTIONS
*******************************************************************************/		
function dumpObj(obj, name, indent, depth)
{
    if (depth > MAX_DUMP_DEPTH) {
           return indent + name + ": <Maximum Depth Reached>\n";
    }
    if (typeof obj == "object") {
           var child = null;
           var output = indent + name + "\n";
           indent += "\t";
           for (var item in obj)
           {
                 try {
                        child = obj[item];
                 } catch (e) {
                        child = "<Unable to Evaluate>";
                 }
                 if (typeof child == "object") {
                        output += dumpObj(child, item, indent, depth + 1);
                 } else {
                        output += indent + item + ": " + child + "\n";
                 }
           }
           return output;
    } else {
           return obj;
    }
}


/*******************************************************************************
 BLIND FUNCTIONS
*******************************************************************************/		
function showBlind(){
    var arrayPageSize = getPageSize();
    
    var thediv = document.getElementById('displayBlind');
    thediv.style.width = arrayPageSize[0];
    thediv.style.height = arrayPageSize[1];
    if(thediv.style.display == "none"){
        thediv.style.display = "";
    }
    return false;
}
function hideBlind(){
    var thediv=document.getElementById('displayBlind');
    if(thediv.style.display != "none"){
        thediv.style.display = "none";
    }
    return false;
}

function getPageSize(){	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

/*******************************************************************************
 POPUP NOTES FUNCTIONS
*******************************************************************************/		
function ShowPopUpNote(strRef)
{
    var e = document.getElementById(strRef);
    
    /* get the mouse left position */
    x = event.clientX ;
    /* get the mouse top position  */
    y = event.clientY + 10;
    /* display the pop-up */
    e.style.display = "block";
    /* set the pop-up's left */
    e.style.left = x;
    /* set the pop-up's top */
    e.style.top = y;
}
/* this function hides the pop-up when
 user moves the mouse out of the link */
function HidePopUpNote()
{
    var e = document.getElementById(strRef);
    
    /* hide the pop-up */
    e.style.display = "none";
}

