// Common JavaScript functions.
//*******************************************************************
// This object holds global variables for the software. Do not override.
var epicVars={
	'cardNumber':0,
	'ntabs':0
};
//*******************************************************************
function show_card(n,ntabs){
//alert('show_card('+n+','+ntabs+')');//1,2
	if (ntabs) epicVars.ntabs=intParse(ntabs);
//alert('ntabs='+ntabs+', epicVars.cardNumber='+epicVars.cardNumber);//2,0

	if (epicVars.cardNumber>0) $('#contents'+epicVars.cardNumber).css({'visibility':'hidden'});
	epicVars.cardNumber=intParse(n);

	$('#contents'+n).css({'visibility':'visible'});
	for(var i=1;i<=epicVars.ntabs;++i){
		$('#Tab_span'+i).removeClass('taba');//remove active tab class from ALL tabs
		$('#Tab_span'+i).removeClass('tabi');//remove inactive tab class from ALL tabs
		$('#Tab_span'+i).removeClass('tabm');//remove mouseover tab class from ALL tabs
		if(i!=n) $('#Tab_span'+i).addClass('tabi');//set only non-selected tabs to inactive
		}
	$('#Tab_span'+n).addClass('taba');//set only selected tab to active tab class

	// resize the remainder - DOM
	var consumed=0;
	for(var i=1;i<=epicVars.ntabs;++i) {
		consumed+=$('#TabTd'+i).width();
		}
	var w=intParse($('#contents1')[0].offsetWidth-consumed);
	if (w>0) $('#TabEnd').css( {width: w+'px' });

	if (typeof(cardhook)=='function') cardhook(n);

	return false;
}
//****************************************************
function tabMouseOver(tab){ if(!$(tab).hasClass('taba')) $(tab).addClass('tabm'); }
//****************************************************
function tabMouseOut(tab){ $(tab).removeClass('tabm'); }
//****************************************************
function adjustClass(){//mix the current inactive tab background color with mixColor to get a happy medium
	var mixColor='#AAAAAA';
	var rules = document.styleSheets[0].rules;
	if(!rules)return;
	for(var i=0,len=rules.length;i<len;++i){
		if(rules.item(i).selectorText=='.tabi'){
			rules.item(i).style.backgroundColor=(NiftyCube.mix(mixColor,rules.item(i).style.backgroundColor));
			return;
			}
		}
}
//*******************************************************************
function CB_click_handler(o)
{
	var h=$('#'+o);
	if ($("#CB_"+o).attr('checked')) h.val("Y");
	else h.val("N");
}
//*******************************************************************
function CB_click_handler_v2(event)
{
	var o=event.data.id;
	var h=$('#'+o);
	if ($("#CB_"+o).attr('checked')) h.val("Y");
	else h.val("N");
}
//*******************************************************************
// USE THIS IN CONJUNCTION WITH STYLE "text-transform:uppercase;"
// SEE <http://www.w3.org/TR/REC-CSS2/text.html#propdef-text-transform>
function blurredUpper(o){o.value=o.value.toUpperCase();}
//*******************************************************************
function blurredPhone(o){
var v=o.value;
var theRegExp=/\d/g;
var a=v.match(theRegExp);
var n=0;
if (a!=null) n=a.length;
var newv="";
for (i=0;i<3;i++) {if (n>i) {if (i==0) newv="(";newv+=a[i];}}
if (n>i) newv+=") ";
for (;i<6;i++) {if (n>i) newv+=a[i];}
if (n>i) newv+="-";
for (;i<10;i++) {if (n>i) newv+=a[i];}
o.value=newv;
}
/**************************************************************************/
function blurredDate(o){
var v=o.value;
var theRegExp = /\d/g;
var a=v.match(theRegExp);
var n=0;
if (a!=null) n=a.length;
var newv="";
for (i=0;i<2;i++) {if (n>i) newv+=a[i];}
if (n>i) newv+="/";
for (;i<4;i++) {if (n>i) newv+=a[i];}
if (n>i) newv+="/";
for (;i<8;i++) {if (n>i) newv+=a[i];}
o.value=newv;
}
/**************************************************************************/
function floatFormat(n,d){ // n = floating point #, d = # of decimal places
	if (n.length==0) n=0.0;
	/*
	SEE: <http://javascriptkit.com/javatutors/round.shtml>
	The comments below are based on: n=399.9999, d=2
	*/
	var p=Math.pow(10,d);			// 100
	var newn=Math.round(n*p)/p;		// 400
	var i=parseInt(newn);			// 400
	var e=floatParse(0.4/p);		// .004
	var a=(newn<0?-1:1);			// 1
	var remainder=parseInt( floatParse(newn - i + (e*a)) * p ) * a;	// 0
	r=remainder;
	for (z=d-1;z>0;z--){if (remainder<Math.pow(10,z)) r="0"+r;}
	var s=i+"."+r;
	return s;
}
/**************************************************************************/
function floatValue(n,d){ /*** to chop off unnecessary decimal digits  seeTaskNumber(8575); ***/
if (d==null) return n;
else if (d<=0) return Math.round(n);
else {
	d=Math.pow(10,d);
	return Math.round(n*d)/d;
	}
}
/**************************************************************************/
function floatParse(n){
	if(typeof n == 'undefined') return 0.0;
	n = n.toString().replace(/,/g,""); //seeTaskNumber(21633);
	var f=parseFloat(n);
	if (isNaN(f)) return 0.0;
	return f;
}
/**************************************************************************/
function intParse(n){
	var i=parseInt(n,10);
	if (isNaN(i)) return 0;
	return i;
}
/**************************************************************************/
// The julian functions below need to be kept consistent with julian.pic!
function toJulian(mdy){ // e.g. "09/07/2001"
	/*
	ASSUMES YOU ARE PASSING IN A VALID "mm/dd/yyyy" DATE!
	Calculates a Julian Date as the #days since November 25, 4714 B.C.
	This should work until December 31, 9999.
	(Mostly from www.basicguru.com/zijlema/javascript.html)
	*/
	var tmp=mdy;
	var mt=intParse(tmp); //"mm"
	tmp=tmp.substring(tmp.indexOf("/")+1);
	var dy=intParse(tmp); //"dd"
	tmp=tmp.substring(tmp.indexOf("/")+1);
	var yr=intParse(tmp); //"yyyy"

	// January & February to be considered as 13th & 14th month of previous year.
	if (mt<3){mt=mt+12;yr=yr-1;}

	var years=Math.floor((4712+yr)*365.25);			// days of full years since -4712
	var leaps=Math.floor(yr/100)-Math.floor(yr/400);// calculate invalid leap days
	var mnths=Math.floor(((mt-1)*30.6)+0.2);		// days of full months
	return years-leaps+mnths+dy;
}
/**************************************************************************/
function fromJulian(jul){ // e.g. 2452160 = 09/07/2001
	/*
	ASSUMES YOU ARE PASSING IN A VALID JULIAN DATE!
	RETURNS the "mm/dd/yyyy" string.
	(Mostly from www.basicguru.com/zijlema/javascript.html)
	*/
	YMD=new Array(2); // 3 elements: 0, 1 and 2
	jul=jul+68569;
	var temp=Math.floor((4*jul)/146097);
	jul=jul-Math.floor((146097*temp+3)/4);
	var tmpYear=Math.floor((4000*(jul+1))/1461001);
	jul=jul-Math.floor((1461*tmpYear)/4)+31;
	var tmpMonth=Math.floor((80*jul)/2447);
	YMD[0]=100*(temp-49)+tmpYear+Math.floor(tmpMonth/11);	// year=element 0
	YMD[1]=tmpMonth+2-(12*Math.floor(tmpMonth/11));			// month=element 1
	YMD[2]=jul-Math.floor((2447*tmpMonth)/80);				// day=element 2

	vMonth=(YMD[1].toString().length<2)?"0"+YMD[1]:YMD[1];
	vday  =(YMD[2].toString().length<2)?"0"+YMD[2]:YMD[2];
	return vMonth+"/"+vday+"/"+YMD[0];
}
//*******************************************************************
document.oncontextmenu = function(e){
	if (!e) var e = window.event;
	e.cancelBubble=true;
	e.returnValue=false;
	return false;
}
//*******************************************************************
function checkrange(v,min,max){// if value is in range then return true else return false
	if (v==undefined || v.length==0) v='0';//seeTaskNumber(17065);
	if (!checknumber(v)) return false;
	else return(numberrange((eval(v)),min,max));
	return true;
}
/**************************************************************************/
function checkint(v){
	//Returns true if value is a number or is NULL
	//otherwise returns false
	if (v==undefined || v.length==0) return true;//seeTaskNumber(17065);
	//Returns true if value is an integer defined as
	//   having an optional leading + or -.
	//   otherwise containing only the characters 0-9.
	var dec='.';
	//The first character can be + -  blank or a digit.
	var check_char=v.indexOf(dec);
	if (check_char<1) return checknumber(v);//Was it a decimal?
	return false;
}
/**************************************************************************/
function checknumber(v){
	//Returns true if value is a number or is NULL
	//otherwise returns false
	if (v.length==0) return true;

	//Returns true if value is a number with
	//   having an optional leading + or -.
	//   having at most 1 decimal point.
	//   otherwise containing only the chars 0-9.
	var start_fmt=' .+-0123456789';
	var number_fmt=' .0123456789';
	var decimal=false;
	var trailing=false;
	var digits=false;
	//The first character can be + - .  blank or a digit.
	var check_char=start_fmt.indexOf(v.charAt(0));
	//Was it a decimal?
	if (check_char==1) decimal=true;
	else if (check_char<1) return false;

	//Remaining characters can be only . or a digit, but only one decimal.
	for (var i=1;i<v.length;i++)
		{
		check_char=number_fmt.indexOf(v.charAt(i));
		if (check_char<0) return false;
		else if (check_char==1)
			{
			if (decimal) return false;		// Second decimal.
			else decimal=true;
			}
		else if (check_char==0)
			{
			if (decimal || digits) trailing=true;// ignore leading blanks
			}
		else if (trailing) return false;
		else digits=true;
		}
	return true; // All tests passed
}
/**************************************************************************/
function numberrange(v,min,max){
	if (min!=null) // check min
		{if (v<min) return false;}
	if (max!=null) // check max
		{if (v>max) return false;}
	return true;
}
/**************************************************************************/
function checkdate(v){
	//Returns true if value is a date format or is NULL
	//otherwise returns false
	if (v.length==0) return true;
	//Returns true if value is a date in the mm/dd/yyyy format
	isplit=v.indexOf('/');
	if (isplit == -1 || isplit==v.length) return false;
	sMonth=v.substring(0,isplit);
	if (sMonth.length==0) return false;
	isplit=v.indexOf('/',isplit+1);
	if (isplit == -1 || (isplit+1)==v.length) return false;
	sDay=v.substring((sMonth.length+1),isplit);
	if (sDay.length==0) return false;
	sYear=v.substring(isplit+1);
	if (!checkint(sMonth)) return false; //check month
	else if (!checkrange(sMonth,1,12)) return false; //check month
	else if (!checkint(sYear) || !checkrange(sYear,1900,2100)) return false; //check year
	else if (!checkrange(sYear,0,9999)) return false; //check year
	else if (!checkint(sDay)) return false; //check day
	else if (!checkday(sYear,sMonth,sDay)) return false; // check day
	else return true;
}
/**************************************************************************/
function checkday(y,m,d){
	max=31;
	if (m==4 || m==6 || m==9 || m==11) max=30;
	else if (m==2){
		if (y%4>0) max=28;
		else if (y%100==0 && y%400>0) max=28;
		else max=29;
		}
	return checkrange(d,1,max); //check day
}
/**************************************************************************/
function checkzip(v,c,f){
	var len=v.length;

	if(c==-1 || c=='US')
	{
	if (len==0) return true;
	if (len!=5 && len!=10) return false;
	// make sure 1st 5 digits are a valid integer
	if (v.charAt(0)=='-' || v.charAt(0)=='+') return false;
	if (!checkint(v.substring(0,5))) return false;
	if (len==5) return true;
	// check if separator is either a'-' or ' '
	if (v.charAt(5)!='-' && v.charAt(5)!=' ') return false;
	// check if last 4 digits are a valid integer
	if (v.charAt(6)=='-' || v.charAt(6)=='+') return false;
	return (checkint(v.substring(6,10)));
	}
	else if(c=='CA')
	{
	if (len==0) return true;

	//seeTaskNumber(7214);
	//seeTaskNumber(13485);
	return /^[a-zA-Z][0-9][a-zA-Z] [0-9][a-zA-Z][0-9]$/.test(v);
	}
	return true;
}
/**************************************************************************/
function checkEmail(v){
	//https://www.w3resource.com/javascript/form/email-validation.php
//	return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(v);
	return /^\w+[\w\*\!\^\#\+\%\?\$\}\~\_\{\=\/\&\-\.]*@\w+([\.-]?\w+)*(\.\w{2,})+$/.test(v);
	/*
	// SEE <http://developer.netscape.com/docs/examples/javascript/formval/overview.html>
	// Email address must be of form a@b.c, ie:
	// * at least one character before the @
	// * at least one character before and after the .
	// * both @ and . are required
	// there must be >= 1 character before @, so we
	// start looking at character position 1
	// (i.e. second character)
	var i=1;
	var l=v.length;
	if (l==0) return true;
	if (l<5) return false;
	while (i<l && v.charAt(i)!='@') i++; // look for @
	if (i>=l || v.charAt(i)!='@') return false;
	else i+=2;
	while (i<l && v.charAt(i)!='.') i++; // look for .
	// there must be at least one character after the .
	if (i>=l-1 || v.charAt(i+1)=='.') return false;
	if(v.match(/[\s<>[\]{}():;,]/g) != null) return false;
	return true;
	*/
}
/**************************************************************************/
// Returns true if character c is a digit ie:(0 .. 9).
function isDigit (c){return ((c>="0") && (c<="9"));}
/**************************************************************************/
// LTrim, RTrim, Trim functions from http://www.vermontsoftware.com/Javascript/trim.html
function LTrim(str){// Remove leading blanks from str.
	var whitespace=new String(" \t\n\r");
	var s=new String(str);
	if (whitespace.indexOf(s.charAt(0))!= -1){
		var j=0,i=s.length;
		// Iterate from the far left of string until no more whitespace
		while(j<i && whitespace.indexOf(s.charAt(j))!= -1) j++;
		// Get the substring from the first non-whitespace character to the end
		s = s.substring(j, i);
		}
	return s;
}
/**************************************************************************/
function RTrim(str){// Remove trailing blanks from str.
	var whitespace=new String(" \t\n\r");
	var s=new String(str);
	if (whitespace.indexOf(s.charAt(s.length-1))!= -1) {
		var i=s.length-1; // length of string
		// Iterate from the far right of string until no more whitespace
		while(i>=0 && whitespace.indexOf(s.charAt(i))!= -1) i--;
		// Get the substring from the front of the string to the last non-whitespace character
		s = s.substring(0, i+1);
		}
	return s;
}
/**************************************************************************/
function Trim(str){//Remove trailing and leading blanks from str.
	return RTrim(LTrim(str));
}
//*******************************************************************
function placeFocus(){ // direct focus to 1st data-entry field
	if (document.forms.length){
		var l;
		var f=document.forms[0];
		for (var i=0, n=f.length;i<n;++i){
			l=f.elements[i];
			if (l.disabled) continue;
			if (l.readOnly) continue;
			if (l.type=='hidden') continue;
			if (l.style && l.style.visibility=='hidden') continue;
			if (l.type=='text' || l.type=='textarea' || l.type.substr(0,6)=='select' || l.type=='password' || (l.type=='radio' && l.checked) || l.id !== "measureNumber"){
				l.focus();
				return;
			}
		}
	}
}
var exclusiveFocusExists=false;
//*******************************************************************
//seeTaskNumber(17390);
function inputFocus(){// workaround for webkit bug
	if (exclusiveFocusExists) return;
	var input = $(this);
	exclusiveFocusExists=true;
	setTimeout(function(){
		//to apply 'select all text' capability to safari mobile inputs, we have to use setSelectionRange(), which only works with input types listed below
		if(/text|search|tel/.test(input[0].type)) input[0].setSelectionRange(0,9999);
		else input.select();

		exclusiveFocusExists=false;
	},10);
}
//*******************************************************************
function bC(){
	var t;
	for (var i=0, n=aM.length;i<n;++i){
		t=$(aM[i]+'menu');
		if (t && t.style) t.style.visibility='hidden';
		}
}
function lo(o){
	if (o.className=='hi') o.className='mi';
	window.status='';
}
function hi(o){
	if (o.className=='mi') o.className='hi';
}
function stopEvent(e){
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}
function jmp(o,e){
	if (!e) var e = window.event;
	stopEvent(e);
	if (o.className=='mi'||o.className=='hi'){
		var t=o.getAttribute('target');
		if (t=='0') return false;
		var u=o.getAttribute('url');
		if (t!=null) window.open(u,t);
		else window.location.replace(u);
		return true;
		}
	return false;
}
function sm(i,e){
	if (!e) var e = window.event;
	var db=document.body;
	var t = $('#row'+i+'menu');
	var right=db.clientWidth-e.clientX;
	var bottom=db.clientHeight-e.clientY;
	if (typeof(nd)=="function") { nd(); nd(); }//seeTaskNumber(12670);

	bC();// hide other menus

	// if the horizontal distance isn't enough, move the menu to the left
	var left;
	if (right<t[0].offsetWidth) left=db.scrollLeft+e.clientX-t[0].offsetWidth;
	else left=db.scrollLeft+e.clientX;// position where the mouse was clicked
	if (left < 0) left = 0;
	t.css('left',left);

	//same concept with the vertical position
	var top;
	if (bottom<t.offsetHeight) top=db.scrollTop+e.clientY-t.offsetHeight;
	else top=db.scrollTop+e.clientY;
	if (top < 0) top = 0;
	t.css('top',top);
	t.css('visibility','visible');

	return false;
}
function showmenu(s,e){
	if (!e) var e = window.event;
	// How close the mouse is to the corner of the window?
	var db=document.body;
	var t = $('#'+s+'menu');
	var right=db.clientWidth-e.clientX;
	var bottom=db.clientHeight-e.clientY;
	bC();// hide other menus

	// if the horizontal distance isn't enough, move the menu to the left
	var left;
	if (right<t[0].offsetWidth) left=db.scrollLeft+e.clientX-t[0].offsetWidth;
	else left=db.scrollLeft+e.clientX;// position where the mouse was clicked
	if (left < 0) left = 0;
	t.css('left',left);

	//same concept with the vertical position
	var top;
	if (bottom<t.offsetHeight) top=db.scrollTop+e.clientY-t.offsetHeight;
	else top=db.scrollTop+e.clientY;
	if (top < 0) top = 0;
	t.css('top',top);
	t.css('visibility','visible');

	return false;
}
//*******************************************************************
function getBgL(){
if (top.mainFrame)  return top.bgL;
else if (window.opener) return window.opener.getBgL();
else if (window.dialogArguments) return window.dialogArguments.getBgL();
}
function getBgD(){
if (top.mainFrame) return top.bgD;
else if (window.opener) return window.opener.getBgD();
else if (window.dialogArguments) return window.dialogArguments.getBgD();
}
function bgL(o){o.style.backgroundColor=getBgL();}
function bgD(o){o.style.backgroundColor=getBgD();}
function bgG(o){o.style.backgroundColor='Gray';}
//*******************************************************************
function askFirst(q,u){
	if (q.length==0) q="Are you sure?";
	if (confirm(q)) location.replace(u);
	else return false;
}
//*******************************************************************
function firstAsk(q){
	q+="  Are you sure?";
	if (confirm(q)) return true;
	else return false;
}
//*******************************************************************
function typical(u){
	var date=new Date();
	return open(u,'d'+date.getTime(),config='top=0,left=0,resizable=yes,status=yes,top=0,left=0,scrollbars=yes,toolbar=yes,menubar=yes,titlebar=no,width=900,height=600;');
}//seeTaskNumber(9539);
//*******************************************************************
function addLoadEvent(func) {//seeTaskNumber(11822);
	var oldonload = window.onload;
	if (typeof window.onload != 'function') window.onload = func;
	else {
		window.onload = function() {
			if (oldonload) oldonload();
			func();
			}
		}
}
//*******************************************************************
function isPhoneNumberValid(val){
	if($.trim(val).length > 0 && $.trim(val).length != 14){
		return false;
	}
	return true;
}
//*******************************************************************
function setSelectValue(v,obj){//seeTaskNumber(9469);
//v: value to set
//obj: selection list object
	obj.val(v).attr('selected',true);
	return;
}
//*******************************************************************
function refreshStatuses(url){
	showPleaseWait();//seeTaskNumber(22768);
	window.location=url;
}
//*******************************************************************
function hideInstructions() {
	$("div#instructions").animate({opacity: 0.0, height: 0, marginTop: 0, marginBottom: 0}, 400, function(){$("div#instructions").hide();});
}
//*******************************************************************
function getURLParameter(name) {
	return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}