/* Global  */
var postCodeFlag = 0
/* End Global */
function order()
{
  var message = "";
  var completed = "true";
  message = checkOrdered(message);
  if(message !="")
  {
  alert(message);
  return;
  }
  else
  {
  message = message + isRequired(message);
  message = message + checkEmail(message);
  message = message + checkRef(message);
  message = message + checkPostCode(message);
  if(message !=""){ completed = "false";}
  }
   if(message == "")
   {
     buildForm();  

   }
  else
   {
   if(completed == "false") message = "Your order cannot be processed because:" + "\n" + message; 
    alert(message);
   } 
}
function getField(field)
{
 var quantity=""; 
 if (document.f1[field])
 {
  if (document.f1[field].length)
  {
   var total=0;
   for (var i=0; i<document.f1[field].length; i++)
   {
    value = parseInt(document.f1[field][i].value,10);
    if (!isNaN(value))
    {
     total += value;
    }
     quantity = total;
    }
   }
   else
   {
    quantity = document.f1[field].value;	
   }
  }
 return quantity;
}

/************************************/
function getField2(field)
{
 var quantity=""; 
 if (document.f1[field])
 {
  if (document.f1[field].length)
  {
   var total=0;
   for (var i=0; i<document.f1[field].length; i++)
   {
    value = parseInt(document.f1[field][i].value,10);
    if (!isNaN(value))
    {
     total += value;
    }
     quantity = total;
    }
   }
   else
   {
    quantity = document.f1[field].value;	
   }
  }
 return quantity;
}
/************************************/

function getRowHTML(fieldname, quantity, code, desc)
{
 var html="";
 html += "\n" + "<tr bgcolor='white'>";
 html += "\n" + "<td valign='top' width='47%'>" + code + "</td><td valign='top' width='46%'>" + desc + "</td>";
 html += "\n" + "<td valign='bottom' width='7%'><input readonly value='" +  quantity + "' type='text' name='" + fieldname + "' size='5' maxlength='5'></td>";
 html += "\n" + "</tr>"; 
 return html;
}

function checkOrdered(message) {
	var message = "";
	var blank = true

/************************** Below chunk will report content/structure of form for debugging purposes *****************
          alert("number of major sections:" + onlineform[0].length) //            is the number of major sections (eg starting/finishing tax year)
for(i=0; i < onlineform[0].length; i++) { // index thru major sections was <=
	for (a=1;a<onlineform[i].length;a++){ // index thru sub sections
		outStr = ""
		for (b=1;b<onlineform[i][a].length;b++){  // index thru indiv. items
			fieldname = onlineform[i][a][b][0];
			quantity =  getField(fieldname);
			code = onlineform[i][a][b][1]
			ref = onlineform[i][a][b][2]
			outStr = outStr + fieldname + "$" + quantity + "$" + code + "$" + ref + "\n"
		}
		
	}
alert("i=" + i + " " + onlineform[0].length)
}
alert("here")

************************** Above chunk will report content/structure of form *****************/

	for(i=0; i < onlineform[0].length; i++) { // added plus 1 on 4 aug 2005 removed jan-10 added
		for (a=1; a < onlineform[i].length; a++) {
			for (b=1; b < onlineform[i][a].length; b++) {
				fieldname = onlineform[i][a][b][0];
				quantity =  getField(fieldname);
				if (quantity) {
					blank = false
					var isItNum = IsNumeric(quantity)
					if (isItNum) {
						quantity = quantity * 1
						var max = onlineform[i][a][b][2] * 1
						if (quantity > max)  { 
							message = "You cannot order more than " + max + " for this item.\nPlease try again or cancel the form"
							overMax = document.f1[fieldname]
							overMax.focus()
							overMax.select()
							return message;
						}
						else if (quantity == 0) {
							message = "You cannot order a zero quantity.\nPlease leave blank if you do not intend to order this item."
							zeroVal = document.f1[fieldname]
							zeroVal.focus()
							zeroVal.select()
							return message;
						}	
						else message = "";
					}
					else {
						message = "Quantities must have a numeric value.\nPlease try again or cancel the form"
						nonNum = document.f1[fieldname]
						nonNum.focus()
						nonNum.select()
						return message;
					}
				} 
			} 
		} 
	}

	if (blank) {
		message = "You are trying to process this form but you have not ordered any stationery.\nPlease try again or cancel the form"
		return message;
	}
	return message
}

