/* *********************************************************************
*                                                                     *
*                       Product.dsp Form Scripts                      *
*                                                                     *
//**********************************************************************
*/
function validateProductChoice(){
	color = document.forms[0].color;
	parts  = document.forms[0].parts;
	pid = document.forms[0].pid;

	// this test for the existence of the color field
	// if (color != null && color != undefined)
	if (color != null)
   		var isColorSelected = isAnySelected(color);
   		else
   			isColorSelected = true;

    // customer must select a color and a parts type
	if (!isColorSelected){
		alert ("Please choose a color.");
		return false;
     	} else if (parts.selectedIndex == 0) {
			alert ("Please choose a parts type.");
			return false;
    		} else if (document.forms[0].CheckQuantity.selectedIndex ==0) {
			alert ("Please select the check quantity.");
			return false;
      	}  else if (document.forms[0].ship_method.selectedIndex == 0) {
			alert ("Please select the shipping method.");
			return false;
		}


	if (document.forms[0].crossSell.value == "Yes")
   		var accval = getCheckboxVal(document.forms[0].webAccessories);
 		else
   		accval = "";

   	if(document.forms[0].CheckQuantity.options[document.forms[0].CheckQuantity.selectedIndex].text == document.forms[0].CheckQuantity.options[1].text)
   		quickShipQty = document.forms[0].CheckQuantity.options[1].text;
   		else
   			quickShipQty = document.forms[0].CheckQuantity.options[2].text;

	// if (color != null && color!= undefined)
	if (color != null)
   		colorVal = getRBSelected(color);
   		else
   			colorVal = "";




 	itemID =  '&color='
		+ colorVal + '&'
		+ 'parts='     + parts.options[parts.selectedIndex].value + '&'
		+ 'Ship=' + document.forms[0].ship_method.options[document.forms[0].ship_method.selectedIndex].value+"&"
		+ 'pid='       + escape(pid.value) + '&'
		+ 'qty='         + document.forms[0].CheckQuantity.options[document.forms[0].CheckQuantity.selectedIndex].text+'&'
		+ 'qs_qty=' + quickShipQty + '&'
		+ 'software=' + getCookie("SoftwareType") +  '&acc='   + accval + "&LineID="+getLineID() +"&printer="+getCookie("PrinterType") + "&maker="+getCookie("MakerType");


	cartId = "&CartID=" +getCookie("CartID");

  	dbPath = getPath();
  	secureUrl = document.forms[0].sURL.value;
  	var Qstring = cartId + itemID + "&RefID=" + dbPath + getReorderStuff();
  	window.location =  secureUrl +"/personalize.dsp?OpenForm"+ Qstring;
}

// end validateProductChoice()


function validateNonCheck() {


		if (document.forms[0].CheckQuantity.options[document.forms[0].CheckQuantity.selectedIndex].text == 0) {
	     alert ("Please select the " + document.forms[0].pgroup.value +" quantity.");
	     return false;
       }  else if (document.forms[0].ship_method.selectedIndex ==0) {
	        alert ("Please select the shipping method.");
	        return false;
      }

    if (document.forms[0].parts)
   	   mparts =  document.forms[0].parts.options[document.forms[0].parts.selectedIndex].value;
       else
          mparts = "0";

    if (document.forms[0].color) {
   	   mcolor = getRBSelected(document.forms[0].color);
			 if(mcolor == null) {
					alert("Please make a color selection");
					return false;
				}
			}
       else
          mcolor = "None";

		if (document.forms[0].crossSell.value == "Yes" && document.forms[0].webAccessories != null )
   		var accval = getCheckboxVal(document.forms[0].webAccessories);
 		else
   		accval = "";


    pid = document.forms[0].pid;

    if(document.forms[0].CheckQuantity.options[document.forms[0].CheckQuantity.selectedIndex].text == document.forms[0].CheckQuantity.options[1].text)
   	    quickShipQty = document.forms[0].CheckQuantity.options[1].text;
    else
   	   quickShipQty = document.forms[0].CheckQuantity.options[2].text;


   productGroup = document.forms[0].pgroup.value;

   itemID =  '&color=' +mcolor+'&'
	           + 'parts=' + mparts + '&'
	           + 'pid='       + escape(pid.value) + '&'
	           + "Ship=" + document.forms[0].ship_method.options[document.forms[0].ship_method.selectedIndex].text+"&"
	           + 'qty='         + document.forms[0].CheckQuantity.options[document.forms[0].CheckQuantity.selectedIndex].text+'&'
	           + 'qs_qty=' + quickShipQty
	           + 'software='         + getCookie("SoftwareType") + "&acc=" + accval +"&LineID="+getLineID()+"&printer="+getCookie("PrinterType")+ "&maker="+getCookie("MakerType");
             addToCart(itemID +  "&prodGroup=" + productGroup +getReorderStuff());
}



