
function time() {
	return((new Date()).getTime());
}

function ShowLoading(id, where) {
	$("#loadingimg").remove();
	var html = "<div id='loadingimg' style='z-index:1000;'><img src='"+IMGS_DIR+"/loading.gif'></div>";
	
	if (where == undefined) {
		where = "a";
	}
	switch (where) {
		case "a":
			$("#"+id).append(html);
		break;
		
		case "p":
			$("#"+id).prepend(html);
		break;
		
		default:
			$("#"+id).append(html);
	}
}

function HideLoading() {
	$("#loadingimg").remove();
}

function ShowProcessing(msg) {
	var win_h = screen.height - (screen.height*0.2);
	var win_w = screen.width;
	
	var box_h = 170;
	var box_w = 250;
	
	var pos_top = (win_h/2) - (box_h/2);
	var pos_lef = (win_w/2) - (box_w/2);
	
	$("body").append('<div id="loadingimg"><br><br><br><br>'+msg+' Please Wait...<br></div>');

	$("#loadingimg").css({	'position' : 'absolute', 
							'top' : pos_top+"px", 
							'left' : pos_lef+"px", 
							'height' : box_h+"px",
							"width" : box_w+"px"});
}

function ConfirmMsg(id, msg, doit) {
	
	$(".conf-msg").remove();
	
	var out = "<div class='conf-msg' id='confirm_msg' onclick='CloseConfirmMsg();'>"+msg+"<span class='conf-close'>close</span></div>";
	
	if (doit == 1) {
		$("#"+id).html(out);
	} else {
		return (out);
	}
}

function DimPage() {
	scroll(0,0);
	$("body").css("overflow", "hidden");
	$("body").prepend('<div id="overlay_div"></div>');
	$("#overlay_div").css({'position' : 'absolute', 'top' : "0px", 'left' : "0px", 'opacity' : '0.4', 'height' : screen.height, 'width' : screen.width});
}
function UnDimPage() {
	$("body").css("overflow", "auto");
	$("#overlay_div").remove();	
}

function CloseConfirmMsg() {
	HideThis("confirm_msg");
}

function ErrorMsg(id, msg, doit) {
	
	var out = "<div class='err-msg' id='err_msg' onclick='CloseErrorMsg();'>"+msg+"<span class='conf-close'>close</span></div>";
	
	if (doit == 1) {
		$("#"+id).html(out);
	} else {
		return (out);
	}
}

function CloseErrorMsg() {
	HideThis("err_msg");
}

function DisableForm(id) {
	$("#"+id+" > *").each(function() {
		$(this).attr("disabled", true);
		return(true);
	});
}

function GetHeight(id) {
	var max_h = 300;
	
	var h = $("#"+id).height();
	if (h > max_h) {
		return (max_h);
	} 
	
	return (h+20);
}

function HideThis(id) {
	//$("#"+id).css("display", "none");
	$("#"+id).fadeOut(500);
	
	if($("#overlay_div").length > 0) {
		UnDimPage();
	}
}

function ShowThis(id) {
	$("#"+id).css("display", "block");
}

function ElemExists(elemID) {
	if ($("#"+elemID).length > 0) {
		return true;
	} else {
		return false;
	}
}

function clearThis(id) {
	$("#"+id).val("");
}

function getDisplayProperty(level) {
	if(navigator.appName.indexOf("Microsoft") > -1){
		var canSee = 'block'
	} else {
		var canSee = 'table-'+level;
	}
	return canSee;
}

function showTrViaCss(id) {
	$("#"+id).css("display", getDisplayProperty('row'));
}

function isElemSownViaCss(elem) {
	var res = $("#"+elem).css("display");
	if (res=="none" || res=="undefined") {
		return false;
	} else {
		return true;
	}
}

function hiliteThis(id) {
	$("#"+id).css("background-color", "#FFFF7F");
}

function unHiliteThis(id) {
	$("#"+id).css("background", "transparent");
}

function showErr(XMLHttpRequest, textStatus, errorThrown) {
	alert(XMLHttpRequest + textStatus + " --Error: " + errorThrown);
}

function altRow(ref) {
	$(ref).hover(function() {
		$(ref).css("background-color", "#FFD455");
	}, function() {
		$(ref).css("background", "transparent");
	})
}

