// JavaScript Document
// Live image upload path
var imagePath='Uploads/113/';

function showdetail(detail) {
	//document.elements[detail].class
	document.getElementById(detail).className = "showme";
}

function hidedetail(detail) {
	//document.elements[detail].class
	document.getElementById(detail).className = "hideme";
}

// inputCounter defaults to 6 because the page starts with 5 input fields
var inputCounter=6;
function addQuickOrderItem() {
	var theTable = document.getElementById("QuickOrderTable");
	var theErrorRow = theTable.insertRow(theTable.rows.length);
	theErrorRow.id = theErrorRow.uniqueID;
	var theRow = theTable.insertRow(theTable.rows.length);
	theRow.id = theRow.uniqueID;
	
	var theErrorBox = theErrorRow.insertCell(0);
	theErrorBox.colspan=2;
	theErrorBox.innerHTML='<variable strVariableName="strErrorMsg'+inputCounter+'">';
	
	var theSKUBox = theRow.insertCell(0);
	theSKUBox.id = theSKUBox.uniqueID;
	theSKUBox.innerHTML='<input type="text" name="strTFPID'+inputCounter+'" id="strTFPID'+inputCounter+'" value="" size="25" />';
	
	var theQtyBox = theRow.insertCell(1);
	theQtyBox.id = theQtyBox.uniqueID;
	theQtyBox.innerHTML='<input type="text" name="Qty'+inputCounter+'" id="Qty'+inputCounter+'" value="" size="4" />';
	
	inputCounter++;
}

function addMoreTextFields(tableName) {
	fieldHeadLeft = document.getElementById('head_left').value;
	fieldTextLeft = document.getElementById('text_left').value;
	fieldHeadRight = document.getElementById('head_right').value;
	fieldTextRight = document.getElementById('text_right').value;

	if (tableName == 'LeftColTable') {
		var leftHeading='<br />Heading (Max of xx characters)<br /><textarea class="heading_txtarea" name="heading_txtarea_l'+fieldHeadLeft+'"></textarea>&nbsp;<a href="javascript:void(0)" onclick="deleteRow(\'LeftColTable\',\'header\',this.parentNode.id)" class="image_x"><img src="'+imagePath+'images/shared/x.jpg" alt="Remove" width="12" height="12" border="0" /></a><br /><br />';
		var leftTextBlock='Text Block<br /><textarea class="txtblock_txtarea" name="txtblock_txtarea_l'+fieldTextLeft+'""></textarea> <a href="javascript:void(0)" onclick="deleteRow(\'LeftColTable\',\'textblock\',this.parentNode.id)" class="image_x"><img src="'+imagePath+'images/shared/x.jpg" alt="Remove" width="12" height="12" border="0" /></a><br />';
		addHeading(tableName,leftHeading,leftTextBlock,"left");
		document.getElementById('head_left').value = parseInt(fieldHeadLeft) + 1;
		document.getElementById('text_left').value = parseInt(fieldTextLeft) + 1;
	}
	else {
		var rightHeading='<br />Heading (Max of xx characters)<br /><textarea class="heading_txtarea" name="heading_txtarea_r'+fieldHeadRight+'"></textarea>&nbsp;<a href="javascript:void(0)" onclick="deleteRow(\'RightColTable\',\'header\',this.parentNode.id)" class="image_x"><img src="'+imagePath+'images/shared/x.jpg" alt="Remove" width="12" height="12" border="0" /></a><br /><br />';
		var RightTextBlock='Text Block<br /><textarea class="txtblock_txtarea" name="txtblock_txtarea_r'+fieldTextRight+'"></textarea> <a href="javascript:void(0)" onclick="deleteRow(\'RightColTable\',\'textblock\',this.parentNode.id)" class="image_x"><img src="'+imagePath+'images/shared/x.jpg" alt="Remove" width="12" height="12" border="0" /></a><br />';
		addHeading(tableName,rightHeading,RightTextBlock,"right");
		document.getElementById('head_right').value = parseInt(fieldHeadRight) + 1;
		document.getElementById('text_right').value = parseInt(fieldTextRight) + 1;
	}
}