function getCheckboxVal(chkbox) {
    //this function will get the selected values in a checkbox field
   var checked = true;
   var chkval = "";
   if ((!chkbox.length) && (checked == chkbox.checked))
			chkval = chkbox.value;
      else {
	    for (var r = 0; r < chkbox.length; r++){
					if ((checked == chkbox[r].checked))
						  chkval += chkbox[r].value + ",";
		      }
	    //if the string has a comma as the last index then create a new string without it
	    if (chkval.lastIndexOf(",") == chkval.length-1)
		  chkval =  chkval.substring(0,chkval.length - 1);
      }
    return chkval;
}

function getLineID() {
    //this function will get the query string and then parse it for the LineID parameter
    var Query = "";
    var LineID = "";
    if ( window.location.search != 0 ) {
      Query = window.location.search;
      } else {
        Query = "?OpenDocument";
    }
    LineID = getParameter(Query,"LineID");
    return LineID;
}

function getReorderStuff() {
//this function get the query string to determine if there is stuff on the query string that we would need
	returnString = "";
	if (window.location.search != 0)
	{
		query = window.location.search;
		otype = getParameter(query,"OTYPE");
		rnum = getParameter(query,"RONUM");
		pcode = getParameter(query,"PCODE");
		if (rnum != "null")
			returnString = "&RONUM="+rnum+"&OTYPE="+otype +"&PCODE="+pcode;
	}
	return returnString;
}

function showPrice() {
    //this function will determine if a parts variation is selected if so then show the price for the  selected amount
    var form = document.forms[0];
    var partsField = form.parts;
    var arraySize = form.CheckQuantity.length - 1;
    var sindex = form.CheckQuantity.selectedIndex;
//    var execPrice = "";
//    var execPriceVal = 0.0;

    //initialize price groups
    var pGroup = new Array();
    if (!form.parts) {
       //build one price group
 	     for (i = 0; i <=arraySize; i++) {
	          pGroup[i] = "$"+ getPrice(i,1);
       }
       } else {
       //build the number of price groups available
 		   rbidx = partsField.selectedIndex;
 		   if (rbidx ==0) {
 			     alert("Select the Parts Type before choosing quantity.");
 			     pGroup[0] = "$0.00";

 			     sindex = 0;
  		     } else {
	 	          for (i= 0; i <=arraySize; i++){
				      pGroup[i] =  "$"+ getPrice(i,rbidx);
				      }
           }
       }
    form.priceDisplay.value = pGroup[sindex];
//    execPriceVal = pGroup[sindex].substring(1, pGroup[sindex].length) * .80;
//    formatVal = Math.round(execPriceVal * 100).toString();
//    form.execPriceDisplay.value = "$" + dollarFormat(formatVal);
}

function dollarFormat(number){

	var dollar = number.substring(0, number.length -2);
	var cents  = number.substring(number.length - 2, number.length);

	return dollar + "." + cents;

}