function queryStr(ji) {
	allUrl = window.location.search.substring(1);
	gy = allUrl.split("&");
	for (i=0;i<gy.length;i++) {
		ft = gy[i].split("=");
		if (ft[0] == ji) {
			return ft[1];
		}
	}
}

function URLDecode(psEncodeString) 
{
  var lsRegExp = /\+/g;
  return unescape(String(psEncodeString).replace(lsRegExp, " ")); 
}

function isArray(obj) {
	return (obj.constructor.toString().indexOf("Array") != -1);
}

/**
* Wicked function to keep ceratin elemnts in the page in sync in terms of
* the "height" attribute. I needed to comeup with this because the list of
* added (dropped) attributes (for example) needed to stay aligned (height)
* with the list of the original attrinutes (draggables).
*/
function adjustHeight(elemToAdjust, elemToCompareTo) {
	var elemToAdjustHt = document.getElementById(elemToAdjust).offsetHeight;
	var elemToCompareToHt = document.getElementById(elemToCompareTo).offsetHeight;
	if (elemToAdjustHt >= elemToCompareToHt) { return; }
	$("#"+elemToAdjust).css("height", elemToCompareToHt+"px");
}

function extract(what) {
    if (what.indexOf('/') > -1)
        answer = what.substring(what.lastIndexOf('/')+1,what.length);
    else
        answer = what.substring(what.lastIndexOf('\\')+1,what.length);
    return(answer);
}

function copyContent(from, to) {
	var copyThis = $("#"+from).html();
	$("#"+to).html(copyThis);
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
		num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function setCookie( name, value, expires, path, domain, secure ) 
{	
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

// with this test document.cookie.indexOf( name + "=" );
function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return URLDecode(cookie_value);
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function expandTextArea(rows, id) {
	var existRows = $("#"+id).attr("rows");
	$("#"+id).attr("rows", parseInt(existRows)+rows);
}

function shrinkTextArea(rows, id) {
	var MIN_ROWS = 3;
	var existRows = $("#"+id).attr("rows");
	if (existRows-MIN_ROWS>=MIN_ROWS) {
		$("#"+id).attr("rows", parseInt(existRows)-rows);
	} else {
		alert('Text Area has reached the minimum size. No more shrinking allowed!')
	}
}
	
var cX = 0; var cY = 0; var rX = 0; var rY = 0;
function UpdateCursorPosition(e){ cX = e.pageX; cY = e.pageY;}
function UpdateCursorPositionDocAll(e){ cX = event.clientX; cY = event.clientY;}
if(document.all) { document.onmousemove = UpdateCursorPositionDocAll; }
else { document.onmousemove = UpdateCursorPosition; }
function AssignPosition(d) {
	if(self.pageYOffset) {
		rX = self.pageXOffset;
		rY = self.pageYOffset;
		}
	else if(document.documentElement && document.documentElement.scrollTop) {
		rX = document.documentElement.scrollLeft;
		rY = document.documentElement.scrollTop;
		}
	else if(document.body) {
		rX = document.body.scrollLeft;
		rY = document.body.scrollTop;
		}
	if(document.all) {
		cX += rX; 
		cY += rY;
		}
	d.style.left = (cX-400) + "px";
	d.style.top = (cY-250) + "px";
}
function hideHint(d) {
	if(d.length < 1) { return; }
	document.getElementById(d).style.display = "none";
}
function showHint(d) {
	if(d.length < 1) { return; }
	var dd = document.getElementById(d);
	AssignPosition(dd);
	dd.style.display = "block";
}
function ReverseContentDisplay(d) {
	if(d.length < 1) { return; }
	var dd = document.getElementById(d);
	AssignPosition(dd);
	if(dd.style.display == "none") { dd.style.display = "block"; }
	else { dd.style.display = "none"; }
}
function showSeqElements(baseName, numEelemts) {
	for (i=0; i<numEelemts; i++) {
		$("#"+baseName+i).css("display", "block");
	}
}
function hideSeqElements(baseName, numEelemts) {
	for (i=0; i<numEelemts; i++) {
		$("#"+baseName+i).css("display", "none");
	}
}
function swapContent(id, content) {
	$("#"+id).html(content);
}

function ShowFormError(id, msg, posId) {
	if (posId=="") {
		posId = id;
	}
	if ($("#err"+id).length==0) {
		if (msg!="") {
			$("#"+posId).after(makeErrMsg(id, msg));
		}
		$("#"+id).addClass("errField");	
		$("#"+id).focus(function() {
			$(this).removeClass("errField");
			$("#err"+id).remove();
		});	
	}
}

function makeErrMsg(id, msg) {
	var out = '<div style="color:red; font-size:12pt;" id="err'+id+'">'+msg+'</div>';
	return(out);
}

function IsEmpty(id) {
	elemVal = $("#"+id).val();
	if (elemVal=="" || elemVal==undefined || elemVal=="0") {
		return true;
	} 
	return false;
}

function IsValidEmail(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
		return false
	}
	
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		return false
	}
	
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		return false
	}
	
	if (str.indexOf(at,(lat+1))!=-1){
		return false
	}
	
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		return false
	}
	
	if (str.indexOf(dot,(lat+2))==-1){
		return false
	}
	
	if (str.indexOf(" ")!=-1){
		return false
	}
	return true					
}

