// JDP 20100330 - 	added showEURA(), and slightly modified showForm() 
// JDP 20100427 - 	changed phone number validation from 10 digits to 11, for international standards
// ALR 20100510 -   Test comment

// this function counts the occuranges of a character in a string
// use: test = "this, as you see, is a sentence, containing many ','s";
// numberOfCommas = test.count(','); // result: 4
String.prototype.count = function (s1) {
	repl = this.replace(s1, '');
	result = this.length - repl.length;
	return result;
};

function subAddForm() {
		document.addForm.submit();
}

function sendForm() {
		document.payForm.submit();
}


function confreturn(taskVal) {
	var msg,
		answer;

	 msg = "Clicking OK will file this return and further revision will not be possible.\n";
	 msg = msg + "Please review the entries provided.  Click Cancel to edit this return\n"; 
	 msg = msg + "or OK to submit this form.";  
	 answer = confirm(msg);
	 if (answer) {
		 location.href="cstaxmnt.pgm?task=" + taskVal;
	 } 

}

function confprepay() {
	var msg,
		answer;
 
	msg = "Clicking OK will record this prepayment for the specified Account number, year\n";
	msg = msg + "and quarter. Please confirm the entries and click OK to record this prepayment\n";
	msg = msg + "or Cancel to stop the payment.";
	
	answer = confirm(msg);
	if (answer) {
		 document.confPayForm.submit();
	}  


}

function confpay() {
	var msg,
		answer;
 
	msg = "Clicking OK will record this payment for the specified Account number, year\n";
	msg = msg + "and quarter. Please confirm the entries and click OK to record this payment\n";
	msg = msg + "or Cancel to stop the payment.";
	
	answer = confirm(msg);
	if (answer) {
		 document.confPayForm.submit();
	}  


}