function getPrice(pindex, fieldPstFx) {
		//given the field name build an array of the values in the field
		var form = document.forms[0];
		var fvalue = eval("document.forms[0].pricegroup"+fieldPstFx + ".value");
		var priceArray = new Array();
		price = "0.00";
		if (pindex != 0)  {
			//get the element from the field value each element is separated by a semicolon
			priceArray = fvalue.split(";");
			price = priceArray[pindex - 1];
		}
		return price;
}

function setDefaultValues() {

		//auto select envelopes - TLW - 20081125
		var selectedEnvelope = "false";
		if (document.forms[0].webAccessories !="null" ) {
			if (!document.forms[0].webAccessories.length) {
				if (document.forms[0].webAccessories.value.substring(0,2) == "CE"){
					document.forms[0].webAccessories.checked=true;
				}
			}
			else {
				for (i = 0;i< document.forms[0].webAccessories.length;i++) {
					if (document.forms[0].webAccessories[i].value.substring(0,2) == "CE"){
						if (document.forms[0].webAccessories[i].value.substring(document.forms[0].webAccessories[i].value.length-1,document.forms[0].webAccessories[i].value.length) == "S") {
							document.forms[0].webAccessories[i].checked = true;
							selectedEnvelope = "true";
							break;
						}
					}
				}
				if (selectedEnvelope == "false") {
					for (i = 0;i< document.forms[0].webAccessories.length;i++) {
						if (document.forms[0].webAccessories[i].value.substring(0,2) == "CE"){
							document.forms[0].webAccessories[i].checked = true;
							selectedEnvelope = true;
							break;
						}
					}
				}
			}
		}

		// if the software and printer type cookie is available then set the selections
		var qstring = window.location.search;
		lineId = getParameter(qstring,"LineID");
		ronum = getParameter(qstring,"RONUM");
		if ((lineId) || (ronum)){
			var qty =getParameter(qstring,"qty");
			var ship = getEncodedParameter(qstring,"Ship");
			var colors = getParameter(qstring,"color");
			var parts = getParameter(qstring,"parts");
			var reverse = getParameter(qstring, "reverse");
			var fto = getParameter(qstring, "fto");
			
			var colorF = document.forms[0].color;
			var partF = document.forms[0].parts;
			var shipF = document.forms[0].ship_method;
			var qtyF = document.forms[0].CheckQuantity;

			//fill the ship_method
			if ((shipF != null) & (ship !="null")) {
				shipF.options[1].selected = true;
				
				for (i = 0;i < shipF.options.length;i++) {
					
					if (shipF.options[i].value == ship) {
							shipF[i].selected = true;
							break;
					}
				}
		 	} else
				shipF.options[1].selected = true;
		/*
		if ((ship !="null")) {
				if (ship == "2D")
						shipF.options[2].selected = true;
				else
						shipF.options[1].selected = true;
		}
		*/

		//fill the color
		if ((colorF != null) & (colors !="null")) {
				for (i = 0;i< colorF.length;i++) {
					if (colorF[i].value == colors){
					colorF[i].checked = true;
					break;
					}
				}
		}

		//fill the parts
		if (document.forms[0].parts) {
			document.forms[0].parts.options[1].selected = true;
			for (i = 0;i<  document.forms[0].parts.options.length;i++) {
					if (document.forms[0].parts.options[i].value == parts) {
					 document.forms[0].parts.options[i].selected = true;
					 break;
					}
			}
		}

		//fill reverse collate
		if (reverse == "1")
				document.forms[0].reverseCollate.checked = true;

		//fill the quantity
		if ((qtyF != null) & (qty !="null" )) {

				for (i = 0;i <qtyF.options.length;i++) {
						if (qtyF.options[i].text == qty) {
								qtyF.options[i].selected= true;
							 //show the price
							 showPrice();
					     break;
							}
						if (qty == "400" && parts == "1") {
								qtyF.options[1].selected= true;
								showPrice();
					      break;
						}

						if (qty == "800" && parts == "1") {
								qtyF.options[2].selected= true;
								showPrice();
					      break;
						}

						if (qty == "300" && parts == "2") {
								qtyF.options[1].selected= true;
								showPrice();
					      break;
						}

						if (qty == "600" && parts == "2") {
								qtyF.options[2].selected= true;
								showPrice();
					      break;
						}


	      }
		//fill first time order
		if(fto == "yes")
		{
			document.forms[0].firstTimeOrder.checked = true;
		}
	
    }
   }
}