function checkEmail(message)
{
if(document.f1.email.value!="")
{
 str = document.f1.email.value;
 reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/;
   if (reg.test(document.f1.email.value) == false)
   {
    message= "- The e-mail address is incorrect" + "\n";
    return message;
   }
  } 
  message = "";
  return message;
}

function isRequired(message)
{
required = new Array ("title","organisation","address","address1");
message="";
for(i=0;i<required.length;i++)
{
field =  required[i];
 if (document.f1.elements[field].value=="")
  { 
   switch (i)
           {
            case 0:
               message = message + "- Your Contact Name is missing" + "\n";
               break;
           case 1:
               message = message +  "- The first line of your Business Name is missing" + "\n";
               break;
           case 2:
               message = message +  "- The first line of your Business Address is missing" + "\n";
               break;
           case 3:
               message = message +  "- The second line of your Business Address is missing" + "\n";
               break;    
           default:
               break;
           }
   } 
 }
 return message;
}

function checkRef(message)
{
var message = "";
for (i=0; i < onlineform[0].length; i++) {
    for (a=1; a < onlineform[i].length; a++) { // changed from a=1
      for (b=1; b < onlineform[i][a].length; b++) { // changed from b=1
        fieldname = onlineform[i][a][b][0];
	quantity =  getField(fieldname);
        if (quantity) {
          if(onlineform[i][a][b][3] == "yes") {
		  str = document.f1.Ref1.value;
         	  reg = /^[0-9]{3}/;
          	  if ((document.f1.Ref1.value=="") && (document.f1.Ref2.value==""))   {
	            message= "- The Employer's Reference Number is missing" + "\n";
		    return message;
            	  }
	          if ((reg.test(document.f1.Ref1.value) == false) || (document.f1.Ref2.value=="")) {
	            message= "- The Employer's Reference Number is incorrect" + "\n";
		    return message;
	          }        
          }
        } 
      }
    }
  }
  return message;
}




/**   old code below
function checkPostCode(message)
{
   message = "";

   regExpStr = "^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$"

  var re = new RegExp(regExpStr)
  if (!document.f1.postcode.value.toUpperCase().match(re)) message = "- The Postcode is incorrect or missing" + "\n";

  return message;
}
       old code above **/

function checkPostCode (message) {

   message = "";

  // Permitted letters depend upon their position in the postcode.
  var alpha1 = "[abcdefghijklmnoprstuwyz]";                       // Character 1
  var alpha2 = "[abcdefghklmnopqrstuvwxy]";                       // Character 2
  var alpha3 = "[abcdefghjkpmnrstuvwxy]";                         // Character 3
  var alpha4 = "[abehmnprvwxy]";                                  // Character 4
  var alpha5 = "[abdefghjlnpqrstuwxyz]";                          // Character 5
  
  // Array holds the regular expressions for the valid postcodes
  var pcexp = new Array ();

  // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Expression for postcodes: ANA NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

  // Expression for postcodes: AANA  NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "{1}" + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Exception for the special postcode GIR 0AA
  pcexp.push (/^(GIR)(\s*)(0AA)$/i);
  
  // Standard BFPO numbers
  pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);
  
  // c/o BFPO numbers
  pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);
  
  // Overseas Territories
  pcexp.push (/^([A-Z]{4})(\s*)(1ZZ)$/i);

  // ********** Load up the string to check ***********

  var postCode = stp(document.f1.postcode.value.toUpperCase());   // strip leading/trailing blanks as well

  // Assume we're not going to find a valid postcode
  var valid = false;
  
  // Check the string against the types of post codes
  for ( var i=0; i<pcexp.length; i++) {
    if (pcexp[i].test(postCode)) {
    
      // The post code is valid - split the post code into component parts
      pcexp[i].exec(postCode);
      
      // Copy it back into the original string, converting it to uppercase and
      // inserting a space between the inward and outward codes
      postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
      
      // If it is a BFPO c/o type postcode, tidy up the "c/o" part
      postCode = postCode.replace (/C\/O\s*/,"c/o ");
      
      // Load new postcode back into the form element
      valid = true;
      
      // Remember that we have found that the code is valid and break from loop
      break;
    }
  }
  
  // Return with either the reformatted valid postcode or the original invalid 
  // postcode

  if (!valid) {message = "- The Postcode is incorrect or missing" + "\n";}
  return message;
}