function totalGross(rate1,rate2) {
	//The tax rates come in as X00 and Y00 (they are 4,2 in the file) so we need to div by 10,000 to get .0X and .0Y
	rate1 = rate1/10000;
	rate2 = rate2/10000;
 
	var SQRETS, SQSERV, SQRNTL, SQWSLE,SQRETS6, SQSERV6,  SQWSLE6,SQOTSL, SQGSEA,SQGSEA6,SQGVSL,SQWSLD,SQOV1K,SQOTRD,SQSLSN,SQOTSL6, SQGVSL6,SQWSLD6,SQOV1K6,SQOTRD6,SQSLSN6;
	//Process the 5% fields
	SQRETS = parseFloat(document.addForm.SQRETS.value,10);
	if (isNaN(SQRETS))
		SQRETS = 0;

	SQSERV = parseFloat(document.addForm.SQSERV.value,10);
	if (isNaN(SQSERV))
		SQSERV = 0;

	SQRNTL = parseFloat(document.addForm.SQRNTL.value,10);
	if (isNaN(SQRNTL))
		SQRNTL = 0;

	SQWSLE = parseFloat(document.addForm.SQWSLE.value,10);
	if (isNaN(SQWSLE))
		SQWSLE = 0;
	
	//Process the 6% fields
	SQRETS6 = parseFloat(document.addForm.SQRETS6.value,10);
	if (isNaN(SQRETS6))
		SQRETS6 = 0;

	SQSERV6 = parseFloat(document.addForm.SQSERV6.value,10);
	if (isNaN(SQSERV6))
		SQSERV6 = 0;

	
	SQWSLE6 = parseFloat(document.addForm.SQWSLE6.value,10);
	if (isNaN(SQWSLE6))
		SQWSLE6 = 0;


	document.addForm.SQGRRT.value = SQRETS + SQSERV + SQRNTL + SQWSLE;
	document.addForm.SQGRRT6.value = SQRETS6 + SQSERV6 + SQWSLE6;
	
	SQOTSL = parseFloat(document.addForm.SQOTSL.value,10);
	if (isNaN(SQOTSL))
		SQOTSL = 0;

	SQGVSL = parseFloat(document.addForm.SQGVSL.value,10);
	if (isNaN(SQGVSL))
		SQGVSL = 0;

	SQWSLD = parseFloat(document.addForm.SQWSLD.value,10);
	if (isNaN(SQWSLD))
		SQWSLD = 0;

	SQOV1K = parseFloat(document.addForm.SQOV1K.value,10);
	if (isNaN(SQOV1K))
		SQOV1K = 0;
	
	SQOTRD = parseFloat(document.addForm.SQOTRD.value,10);
	if (isNaN(SQOTRD))
		SQOTRD = 0;

	SQSLSN = parseFloat(document.addForm.SQSLSN.value,10);
	if (isNaN(SQSLSN))
		SQSLSN = 0;

	//This is sales to gov agencies - comment out until we have a field for this.
	//SQGSEA= parseFloat(document.addForm.SQGSEA.value,10);
	//if (isNaN(SQGSEA))
	//  SQSLSN = 0;


	//Process 6% fields
	SQOTSL6 = parseFloat(document.addForm.SQOTSL6.value,10);
	if (isNaN(SQOTSL6))
		SQOTSL6 = 0;

	SQGVSL6 = parseFloat(document.addForm.SQGVSL6.value,10);
	if (isNaN(SQGVSL6))
		SQGVSL6 = 0;

	SQWSLD6 = parseFloat(document.addForm.SQWSLD6.value,10);
	if (isNaN(SQWSLD6))
		SQWSLD6 = 0;

	SQOV1K6 = parseFloat(document.addForm.SQOV1K6.value,10);
	if (isNaN(SQOV1K6))
		SQOV1K6 = 0;
	
	SQOTRD6 = parseFloat(document.addForm.SQOTRD6.value,10);
	if (isNaN(SQOTRD6))
		SQOTRD6 = 0;

	SQSLSN6 = parseFloat(document.addForm.SQSLSN6.value,10);
	if (isNaN(SQSLSN6))
		SQSLSN6 = 0;

	//SQGSEA6 = parseFloat(document.addForm.SQGSEA6.value,10);
	//if (isNaN(SQGSEA6))
	//  SQSLSN6 = 0;

	document.addForm.SQTLDT.value = SQOTSL + SQGVSL + SQWSLD + SQOV1K + SQOTRD + SQSLSN;
	document.addForm.SQTLDT6.value = SQOTSL6 + SQGVSL6 + SQWSLD6+ SQOV1K6 + SQOTRD6 + SQSLSN6;

	document.addForm.SQNETT.value = parseFloat(document.addForm.SQGRRT.value,10) - 
									parseFloat(document.addForm.SQTLDT.value,10); 

	document.addForm.SQNETT6.value = parseFloat(document.addForm.SQGRRT6.value,10) - 
									parseFloat(document.addForm.SQTLDT6.value,10);

	//This function is used to round the total tax due to 
	//get the total tax due as net taxable * rate1
	var tottax1 = parseFloat(document.addForm.SQNETT.value,10) * rate1;
		
	//get the index of the decimal point
	var decpt = tottax1.toString().indexOf('.');
	
	//of decpt >= 0 a decimal point was found
	if (decpt >= 0) {
		if (tottax1.toString().charAt(decpt + 3) >= 5) {
			var tottax1 = tottax1 + .01; 
			document.addForm.SQTXDU.value = tottax1.toString().substring(0,decpt + 3);
			
		 } else {
			document.addForm.SQTXDU.value = tottax1.toString().substring(0,decpt + 3);
		 }
	}
	//else there is no decimal point in the number, just set tax due to tottax
	else {
			document.addForm.SQTXDU.value = tottax1;
	}

	//This function is used to round the total tax due to 
	//get the total tax due as net taxable * rate2
	var tottax2 = parseFloat(document.addForm.SQNETT6.value,10) * rate2;
	
	//get the index of the decimal point
	var decpt = tottax2.toString().indexOf('.');
	
	//of decpt >= 0 a decimal point was found
	if (decpt >= 0) {
	
		if (tottax2.toString().charAt(decpt + 3) >= 5) {
			var tottax2 = tottax2 + .01;
			document.addForm.SQTXDU6.value = tottax2.toString().substring(0,decpt + 3);
			
		 } else {
			 document.addForm.SQTXDU6.value = tottax2.toString().substring(0,decpt + 3);	
		 }
	} 
	//else there is no decimal point in the number, just set tax due to tottax
	else {
		document.addForm.SQTXDU6.value = tottax2;
	}

	document.addForm.SUBTOT.value = parseFloat(document.addForm.SQTXDU6.value,10) + parseFloat(document.addForm.SQTXDU.value,10); 
 }