/* *********************************************************************
*                                                                     *
*                       Personalize.dsp Form Scripts                  *
*                                                                     *
//**********************************************************************
*/

function showDetails(obj) {

	var dbname = document.forms[0].dbname.value;
	var logoDocUnid = document.forms[0].LogoDocUnid.value;

	var text = obj.options[obj.selectedIndex].text;
	var value = obj.options[obj.selectedIndex].value;
	var image = document.images["LogoImage"];

	image.src = "/" + dbname + "/0/" + logoDocUnid + "/$FILE/" + value;

}

function loadFont() {
	sFont = document.forms[0].Font.options[document.forms[0].Font.selectedIndex].text;
	document.images['TypeDisplayImg'].src = "/mtw.nsf/Type" + sFont + ".gif?OpenImageResource";

}




function extraValidation()
{
//validate that the user did not select both a oneliner and a text oversig line
	f = document.forms[0];

		if((f.no_signature_lines.selectedIndex != 0) && (f.txt_over_signature_line1.value !="") &&  (f.txt_over_signature_line2.value !="") )
		{
			alert("Your business check can have either\nOne Extra Signature Line and One Text Over Signature Line\n          or\n"+
			"Two Extra Signature Lines and No Text Over Signature Lines\n          or\nTwo Text Over Signature Lines and No Extra Signature Lines" +
			"\n          or\nNo Extra Signature Lines and No Text Over Signature Lines");
			return false;
		}
		else if((f.no_signature_lines.selectedIndex == 2) && ((f.txt_over_signature_line1.value !="") ||  (f.txt_over_signature_line2.value !="")))
		{
			alert("Your business check can have either\nOne Extra Signature Line and One Text Over Signature Line\n          or\n"+
			"Two Extra Signature Lines and No Text Over Signature Lines\n          or\nTwo Text Over Signature Lines and No Extra Signature Lines" +
			"\n          or\nNo Extra Signature Lines and No Text Over Signature Lines");
			return false;
		}
	if (isNaN(f.RoutingNumber.value))
	{
		alert("Routing Number is a numeric field.\nPlease enter a number 9 digits long.");
		return false;
	}

	if ( isNaN(f.AccountNumber.value) && getParameter(window.location.search, "OTYPE") != "R")
	{
		alert("Account Number is a numeric field.\nPlease enter a numeric value.");
		return false;
	}

	if (isNaN(f.StartingNumber.value))
	{
		alert("We can only accept numbers in the\n starting number over the web.\nIf you need letters here,\n please give us a call.");
		return false;
	}
if( (f.StartingNumber.value == "") | (f.StartingNumber.value > 2147483646))
	{
		alert("Please enter a value for the starting check number between 1 and 2147483646");
		return false;
	}
	return true;
}

/*
==================================================================
LTrim(string) : Returns a copy of a string without leading spaces.
==================================================================
*/
function LTrim(str)
/*
   PURPOSE: Remove leading blanks from our string.
   IN: str - the string we want to LTrim
*/
{
   var whitespace = new String(" \t\n\r");

   var s = new String(str);

   if (whitespace.indexOf(s.charAt(0)) != -1) {
      // We have a string with leading blank(s)...

      var j=0, i = s.length;

      // Iterate from the far left of string until we
      // don't have any more whitespace...
      while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
         j++;

      // Get the substring from the first non-whitespace
      // character to the end of the string...
      s = s.substring(j, i);
   }
   return s;
}

