function time() {
	return((new Date()).getTime());
}

function microtime(get_as_float) {
    var now = new Date().getTime() / 1000;
    var s = parseInt(now, 10);

    return (get_as_float) ? now : (Math.round((now - s) * 1000) / 1000) + ' ' + s;
}

function randomString() {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = 4;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
    return(randomstring);
}


function ShowLoading(id, where, loader_id) {
	if (where == undefined) { where = "a"; }
    
    if (loader_id == undefined) {
        var loader_id = 'loader' + time();
    }
    
	var html = "<div id='"+loader_id+"' style='z-index:5000;'><img src='"+MY_DOMAIN+"/images/loading.gif'><br>loading...</div>";
	
	switch (where) {
		case "a":
			$("#"+id).append(html);
		break;
		
		case "p":
			$("#"+id).prepend(html);
		break;
        
        case "o":
            var loader_offset = $("#"+id).offset();
            var loader_height = $("#"+id).height();
            var loader_width = $("#"+id).width();
        	var loader_css = {	
                        'position' : 'absolute', 
        				'top' : loader_offset.top+"px", 
        				'left' : loader_offset.left+"px", 
        				'width' : loader_width+"px", 
        				'background' : 'transparent',
                        'text-align' : 'center',
                        'color' : '#ED01D6'
        			};
            $("#"+id).after(html);
            $("#"+loader_id).css(loader_css);
        break;
		
		default:
			$("#"+id).append(html);
	}
}

function HideLoading(loader_id) {
	$("#"+loader_id).remove();
}

function showOverlay(id, overlay_id) {
    
    if (overlay_id == undefined) {
        overlay_id = 'overlay' + time();
    }
    
    var my_photo_offset = $("#"+id).offset();
    var my_photo_height = $("#"+id).height();
    var my_photo_width = $("#"+id).width();
	var overlay_css = {	
                'position' : 'absolute', 
				'top' : my_photo_offset.top+"px", 
				'left' : my_photo_offset.left+"px", 
				'opacity' : '0.4', 
				'height' : my_photo_height+"px", 
				'width' : my_photo_width+"px", 
				'background' : '#666', 
				'z-index' : '4999'
			};
    $("#"+id).after('<div id="'+overlay_id+'">&nbsp;</div>');
    $("#"+overlay_id).css(overlay_css);    
}

function hideOverlay(overlay_id) {
	$("#"+overlay_id).remove();
}

function ShowProcessing(msg, zindex) {
	
	if (msg == undefined) { msg = "Processing. Please Wait..."; }
	if (zindex == undefined) { zindex = "10001"; }
	
	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">'+msg+'</div>');

	$("#loadingimg").css({	'position' : 'absolute', 
							'top' : pos_top+"px", 
							'left' : pos_lef+"px", 
							'height' : box_h+"px",
							"width" : box_w+"px",
							"z-index" : zindex,
							"background-color" : "#fff",
							"padding" : "10px",
							"padding-top" : "30px",
							"background-image" : "url(images/processing.gif)",
							"background-repeat" : "no-repeat",
							"background-position" : "center 10px",
							"text-align" : "center" 
						});
}

function HideProcessing() {
	$("#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(domid, overlay_id, zindex) {
	
	if (domid == undefined) { domid = "overlay_div"; }
	if (overlay_id == undefined) { overlay_id = null; }
	if (zindex == undefined) { zindex = "4999"; }
	
	$("body").css("overflow", "hidden");
	
	if ($("#"+domid).length > 0) {
		return;
	}
	
	$("body").prepend('<div id="'+domid+'"></div>');
	
	if (overlay_id == null) {
		domcss = {	'position' : 'absolute', 
					'top' : "0px", 
					'left' : "0px", 
					'opacity' : '0.4', 
					'height' : screen.height, 
					'width' : screen.width, 
					'background' : 'gray', 
                    //'background-image' : 'url('+MY_DOMAIN+'images/overlay_tile.png)',
					'z-index' : zindex
				};
	} else {
		
		pos = $("#"+overlay_id);
		offset = pos.offset();
		
		h = $("#"+overlay_id).height();
		w = $("#"+overlay_id).width();
		 
		domcss = {	'position' : 'absolute', 
					'top' : offset.top+"px", 
					'left' : offset.left+"px", 
					'opacity' : '0.4', 
					'height' : h+"px", 
					'width' : w+"px", 
					//'background' : 'gray',
                    'background-image' : 'url('+MY_DOMAIN+'images/overlay_tile.png)', 
					'z-index' : zindex
				};
	}
	
	$("#"+domid).css(domcss);
}

function UnDimPage(domid) {
	
	if (domid == undefined) { domid = "overlay_div"; }
	
	$("body").css("overflow", "auto");
	$("#"+domid).remove();	
	
	if (window["reload_parent"] == 1) {
		location.reload();
	}
}

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!')
	}
}
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 = 5; // 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);
}

    // At least one number
    re = /[0-9]/;
    if(!re.test(checkStr)) {
        return false;
    }
    
    // At least one letter
    re = /[a-zA-Z]/;
    if(!re.test(checkStr)) {
        return false;
    }



return true;
}



function validateUsername(username) {

    var minLength = 3; // Minimum length
    var maxLength = 24; // Minimum length
    
    // check for minimum length
    if (username.length < minLength) {
        alert('Your username must be at least ' + minLength + ' characters long.');
        return false;
    }
    
    // check for max length
    if (username.length > maxLength) {
        alert('Your username 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 = username;
    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("You have entered one or more invalid characters for the Username.\n\nAcceptable characters:\n\nany number, any letter, and these symbols: _ . - @ !");
        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;
}