//This function is called when you click on the Graph Consumption menu option
function getGraphDate() {
	window.open("csmethst.pgm?task=getDate","datePage","width=400,height=300");

} 

//This function is called when the user clicks graph from the pop up window. It validates that the date format populated
//it populates the date value in the calling form, submits the calling form and then closes itself. 
function doGraph() {
	if (document.selectForm.graphDate.value == "0000/00/00")		{
			alert("Please enter a date in yyyy/mm/dd format\n or use the button provided to select one."); 
	} else {
		window.opener.document.graphForm.fromDate.value = document.selectForm.graphDate.value;
		window.opener.document.graphForm.submit();
		self.close();
	}
}


//This function is used to disable the function key in the graphing window. If the user hit the enter key it would 
//not work properly. This was the easiest way to stop that from happening.
function disableEnterKey() { 
	if (window.event.keyCode == 13) {
		window.event.keyCode = 0; 
		alert("Please use the 'Draw Graph' button provided to submit your dates");  
	}
}

function countAreaChars(area, counter, limit) {
	var badChar = /[^\w \.,@_&\!:\-\/]|(&#39;)/gi;  // finds anything not alphanumeric, space, period, comma, @ _ - & ! :
	var occur = area.val().count(badChar);
	// I know that the value I will be replacing badChar is 5 char long, so minus an extra 4 char from the remaining length display
	
	// check the length of the description field, but don't cut it off if the user goes over
	if (area.val().length + (occur * 4) >= limit) {
		area.val(area.val().substring(0,limit - (occur * 4)));
		counter.html("0").css("color","Red");
	} else {
		counter.html(limit - area.val().length - (occur * 4)).css("color","Navy");
	}
}

// checks for mandatory fields to be filled out
function validateMand() {

	var valid = true;				// assume form is valid to start
	var formValue = "";
	var matched = null;
	var badChar = /[^\w \.,@_&\!:\-\/]|(&#39;)/gi;
	
	jQuery("#errors").html("");

	// (you do not need to escape regular metacharacters in a character class[] but you can if you want to (like I did for the / and - )
	// (the - actually needs to be escaped because it signifies a range, unless it's the first character right after the caret ^ symbol, which improves readability, but is really just confusing)
	
	jQuery('tr:visible > td > .mand').next('input, select, textarea').each(function (i) {	// matching only visible fields, because it is unreasonable for a user to fill out something hidden
		formValue = this.value;
		// match will produce a result if there are any alphanumeric characters (will be null otherwise, including if empty)
		matched = formValue.match(/[\w]/gi);
		if (matched === null) {
			formValue = jQuery(this).parent('td').prev('td').html().replace(/:/, "");
			jQuery("#errors").append("Please fill out the "+formValue+" field.<br />");
			valid = false;
			jQuery(this).focus();
		}
	});

	// remove any invalid characters
	jQuery(":input:text, textarea").each(function (i) {
		if (this.name.match(/DATE$/i) === null) {
			formValue = this.value;
			formValue = formValue.replace(badChar, "&#39;");
			jQuery(this).val(formValue);
		}
	});

	//badChar = /[^\d/-.]/g;	// finds anything not a digit or / or - or .
	// remove any non-numeric characters from the date fields too, except slashes
	// this matches a date as well: 
	// YYYY/MM/DD:
	//badChar = /^(19|20)\d\d[\- \/.]?(0[1-9]|1[012])[\- \/.]?(0[1-9]|[12][0-9]|3[01])$/;
	// MM/DD/YYYY:
	badChar = /^(0[1-9]|1[012])[\- \/.]?(0[1-9]|[12][0-9]|3[01])[\- \/.]?(19|20)\d\d$/;
	
	
	jQuery("input[name*='DATE']:visible").each(function (i) {
		formValue = jQuery(this).val();
		matched = formValue.match(badChar);
		if (matched === null) {
			formValue = jQuery(this).parent('td').prev('td').html().replace(/:/, "");
			jQuery("#errors").append("The value you have entered for "+formValue+" is not a valid date.\nPlease use a mm/dd/yyyy or mmddyyyy format.<br />");
			valid = false;
			jQuery(this).focus();
		}
	});
	// to a digit search for the phone and fax fields
	badChar = /\D/g; // find anything not a digit
	
	formValue = jQuery("input[name*='PHON']").val();
	formValue = formValue.replace(badChar, "");
	jQuery("input[name*='PHON']").val(formValue);
	if (formValue.length > 11) {
		formValue = formValue.substr(0, 11);
	}
	if (formValue.length > 11 || (formValue.length < 10 && formValue.length !== 0)) {
		jQuery("#errors").append("Please enter a ten or eleven digit phone number, including area code (and country code for non-US numbers).<br />");
		valid = false;
	}
	
	formValue = jQuery("input[name*='FAX']").val();
	formValue = formValue.replace(badChar, "");
	jQuery("input[name*='FAX']").val(formValue);
	if (formValue.length > 11 || (formValue.length < 10 && formValue.length !== 0)) {
		jQuery("#errors").append("Please enter a ten or eleven digit fax number, including area code (and country code for non-US numbers).<br />");
		valid = false;
	}
	
	
	matched = null;	// reset match back to null, just 'in case'
	badChar = /^(\w)+([\.\w_\-])*@([\w_\-])+(\.[\w_\-]+)+$/g;  // - symbol is escaped, even though it is the last character in the class
/*
\w is short for a-zA-Z0-9 or all alphanumeric characters (alpha and numeric)
the above regular express checks for any characters NOT in the specified set
by this expression even the following string is valid: "aaa.bb_c-dd@eee.ff_ggg-a"
*/
	// even though we're fetching the DOMelement by the ambiguous "if it has 'email' in the name" selector,
	// there shouldn't be more than on of these on a page, so there's no need to use the .each() function
	var element = jQuery("input[name*='EMAL']");
	if (element.length === 0) {
		element = jQuery("input[name*='EMAIL']");
	}

	formValue = element.val();

	matched = formValue.match(badChar);
	if (matched === null && formValue !== "") {
		formValue = element.parent('td').prev('td').html().replace(/:/, "");
		jQuery("#errors").append("The email you have entered is not valid.<br />");
		valid = false;
		element.focus();
	}

	return valid;
}

function submitCoin(file) {
	var names = [],
		values = [],
		parms = "";
	jQuery("#errors").html("");
	var valid = validateMand();
	
	if (valid === false) {
		return valid;
		
	} else {
	
		jQuery("#popForm :input").each(function () {
			names.push(jQuery(this).attr("name"));
			values.push(jQuery(this).val());
		});
			
		//document.write(values);
		//document.write(names);
		
		for (x = 0, xx = names.length; x < xx; x = x + 1) {
			if (names[x] !== "") {
				parms = parms + "&" + names[x] + "=" + values[x];
			}
		}

		jQuery.ajax({
			url: file,
			cache: false,
			dataType: "json",
			type: "POST",
			data: "rand=123456" + parms,
			success: function (resp) {
				if (resp.valid === "valid") {
					var msg = "<a href=\"http://www.sitkaonline.com/sitka/" + resp.file + "\" target=\"_blank\">Click here, or right-click to Save as</a>";
					showExp(msg);

//					jQuery("form#popForm").attr("action", resp.file).submit();
//					jQuery("form#popForm").attr("action", "");

					jQuery("#showForm").hide();
				} else {
					showExp(resp.err);
				}
				
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				//alert("error thrown: " + XMLHttpRequest.responseText + " " + textStatus + " " + errorThrown);
			}
		});

		return false;
	}
}

function submitThis(form) {
	//var theForm = "#"+form;
	//jQuery(theForm).submit();
	document.getElementById(form).submit();
}

function resetThis(form) {
	var theForm = "#"+form;
	jQuery(theForm+' input:text').val('');
	jQuery(theForm+' option').val('');
	submitThis(form);
}

function getDL(BDDOCID, BDDTLID, BHDEPT) {
	jQuery.ajax({
		url: "csbidlst.pgm",
		cache: false,
		dataType: "json",
		type: "POST",
		data: "task=download&BDDOCID=" + BDDOCID + "&BDDTLID=" + BDDTLID + "&BHDEPT=" + BHDEPT,
		success: function (data) {
			var download = false;

			if (data.expired !== 'expired' && data.expired !== 'newbid') {
				// check 'info required'
				if (data.req === "Y") {
					//show form
					showEURA(BDDTLID);
					download = false;

				} else {
					download = true;
				}

				// get download
				if (download === true && data.file !== '') {
					var msg = "<a href=\"http://www.sitkaonline.com/sitka/" + data.file + "\" target=\"_blank\">Click here, or right-click to Save as</a>";
					showExp(msg);
					//window.open(data.file);
				}
			} else {
				showExp(data.expmsg);
			}

		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			//alert("error thrown: " + XMLHttpRequest.responseText + " " + textStatus + " " + errorThrown);
		}

	});
	return false;
}


// JDP 20100330 - Added to show the EURA on the CSBIDLST.pgm, when a user clicks a download
// 					when clicked, this funciton is called, passing it the Bid Detail (file) id
//					which is stored in a hidden variable.  The element is shown. If accepted
//					showForm() is called, to show the contact info form.
function showEURA(BDDTLID) {
	jQuery("#msgbox").hide();
	//request data for centering
	var docwidth = document.documentElement.clientWidth;
	var docheight = document.documentElement.clientHeight;
	var divwidth = jQuery('#showEURA').width();
	var divheight = jQuery('#showEURA').height();
	
	// setting header width and display (fix for IE)
	jQuery('#popheader').css({
		'width': divwidth + 'px',
		'display': 'block'
	});
	
	// centering
	jQuery('#showEURA').css({
		'top': docheight/2 - divheight/2,
		'left': docwidth/2 - divwidth/2
	});
	
	// fixed not available in IE6, added scrolling event to keep popup in place
	if (jQuery.browser.msie === true && jQuery.browser.version.substr(0, 1) == 6) {
		var topnew = 0;
		topie6 = jQuery('#showEURA').css('top');
		topie6 = topie6.replace(/px/, '');
		topie6 = topie6 - 1 + 1;
		jQuery(window).scroll(function () {
			topnew = document.documentElement.scrollTop + topie6;
			jQuery('#showEURA').css({
				'top': topnew + 'px'
			});
		});
	}
//	jQuery('#BRDTLIDtmp').val(BDDTLID);
	jQuery('#BRDTLID').val(BDDTLID);
	jQuery('#showEURA').show();
}

function showForm() {
	jQuery("#msgbox").hide();
	jQuery('#showEURA').hide();
	//request data for centering
	var docwidth = document.documentElement.clientWidth;
	var docheight = document.documentElement.clientHeight;
	var divwidth = jQuery('#showForm').width();
	var divheight = jQuery('#showForm').height();
	
	// setting header width and display (fix for IE)
	jQuery('#popheader').css({
		'width': divwidth + 'px',
		'display': 'block'
	});
	
	// centering
	jQuery('#showForm').css({
		'top': docheight/2 - divheight/2,
		'left': docwidth/2 - divwidth/2
	});
	
	// fixed not available in IE6, added scrolling event to keep popup in place
	if (jQuery.browser.msie === true && jQuery.browser.version.substr(0, 1) == 6) {
		var topnew = 0;
		topie6 = jQuery('#showForm').css('top');
		topie6 = topie6.replace(/px/, '');
		topie6 = topie6 - 1 + 1;
		jQuery(window).scroll(function () {
			topnew = document.documentElement.scrollTop + topie6;
			jQuery('#showForm').css({
				'top': topnew + 'px'
			});
		});
	}
	// gets the Bid Detail (file) id from the hidden form on the EURA
	jQuery('#BRDTLIDtmp').val(jQuery('#BRDTLIDtmp').val());
	jQuery('#showForm').show();
}

function showExp(msg) {
	jQuery("#showForm").hide();
	jQuery("#msgbox").html("<p>"+msg+"<br /><button onclick='jQuery(\"#msgbox\").hide();'>Close</button></p>");
	jQuery("#msgbox p").css({margin : "10px"});
	jQuery("#msgbox").css({width : "240px", height : "90px"});
	
	//request data for centering
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = jQuery("#msgbox").height();
	var popupWidth = jQuery("#msgbox").width();
	
	// setting header width and display (fix for IE)
	jQuery("#popheader").css({
		"width": popupWidth + "px",
		"display": "block"
	});
	
	// centering
	jQuery("#msgbox").css({
		"top": windowHeight/2 - popupHeight/2,
		"left": windowWidth/2 - popupWidth/2
	});
	
	// fixed not available in IE6, added scrolling event to keep popup in place
	if (jQuery.browser.msie === true && jQuery.browser.version.substr(0, 1) == 6) {
		var topnew = 0;
		topie6 = jQuery("#msgbox").css("top");
		topie6 = topie6.replace(/px/, "");
		topie6 = topie6 - 1 + 1;
		jQuery(window).scroll(function () {
			topnew = document.documentElement.scrollTop + topie6;
			jQuery("#msgbox").css({
				"top": topnew + "px"
			});
		});
	}
	
	jQuery("#msgbox").show();

}

function pubIco() {
		//request data for centering
		var docwidth = document.documentElement.clientWidth;
		var docheight = document.documentElement.clientHeight;
		var divwidth = jQuery('#showList').width();
		var divheight = jQuery('#showList').height();
		
		// setting header width and display (fix for IE)
		jQuery('#popheader').css({
			'width': divwidth + 'px',
			'display': 'block'
		});
		
		// centering
		jQuery('#showList').css({
			'top': docheight/2 - divheight/2,
			'left': docwidth/2 - divwidth/2
		});
		
		// fixed not available in IE6, added scrolling event to keep popup in place
		if (jQuery.browser.msie === true && jQuery.browser.version.substr(0, 1) == 6) {
			var topnew = 0;
			topie6 = jQuery('#showList').css('top');
			topie6 = topie6.replace(/px/, '');
			topie6 = topie6 - 1 + 1;
			jQuery(window).scroll(function () {
				topnew = document.documentElement.scrollTop + topie6;
				jQuery('#showList').css({
					'top': topnew + 'px'
				});
			});
		}

	jQuery('#holders').css({height: (jQuery('#showList').height() - 250) + 'px', 'overflow-x' : 'hidden'});

}