/*
==================================================================
RTrim(string) : Returns a copy of a string without trailing spaces.
==================================================================
*/
function RTrim(str)
/*
   PURPOSE: Remove trailing blanks from our string.
   IN: str - the string we want to RTrim

*/
{
   // We don't want to trip JUST spaces, but also tabs,
   // line feeds, etc.  Add anything else you want to
   // "trim" here in Whitespace
   var whitespace = new String(" \t\n\r");

   var s = new String(str);

   if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
      // We have a string with trailing blank(s)...

      var i = s.length - 1;       // Get length of string

      // Iterate from the far right of string until we
      // don't have any more whitespace...
      while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
         i--;


      // Get the substring from the front of the string to
      // where the last non-whitespace character is...
      s = s.substring(0, i+1);
   }

   return s;
}

/*
=============================================================
Trim(string) : Returns a copy of a string without leading or trailing spaces
=============================================================
*/
function Trim(str)
/*
   PURPOSE: Remove trailing and leading blanks from our string.
   IN: str - the string we want to Trim

   RETVAL: A Trimmed string!
*/
{
   return RTrim(LTrim(str));
}


function doSubmit(f, v){

	var queryString = document.forms[0].queryString.value;
	var category = unescape(queryString.substring(queryString.indexOf("prodGroup=") + 10, queryString.indexOf("&CartID=")));
	var orderType = getParameter(queryString, "OTYPE");


//	if (category != "business" || category != "personal" || category != "computer")   <--- these should be &&s -- Jeb 2/20/04
	if (category != "business" && category != "personal" && category != "computer")
		var categoryName = "accessory";
		else var categoryName = category;

	if ( v ){
			if (f.line1.value == "" || containsAllSpaces(f.line1.value)) {
				alert("Line1 cannot be blank. Please enter a value");
				f.line1.focus();
				return false;
				}

			// if (f.RoutingNumber != undefined ){
			if (f.RoutingNumber != null){
			var routing = Trim(f.RoutingNumber.value);
			if (routing.length != 9) {
				alert("Please enter 9 digit number value without spaces in the Routing Number field");
				f.RoutingNumber.focus();
				return false;
				}

			if ( chkNumeric(f.RoutingNumber.value) == false ) {
				alert("Please enter 9 digit number value without spaces in the Routing Number field");
				f.RoutingNumber.focus();
				return false;
				}
			}

		// if (f.AccountNumber != undefined){
		if (f.AccountNumber != null){
			 if(f.AccountNumber.value == "") {
				alert("Please enter an all numeric value in the Account number field");
				f.AccountNumber.focus();
				return false;
				}

			 if(chkNumeric(f.AccountNumber.value) == false  && orderType != "R") {
				alert("Please enter an all numeric value in the Account number field");
				f.AccountNumber.focus();
				return false;
				}
		}


		// if (f.StartingNumber != undefined){
		if (f.StartingNumber != null){
		 	if(f.StartingNumber.value == "") {
				alert("Please enter an all numeric value in the Starting number field");
				f.StartingNumber.focus();
				return false;
				}
			if(chkNumeric(f.StartingNumber.value) == false)  {
				alert("Please enter an all numeric value in the Starting number field");
				f.StartingNumber.focus();
				return false;
				}
			if( categoryName !="personal" && f.StartingNumber.value > 2147483646) {
				alert("Please enter a value for the starting check number between 1 and 2147483646.");
				return false;
				}
			if( categoryName =="personal" && (f.StartingNumber.value < 101 ||  f.StartingNumber.value > 9100) ) {
				alert("Please enter a value for the starting check number between 101 and 9100. You may need to roll back to 101.");
				return false;
				}
		}

		var imgReq = getParameter(queryString, "imgReq");
		if (imgReq == "Yes") {
			var cutType = document.forms[0].CornerCut.selectedIndex;
			var cutName = document.forms[0].cCutDisplay.value;
			if (imgReq == "Yes" && cutName == "none" && cutType == 0) {
				alert("Please choose a logo or monogram image for this product");
				return false;
			}
		}

		var a = new Array();
		a[a.length] = [f.line1.value, 'Line 1'];
		// if (f.RoutingNumber != undefined)
		if (f.RoutingNumber != null)
		a[a.length] = [f.RoutingNumber.value , 'Routing Number', ['validlength', 9, null]];
		// if (f.AccountNumber != undefined)
		if (f.AccountNumber != null)
		a[a.length] = [f.AccountNumber.value, 'Account Number'];

		if (!f.ConfirmPersonalization.checked) {
			alert("Please confirm your product personalization area is correct and select the check box at the bottom of the page.");
			return false;
		}

		if ( validateRequiredFields( f, a ) )
			return true;
				else
			return false;

			}
}