function addHeading(tableName,heading,textBlock,fieldHead) {
	var theTable = document.getElementById(tableName);
	var len = theTable.rows.length;
	var theRow = theTable.insertRow(theTable.rows.length);
	if (fieldHead == 'left') { theRow.setAttribute("id","tr_l" + fieldHeadLeft + "h"); } else { theRow.setAttribute("id","tr_r" + fieldHeadRight + "h"); }
	
	var theInput = theRow.insertCell(0);
	if (fieldHead == 'left') { theInput.setAttribute("id","tr_l" + fieldHeadLeft + "h_td1"); } else { theInput.setAttribute("id","tr_r" + fieldHeadRight + "t_td1"); }
	
	theInput.innerHTML=heading;
	
	addTextBlock(tableName,textBlock,fieldHead);
}

function addTextBlock(tableName,textBlock,fieldHead) {
	var theTable = document.getElementById(tableName);
	var theRow = theTable.insertRow(theTable.rows.length);
	if (fieldHead == 'left') { theRow.setAttribute("id","tr_l" + fieldTextLeft + "t"); } else { theRow.setAttribute("id","tr_r" + fieldTextRight + "t"); }
	
	var theInput = theRow.insertCell(0);
	if (fieldHead == 'left') { theInput.setAttribute("id","tr_l" + fieldTextLeft + "t_td1"); } else {theInput.setAttribute("id","tr_r" + fieldTextRight + "t_td1"); }
	
	theInput.innerHTML=textBlock;
}


function deleteRow(tableName,fieldType,theCell) {
  var theRow = document.getElementById(theCell).parentNode.rowIndex;
  document.getElementById(tableName).deleteRow(theRow);
//	if (tableName == 'LeftColTable') {
//		if (fieldType == 'header')
//			document.getElementById('head_left').value = parseInt(fieldHeadLeft) - 1;
//		else
//			document.getElementById('text_left').value = parseInt(fieldTextLeft) - 1;
//	}
//	else {
//		if (fieldType == 'header')
//			document.getElementById('head_right').value = parseInt(fieldHeadRight) - 1;
//		else
//			document.getElementById('text_right').value = parseInt(fieldTextRight) - 1;
//	}
}

function flip_arrow(theArrow){
	var source_check=document[theArrow].src;
	if (source_check.match('arrow_brown_side.gif')) {
		document[theArrow].src=imagePath+'images/shared/arrow_brown_down.gif';
		document.getElementById('sidebar_cart').innerHTML='<table width="145" cellpadding="0" cellspacing="0" border="0" class="table" id="SidebarCartTable"><tr><td></td></tr></table><table width="145" cellpadding="0" cellspacing="0" border="0" class="table"><tr><td align="right"><b>total '+SidebarCartTotal+'</b></td></tr></table>';
		printSidebarCart();
	}
	else {
		document[theArrow].src=imagePath+'images/shared/arrow_brown_side.gif';
		document.getElementById('sidebar_cart').innerHTML='<table width="145" cellpadding="0" cellspacing="0" border="0" class="table"><tr><td align="left"><a href="shoppingbasket.cfm">'+SidebarCartItemCount+' items</a></td><td align="right"><a href="shoppingbasket.cfm">total '+SidebarCartTotal+'</a></td></tr></table>';
		sidebarRowSeq=1;
	}
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,"");
	if(isNaN(num))
		num = "0";
	var sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	var 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);
}

var sidebarRowSeq = 1;

function newCell(row,html,cssclass,align){
  var cell = row.insertCell(-1);
  cell.innerHTML = html;
//  if (cell.className)
    cell.setAttribute("className", cssclass);
//  else
    cell.setAttribute("class",cssclass);
  if (align!=null && align.length > 0)
    cell.style.textAlign = align;
  return cell;
}

function printItemSidebar(item, seq){
	var row = document.getElementById('SidebarCartTable').insertRow(sidebarRowSeq);  
	sidebarRowSeq++;
	
	// Item Number
	//newCell(row,"<a href='/shoppingbasket.cfm?strAction=EDITITEM&intSequence=" + seq + "/'></div>" + item[0] + "</a>","","left");
	newCell(row,item[0],"sidebar_cart_item","left");

	var unitPrice = 0;
	var quantity = parseInt(item[2]);
	var extendedPrice = parseFloat(item[3]);
	
	if (quantity > 0 && extendedPrice >0)
	unitPrice = extendedPrice / quantity;
	
	// Unit Price
	newCell(row,formatCurrency(unitPrice),"sidebar_cart_item","right");  
}