function IsNumeric(sText) {
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;
	for (i = 0; i < sText.length && IsNumber == true; i++) { 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) {
	 		IsNumber = false;
	 	}
	}
	return IsNumber;
}

function IsInteger(sText) {
	var ValidChars = "0123456789";
	var IsInt=true;
	var Char;
	for (i = 0; i < sText.length && IsInt == true; i++) { 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) {
	 		IsInt = false;
	 	}
	}
	return IsInt;
}

/**
 * Truncate a string to the given length, breaking at word boundaries and adding an elipsis
 * @param string str String to be truncated
 * @param integer limit Max length of the string
 * @return string
 */
function truncate (str, limit) {
	var bits, i;
	bits = str.split('');
	if (bits.length > limit) {
		for (i = bits.length - 1; i > -1; --i) {
			if (i > limit) {
				bits.length = i;
			}
			else if (' ' === bits[i]) {
				bits.length = i;
				break;
			}
		}
		bits.push('...');
	}
	return bits.join('');
};
// END: truncate


function isZip(s) {
	// Check for correct zip code
	reZip = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
	
	if (!reZip.test(s)) {
	  return false;
	}
	
	return true;
}

function validatePwd(pw1) {

var minLength = 6; // Minimum length
var maxLength = 24; // Minimum length

// check for minimum length
if (pw1.length < minLength) {
//alert('Your password must be at least ' + minLength + ' characters long.');
return false;
}

// check for max length
if (pw1.length > maxLength) {
//alert('Your password must not exceed ' + maxLength + ' characters long.');
return false;
}

// allow ONLY alphanumeric keys, no symbols or punctuation
// this can be altered for any "checkOK" string you desire
var checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var checkStr = pw1;
var allValid = true;
for (i = 0;  i < checkStr.length;  i++)
{
ch = checkStr.charAt(i);
for (j = 0;  j < checkOK.length;  j++)
if (ch == checkOK.charAt(j))
break;
if (j == checkOK.length)
{
allValid = false;
break;
}
}
if (!allValid)
{
//alert("Please enter only letter and numeric characters in the \"Alias\" field.");
//theForm.Alias.focus();
return (false);
}


return true;
}



function validateUsername(user) {

var minLength = 3; // Minimum length

// check for minimum length
if (user.length < minLength) {
return false;
}

return true;
}


function substr_count (haystack, needle, offset, length) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // *     example 1: substr_count('Kevin van Zonneveld', 'e');
    // *     returns 1: 3
    // *     example 2: substr_count('Kevin van Zonneveld', 'K', 1);
    // *     returns 2: 0
    // *     example 3: substr_count('Kevin van Zonneveld', 'Z', 0, 10);
    // *     returns 3: false

    var pos = 0, cnt = 0;

    haystack += '';
    needle += '';
    if (isNaN(offset)) {offset = 0;}
    if (isNaN(length)) {length = 0;}
    offset--;

    while ((offset = haystack.indexOf(needle, offset+1)) != -1){
        if (length > 0 && (offset+needle.length) > length){
            return false;
        } else{
            cnt++;
        }
    }

    return cnt;
}