function showAccents(category){

	var queryString = document.forms[0].queryString.value;
	var prodGroup = "";

	if( getParameter(queryString, "prodGroup") == "personal") {
		prodGroup = "Check";
		} else if(getParameter(queryString, "prodGroup") == "Address") {
		prodGroup = "Label";
		} else prodGroup = "Stamp";

	if (category == "personal")
		winAccent = window.open((getPath() + "/logodisplay_wallet.dsp?OpenForm"), 'typestyle', 'toolbar=no,location=no,directories=no,menubar=no,scrollbars=yes,resizable=yes,width=450,height=450');
	if (category == "business" || category == "computer" )
		winAccent = window.open((getPath() + "/logodisplay.dsp?OpenForm"), 'typestyle', 'toolbar=no,location=no,directories=no,menubar=no,scrollbars=yes,resizable=yes,width=450,height=450');
	if (category == "initials" )
		winAccent = window.open((getPath() + "/logodisplay_prestige.dsp?OpenForm&group=" + prodGroup), 'typestyle', 'toolbar=no,location=no,directories=no,menubar=no,scrollbars=yes,resizable=yes,width=450,height=450');
	if (category == "accessory" || category == "Stamps")
		winAccent = window.open((getPath() + "/logodisplay_rclogos.dsp?OpenForm"), 'typestyle', 'toolbar=no,location=no,directories=no,menubar=no,scrollbars=yes,resizable=yes,width=450,height=450');

	winAccent.focus();
}


function loadAccent()  {

	var queryString = document.forms[0].queryString.value;
	var category = unescape(queryString.substring(queryString.indexOf("prodGroup=") + 10, queryString.indexOf("&CartID=")));
	// alert(category);
	accent = document.forms[0].CornerCut.options[document.forms[0].CornerCut.selectedIndex].value;
	accentText = document.forms[0].CornerCut.options[document.forms[0].CornerCut.selectedIndex].text;
	if (accentText == "Standard Logo")	showAccents(category);
	else if(accentText == "Custom Logo") {
		document.images['AccentDisplayImg'].src = getPath()+"/clearpix.gif";
		document.forms[0].cCutDisplay.value = "Custom";
		Start("/mtw.nsf/customlogo?OpenPage");
	}
		
	else if(accentText == "Monogram") showAccents("initials");
	else if(category == "Accessories" && accentText == "Monogram") showAccents("Accessories");
	else{
		document.images['AccentDisplayImg'].src = getPath()+"/clearpix.gif";
	     document.forms[0].cCutDisplay.value = "none";
	}
}


function chkNumeric(objName) {

	var checkOK = "0123456789";
	var checkStr = objName;
	var allValid = true;
	var decPoints = 0;
	var allNum = "";

	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 (ch != ",")
				allNum += ch;
		}
		if (!allValid){
			return false;
			}
}



function setImageValue(imageVal) {
	if (imageVal != "none") {
		var QueryString = document.forms[0].queryString.value;
		var configVal = getParameter(QueryString, "ppcfg");
		var imageTypeCode = configVal.substring(2,3);
		if (imageTypeCode == "1")
			document.forms[0].imageCode1.value = imageVal;
			else
			document.forms[0].monogram.value = imageVal;
		}
}


function containsAllSpaces(fieldVal){
	for(i=0; i < fieldVal.length ; i++) {
		if(fieldVal.charAt(i) != " ") {
			return false;
			break;
		}
	}
	return true;
}