function printSidebarCart(){
	if (arySC.length){
	  for(var i=0;i<arySC.length;i++){
		printItemSidebar(arySC[i], i+1);
	  }
	}
	else {
		var row = document.getElementById('SidebarCartTable').insertRow(0);
		newCell(row,"no items","sidebar_cart_item","left");
	}
}

function resizeImages(pics,title,description,messages){
	for (i=0; i<title.length; i++) {
		var newImg = new Image();
		newImg.src = pics[i];
		var theHeight = newImg.height;
		var theWidth = newImg.width;
		if((theHeight>100) || (theWidth||100)){
			if(theWidth>theHeight){
				var ratio=100/theWidth;
				theHeight=theHeight*ratio;
				theHeight=Math.round(theHeight);
				theWidth=100;
			}
			else if(theHeight>theWidth){
				var ratio=100/theHeight;
				theWidth=theWidth*ratio;
				theWidth=Math.round(theWidth);
				theHeight=100;
			}
			else{ //height=width
				theHeight=100;
				theWidth=100;
			}
		}
		var finalImage='<img class="product_image" src="'+pics[i]+'" width="'+theWidth+'" height="'+theHeight+'" alt="image" border="0" align="left" />';
		messages.push();
		messages[i] = new Array(title[i],finalImage+description[i]);
	}
}

function submit_quick_order(destination){
	if (destination=='checkout') {
		document.getElementById('strReturnToURL').value='shoppingbasket.cfm';
		document.quick_order_frm.submit();
	}
	else {
		document.getElementById('strReturnToURL').value='engine.cfm';
		document.quick_order_frm.submit();		
	}
}

// Begin Form Finder functions
function choose_formfinder_action() {
	var whereToGo=document.getElementById('step1').value;
	if(whereToGo=='TaxForms')
		document.frm.action="formfinder.cfm";
	else if(whereToGo=='HCFA')
		document.frm.action="engine.cfm?strTFPType=HCFA";
	else
		document.frm.action="engine.cfm?strTFPType=ImpExp";
	document.frm.submit();
}

function writeFormFinderCats(taxCat,healthCat,impExpCat) {
	if (taxCat.length && !(taxCat=='0'))
		document.write('<option value="TaxForms" selected="selected">Tax Forms</option>');
	if (healthCat.length && !(healthCat=='0'))
		document.write('<option value="HCFA">Health Ins. Forms</option>');
	if (impExpCat.length && !(impExpCat=='0'))
		document.write('<option value="ImpExp">Import/Export Forms</option>');
}
// End Form Finder functions

function forgotPassword() {
	document.frmSignIn.strMembershipAction.value='ForgotPassword'; 
	document.frmSignIn.submit(); 
	return false;	
}

function writeIndexCats(taxCat,healthCat,impExpCat) {
	if (taxCat.length && !(taxCat=='0'))
		document.write('<option value="TaxForms">Tax Forms</option>');
	if (healthCat.length && !(healthCat=='0'))
		document.write('<option value="HCFA">Health Ins. Forms</option>');
	if (impExpCat.length && !(impExpCat=='0'))
		document.write('<option value="ImpExp">Import/Export Forms</option>');
}

// Begin Search Functions
function clearFillSearch(clear,message){
	if (clear)
		document.getElementById('searchon').value='';
	else if (!(clear) && (document.getElementById('searchon').value==''))
		document.getElementById('searchon').value=message;
	else {} // Do Nothing
}

function writeSearchCats(taxCat,healthCat,impExpCat) {
	if (taxCat.length && !(taxCat=='0'))
		document.write('<div class="product_link"><a href="engine.cfm?strTFPType=TaxForms">Tax Forms</a> <span class="left_menu_arrow"><img src="'+imagePath+'images/shared/spacer.gif" width="10" height="10" alt=">" border="0" /></span></div>');
	if (healthCat.length && !(healthCat=='0'))
		document.write('<div class="product_link"><a href="engine.cfm?strTFPType=HCFA">Health Insurance Claim Forms</a> <span class="left_menu_arrow"><img src="'+imagePath+'images/shared/spacer.gif" width="10" height="10" alt=">" border="0" /></span></div>');
	if (impExpCat.length && !(impExpCat=='0'))
		document.write('<div class="product_link"><a href="engine.cfm?strTFPType=ImpExp">Import/Export Forms</a> <span class="left_menu_arrow"><img src="'+imagePath+'images/shared/spacer.gif" width="10" height="10" alt=">" border="0" /></span></div>');
}
// End Search Functions

