
function time() {
	return((new Date()).getTime());
}

function ShowLoading(id, where) {
	$("#loadingimg").remove();
	var html = "<div id='loadingimg' style='z-index:1000; width:100%; text-align:center;'><img src='"+IMGS_DIR+"/nr_processing.gif'><br>We are scanning over 55,000,000 sources for information<br>from the last two weeks on your subject.</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 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() {
	$("body").prepend('<div id="overlay_div"></div>');
	$("#overlay_div").css({'position' : 'absolute', 'top' : "0px", 'left' : "0px", 'opacity' : '0.4', 'height' : $(document).height(), 'width' : $(window).width(), 'background' : 'gray', 'z-index' : '999', 'display' : 'none'});
	$("#overlay_div").fadeIn(500);
}

function UnDimPage() {
	$("#overlay_div").fadeOut(500, function() {
		$("#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", "yellow");
}

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;" 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 addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}