function stp(fld) {
var res = "";
var c = 0;
for (i=0; i<fld.length; i++) {
  if (fld.charAt(i) != " " || c > 0) {
    res += fld.charAt(i);
    if (fld.charAt(i) != " ") c = res.length;
    }
  }
return res.substr(0,c);
}

function checkMaxQuantity(input,maxquantity)
{
  var quantity = input.value;
  if(quantity > maxquantity)
  {
  alert("The most you can order is " + maxquantity)
  input.focus();
  input.select();
  }
}

function IsNumeric(sText)
{

   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;
 
   for (ii = 0; ii < sText.length && IsNumber == true; ii++) 
      { 
      Char = sText.charAt(ii); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         	IsNumber = false;
         }
      }
   return IsNumber;
   
   }

function buildForm()
{

var submitWindow = window.open("", "temp", "toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes");
submitWindow.focus();
submitWindow.document.open();
submitWindow.document.write("\n" + "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">")
submitWindow.document.write("\n" + "<html>");
submitWindow.document.write("\n" + "<head>");
submitWindow.document.write("\n" + "<link rel='stylesheet' href='../main.css'>");
submitWindow.document.write("\n" + "<script language=\"JavaScript\">");
submitWindow.document.write("\n" + "function print_it() {");
submitWindow.document.write("\n" + "if(window.print){");
submitWindow.document.write("\n" + "alert(\"Please set the required printer options in the dialog box which follows\")");
submitWindow.document.write("\n" + "window.print()");
submitWindow.document.write("\n" + "}");
submitWindow.document.write("\n" + "else {");
submitWindow.document.write("\n" + "alert(\"Your browser does not allow you print from here.\" + \"\\n\" + \"Instead, you can choose 'Print' from the File Menu in this window.\")");
submitWindow.document.write("\n" + "}");
submitWindow.document.write("\n" + "}");
submitWindow.document.write("\n" + "</\script>");
submitWindow.document.write("\n" + "<meta http-equiv='pragma' content='no cache'>");
submitWindow.document.write("\n" +"</head>");
submitWindow.document.write("\n" + "<body>");
submitWindow.document.write("\n" + "<table width='605'>");
submitWindow.document.write("\n" + "<tr><td width='16'>&nbsp;</td><td>");
submitWindow.document.write("\n" + "<a href='/home.htm' access key='1' target='_top'><img src='/images/logo_bw.gif' width='160' height='62' border='0' alt='Link to Home page'></a>");
submitWindow.document.write("\n" + "<p><b>Please check these details then click Submit to send the form, or Re-Order to go back and amend your order</b></p>");

// below line is live
submitWindow.document.write("\n" + "<form action='/asplib/employers_emp-form.asp' name=f1 method=post>");  // ***** live 
// below liness used for testing
//submitWindow.document.write("\n" + "<form action='mailto:chris.alsop@ir.gsi.gov.uk' method='post' enctype='text/plain'>"); // ***** test *****
//submitWindow.document.write("\n" + "<form action='mailto:chris.lowe@hmrc.gsi.gov.uk' method='post' enctype='text/plain'>"); // ***** test *****
submitWindow.document.write("\n" + "<p><b>Contact Details - You have given the following information:</b></p>");
submitWindow.document.write("\n" + "<table border='0' cellspacing='0' cellpadding='0'>");
submitWindow.document.write("\n" + "<tr bgcolor='#009966'>");
submitWindow.document.write("\n" + "<td>");
submitWindow.document.write("\n" + "<table border='0' cellspacing='1' cellpadding='1'>");

/* added crl 07.12.04 to correctly form reference number */
var reference = document.f1.Ref1.value + "/" + document.f1.Ref2.value
if (reference == "/") {reference = ""}
submitWindow.document.write("\n" + "<tr bgcolor='white'>");
submitWindow.document.write("\n" + "<td nowrap width='151'>Employer's Reference No:</td>");
submitWindow.document.write("\n" + "<td>");
submitWindow.document.write("\n" + "<input readonly value='"+ reference + "' type='text' name='reference:' size='10' maxlength='10'>");
submitWindow.document.write("\n" + "<tr bgcolor='white'>");
submitWindow.document.write("\n" + "<td nowrap width='150'>Contact Name:");
submitWindow.document.write("\n" + "</td>");
submitWindow.document.write("\n" + "<td>");
submitWindow.document.write("\n" + "<input readonly value='"+ document.f1.title.value + "' type='text' name='title:' size='20' maxlength='28'>");
submitWindow.document.write("\n" + "</td>");
submitWindow.document.write("\n" + "</tr>");
submitWindow.document.write("\n" + "<tr bgcolor='white'>");
submitWindow.document.write("\n" + "<td nowrap width='150' valign='top'>Business Name:</td>");
submitWindow.document.write("\n" + "<td>");
/* .replace code added to address lines to allow user to enter a single quote CRL 22.04.05 */
submitWindow.document.write("\n" + "<input readonly value='"+ document.f1.organisation.value.replace("'", "&#39") + "' type='text' name='organisation:' size='28' maxlength='28'>");
submitWindow.document.write("\n" + "</td>");
submitWindow.document.write("\n" + "</tr>");
submitWindow.document.write("\n" + "<tr bgcolor='white'>");
submitWindow.document.write("\n" + "<td nowrap width='150' valign='top'>&nbsp;</td>");
submitWindow.document.write("\n" + "<td>");
submitWindow.document.write("\n" + "<input readonly value='"+ document.f1.organisation1.value.replace("'", "&#39") + "' type='text' name='organisation1:' size='28' maxlength='28'>");
submitWindow.document.write("\n" + "</td>");
submitWindow.document.write("\n" + "</tr>");                       
submitWindow.document.write("\n" + "<tr bgcolor='white'>");
submitWindow.document.write("\n" + "<td nowrap width='150' valign='top'>&nbsp;</td>");
submitWindow.document.write("\n" + "<td>");
submitWindow.document.write("\n" + "<input readonly value='"+ document.f1.organisation2.value.replace("'", "&#39") + "' type='text' name='organisation2:' size='28' maxlength='28'>");
submitWindow.document.write("\n" + "</td>");
submitWindow.document.write("\n" + "</tr>");
submitWindow.document.write("\n" + "<tr bgcolor='white'>");
submitWindow.document.write("\n" + "<td nowrap width='150' valign='top'>&nbsp;</td>");
submitWindow.document.write("\n" + "<td>");
submitWindow.document.write("\n" + "<input readonly value='"+ document.f1.organisation3.value.replace("'", "&#39") + "' type='text' name='organisation3:' size='28' maxlength='28'>");
submitWindow.document.write("\n" + "</td>");
submitWindow.document.write("\n" + "</tr>");
submitWindow.document.write("\n" + "<tr bgcolor='white'>");
submitWindow.document.write("\n" + "<td nowrap rowspan='4' valign='top'>Address: </td>");
submitWindow.document.write("\n" + "<td>");
submitWindow.document.write("\n" + "<input readonly value='"+ document.f1.address.value.replace("'", "&#39") + "' type='text' size='28' name='address:' maxlength='28'>");
submitWindow.document.write("\n" + "</td>");
submitWindow.document.write("\n" + "</tr>");
submitWindow.document.write("\n" + "<tr bgcolor='white'>");
submitWindow.document.write("\n" + "<td>");
submitWindow.document.write("\n" + "<input readonly value='"+ document.f1.address1.value.replace("'", "&#39") + "' type='text' size='28' name='address1:' maxlength='28'>");
submitWindow.document.write("\n" + "</td>");
submitWindow.document.write("\n" + "</tr>");
submitWindow.document.write("\n" + "<tr bgcolor='white'>");
submitWindow.document.write("\n" + "<td>");
submitWindow.document.write("\n" + "<input readonly value='"+ document.f1.address2.value.replace("'", "&#39") + "' type='text' size='28' name='address2:' maxlength='28'>");
submitWindow.document.write("\n" + "</td>");
submitWindow.document.write("\n" + "</tr>");
submitWindow.document.write("\n" + "<tr bgcolor='white'>");
submitWindow.document.write("\n" + "<td>");
submitWindow.document.write("\n" + "<input readonly value='"+ document.f1.address3.value.replace("'", "&#39") + "' type='text' size='28' name='address3:' maxlength='28'>");
submitWindow.document.write("\n" + "</td>");
submitWindow.document.write("\n" + "</tr>");
submitWindow.document.write("\n" + "<tr bgcolor='white'>");
submitWindow.document.write("\n" + "<td nowrap width='150' valign='top'>Postcode:</td>");
submitWindow.document.write("\n" + "<td>");
submitWindow.document.write("\n" + "<input readonly value='"+ document.f1.postcode.value + "' type='text' size='8' name='postcode:' maxlength='8'>");
submitWindow.document.write("\n" + "</td>");
submitWindow.document.write("\n" + "</tr>");                                 
submitWindow.document.write("\n" + "<tr bgcolor='white'>");
submitWindow.document.write("\n" + "<td nowrap width='150'>Email:</td>");
submitWindow.document.write("\n" + "<td>");
submitWindow.document.write("\n" + "<input readonly value='"+ document.f1.email.value + "' type='text' name='email:' size='28' maxlength='50'>");
submitWindow.document.write("\n" + "</td>");
submitWindow.document.write("\n" + "</tr>");
submitWindow.document.write("\n" + "<tr bgcolor='white'>");
submitWindow.document.write("\n" + "<td nowrap width='150'>Telephone:</td>");
submitWindow.document.write("\n" + "<td>");
submitWindow.document.write("\n" + "<input readonly value='"+ document.f1.telephone.value + "' type='text' name='telephone:' size='20' maxlength='20'>");
submitWindow.document.write("\n" + "</td>");
submitWindow.document.write("\n" + "</tr>");
submitWindow.document.write("\n" + "</table>");
submitWindow.document.write("\n" + "</td>");
submitWindow.document.write("\n" + "</tr>");
submitWindow.document.write("\n" + "</table>");
submitWindow.document.write("\n" + "<p><b>Order Details - You have given the following information:</b></p>");
submitWindow.document.write("\n" + "<table width='605' border='0' cellspacing='0' cellpadding='0'><tr bgcolor='#009966'><td>");
submitWindow.document.write("<table border='0' cellpadding='1' cellspacing='1' width='100%'>");
submitWindow.document.write("<tr bgcolor='white'><td><b>Name</b></td><td><b>Description</b></td><td><b>Qty</b></td></tr>");
var orders = new Array();

for(i=0; i < onlineform[0].length ; i++) { // this should match loop above
	for (a=1; a < onlineform[i].length; a++) {  
		for (b=1; b < onlineform[i][a].length; b++)  { 
			fieldname = onlineform[i][a][b][0];
			quantity =  getField2(fieldname);
			if (quantity) {
				var codebit = fieldname.substring(0,6)
				if(codebit == "XXYYZZ") {
	        			fieldname = fieldname.substring(6)
				}
				var code = fieldname.replace(/\/'/g, "'"); // was onlineform[i][a][b][0]
			   	var desc = onlineform[i][a][b][1].replace(/\/'/g, "'");
				var fieldname2 = fieldname + ":"    // this to add : to format field names for transmission
			   	orders[fieldname] = getRowHTML(fieldname2, quantity, code, desc);
			} 
		}
	}
}
for (i in orders)
{
  submitWindow.document.write(orders[i]);
}

submitWindow.document.write( "\n" + "</table>");
submitWindow.document.write("\n" + "</td></tr></table>");
submitWindow.document.write("\n" + "<p align='left'>&nbsp;</p>");
submitWindow.document.write("\n" + "<p align='left'><b>Please be patient when you submit your order as, depending on your type of connection and connection speed, there may be a slight delay before your order is confirmed.</b></p>");
submitWindow.document.write("\n" + "<p align='left'>&nbsp;</p>");
submitWindow.document.write("\n" + "<table width='589'>");
submitWindow.document.write("\n" + "<tr>");
submitWindow.document.write("\n" + "<td>");
submitWindow.document.write("\n" + "<div align='center'>");
submitWindow.document.write("\n" + "<input type='reset' name='reset' value='Re-Order' onClick='window.close()'>");
submitWindow.document.write("\n" + "</div>");
submitWindow.document.write("\n" + "</td>");
submitWindow.document.write("\n" + "<td>");
submitWindow.document.write("\n" + "<div align='center'>");
submitWindow.document.write("\n" + "<input type='button' name='print' value='Print' onClick='print_it()'>");
submitWindow.document.write("\n" + "</div>");
submitWindow.document.write("\n" + "<td>");
submitWindow.document.write("\n" + "<div align='center'>");
submitWindow.document.write("\n" + "<input type='submit' name='submit' value='Submit'>");
submitWindow.document.write("\n" + "</div>");
submitWindow.document.write("\n" + "</td>");
submitWindow.document.write("\n" + "</tr></table>");
submitWindow.document.write("\n" + "</form>");
submitWindow.document.write("\n" + "</tr></td></table>");
submitWindow.document.write("\n" +"</body></html>");
submitWindow.document.close();
}