function writeWelcomeMsgCats(taxCat,healthCat,impExpCat) {
	if ((taxCat.length && !(taxCat=='0'))&&(healthCat.length && !(healthCat=='0'))&&(impExpCat.length && !(impExpCat=='0')))
		document.write('<a href="engine.cfm?strTFPType=TaxForms">Tax Form</a>, <a href="engine.cfm?strTFPType=HCFA">Health Insurance Claim Form</a> and <a href="engine.cfm?strTFPType=ImpExp">Import/Export Form</a>');
	else if ((taxCat.length && !(taxCat=='0'))&&(healthCat.length && !(healthCat=='0')))
		document.write('<a href="engine.cfm?strTFPType=TaxForms">Tax Form</a> and <a href="engine.cfm?strTFPType=HCFA">Health Insurance Claim Form</a>');
	else if ((taxCat.length && !(taxCat=='0'))&&(impExpCat.length && !(impExpCat=='0')))
		document.write('<a href="engine.cfm?strTFPType=TaxForms">Tax Form</a> and <a href="engine.cfm?strTFPType=ImpExp">Import/Export Form</a>');
	else if ((healthCat.length && !(healthCat=='0'))&&(impExpCat.length && !(impExpCat=='0')))
		document.write('<a href="engine.cfm?strTFPType=HCFA">Health Insurance Claim Form</a> and <a href="engine.cfm?strTFPType=ImpExp">Import/Export Form</a>');
	else if (healthCat.length && !(healthCat=='0'))
		document.write('<a href="engine.cfm?strTFPType=HCFA">Health Insurance Claim Form</a>');
	else if (impExpCat.length && !(impExpCat=='0'))
		document.write('<a href="engine.cfm?strTFPType=ImpExp">Import/Export Form</a>');
	else if (taxCat.length && !(taxCat=='0'))
		document.write('<a href="engine.cfm?strTFPType=TaxForms">Tax Form</a>');
	else
		document.write('forms');
}

function writeLogoCats(taxCat,healthCat,impExpCat) {
	if ((taxCat.length && !(taxCat=='0'))&&(healthCat.length && !(healthCat=='0'))&&(impExpCat.length && !(impExpCat=='0')))
		document.write('tax forms<br />health insurance claim forms<br />import &amp; export forms');
	else if ((taxCat.length && !(taxCat=='0'))&&(healthCat.length && !(healthCat=='0')))
		document.write('tax forms<br />health insurance claim forms');
	else if ((taxCat.length && !(taxCat=='0'))&&(impExpCat.length && !(impExpCat=='0')))
		document.write('tax forms<br />import &amp; export forms');
	else if ((healthCat.length && !(healthCat=='0'))&&(impExpCat.length && !(impExpCat=='0')))
		document.write('health insurance claim forms<br />import &amp; export forms');
	else if (healthCat.length && !(healthCat=='0'))
		document.write('health insurance claim forms');
	else if (impExpCat.length && !(impExpCat=='0'))
		document.write('import &amp; export forms');
	else if (taxCat.length && !(taxCat=='0'))
		document.write('tax forms');
	else
		document.write('');
}

// Begin Order History scripts
function check_order_history(objForm)
{
	var strReqMsg = "";
	var strValidationMsg = "";

	if(objForm.ldtDateBefore.value.length
		&& ! isDate(objForm.ldtDateBefore.value))
	{ strValidationMsg += "    - To Date must be a date\n"; }

	if(isNumeric(objForm.ldtDateBefore.value)
		&& objForm.ldtDateBefore.value > 0)
	{ strValidationMsg += "    - To Date must be less than 0\n"; }

	if(isNumeric(objForm.ldtDateBefore.value)
		&& objForm.ldtDateBefore.value <0)
	{ strValidationMsg += "    - To Date must be more than 0\n"; }
					
	if(objForm.ldtDateAfter.value.length
		&& ! isDate(objForm.ldtDateAfter.value))
	{ strValidationMsg += "    - From Date must be a date\n"; }

	if(isNumeric(objForm.ldtDateAfter.value)
		&& objForm.ldtDateAfter.value > 0)
	{ strValidationMsg += "    - From Date must be less than 0\n"; }

	if(isNumeric(objForm.ldtDateAfter.value)
		&& objForm.ldtDateAfter.value <0)
	{ strValidationMsg += "    - From Date must be more than 0\n"; }

	// Assemble all of the error messates together to display to the user
	if(strReqMsg.length || strValidationMsg.length)
	{
		var strDisplay = "";
		if(strReqMsg.length)
		{ strDisplay += "The following fields are required to be completed:\n\n" + strReqMsg; }

		if(strValidationMsg.length)
		{ strDisplay += "The following fields are not filled in correctly:\n\n" + strValidationMsg; }

		alert(strDisplay);
		return false;
	}
	else
	{
		return true;
	}
}
// End Order History scripts

function isNumeric(strValue)
{
	// sChar will hold the current character
	var strChar = "";
	// bNumeric is set to false when a bad character is encountered
	var blnNumeric = true;
	var intDecimalPointsFound = 0;

	// Loop through each of the characters in the string
	for(intIndex = 0; intIndex < strValue.length; intIndex++)
	{
		// Get the character at the current index
		strChar = strValue.charAt(intIndex);
		// If the first character is a '-' and it isn't the only character
		if((strChar == "-" && intIndex == 0 && strValue.length > 1))
		{
			blnNumeric = true;
		}
		// If the character is not a number and is not a '.', we can't allow it
		else if(isNaN(parseInt(strChar)) && strChar != ".")
		{
			blnNumeric = false;
			// Early exit
			intIndex = strValue.length;
		}
		else if(strChar == ".")
		{
			intDecimalPointsFound++;
		}
	}

	if(intDecimalPointsFound > 1 || intDecimalPointsFound == strValue.length)
	{
		blnNumeric = false;
	}

	return blnNumeric;
}
	
function isDate(dateStr) {
var datePat = /^(\d{1,2})(\/)(\d{1,2})(\/)(\d{4})$/;
var matchArray = dateStr.match(datePat); // is the format ok?

if (matchArray == null) {
return false;
}
else {
	month = matchArray[1]; // p@rse date into variables
	day = matchArray[3];
	year = matchArray[5];
	
	if (month < 1 || month > 12) { // check month range
	return false;
	}
	
	if (day < 1 || day > 31) {
	return false;
	}
	
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
	return false;
	}
	
	if (month == 2) { // check for february 29th
	var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
	if (day > 29 || (day==29 && !isleap)) {
	return false;
	}
	}
	return true; // date is valid
  }
}

function ValidatePhone(objPhone) {
	var strPhoneTxt = objPhone.value.replace(/\s+/g, "");
	var intPhoneLen = strPhoneTxt.length;
	var strTemp = "";
	var intTempLen = 0;
	var strFormatted = "";
	for(var i = 0; i < intPhoneLen; i++) {
		idxChar = strPhoneTxt.charAt(i);
		if(!isNaN(idxChar)) {
			strTemp = strTemp + idxChar;
		}
	}
	if(strTemp.length > 10) {
		strTemp = strTemp.substring(0,10);
	}
	if(strTemp.length > 0) {
		strFormatted = strFormatted + '(';
		if(strTemp.length > 3) {
			strFormatted = strFormatted + strTemp.substring(0,3) + ') ';
			strTemp = strTemp.substring(3);
			if(strTemp.length > 3) {
				strFormatted = strFormatted + strTemp.substring(0,3) + '-' + strTemp.substring(3);
			}
			else {
				strFormatted = strFormatted + strTemp.substring(0);
				if(strFormatted.length == 9) {
					strFormatted = strFormatted + '-';
				}
			}
		}
		else {
			strFormatted = strFormatted + strTemp.substring(0);
			if(strFormatted.length == 4) {
				strFormatted = strFormatted + ') ';
			}
		}
	}
	objPhone.value = strFormatted;
}

function pauseThenValidate(objPhone) {
	this.phone=objPhone;
	self.setTimeout('ValidatePhone(this.phone)', 1500);
}