// JavaScript Document

//alert("global lib linked")

// function to populate menus with valid dates
function updateMenus (num) {

	var monthDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
	var combo = new Array();
	
	combo[0] = new Array('dobDateMonth','dobDateDay','dobDateYear');

	var n = eval("document.forms[0]." + combo[num][0] + ".selectedIndex");
	//alert (document.forms[0].dobdateday.options[document.forms[0].dobdateday.options.selectedIndex].value)
	var year = eval("document.forms[0]." + combo[num][2] + ".options[document.forms[0]." + combo[num][2] + ".options.selectedIndex].value");
	
	if (LeapYear(year)) {
   	monthDays[1] = 29;
   	} else {
   	monthDays[1] = 28;
    }

	var numDays = monthDays[n];

	eval("document.forms[0]." + combo[num][1] + ".length = numDays");

	for (var x = 0; x < 9; x++)
	{
		eval("document.forms[0]." + combo[num][1] + ".options[x].text = \"0\" + (x+1)");
		eval("document.forms[0]." + combo[num][1] + ".options[x].value = \"0\" + (x+1)"); 
	}
	
	for (var x = 9; x < numDays; x++)
	{
		eval("document.forms[0]." + combo[num][1] + ".options[x].text = x+1");
		eval("document.forms[0]." + combo[num][1] + ".options[x].value = x+1"); 
	}

}

// function to check for leap year for date functions
function LeapYear(year) { // returns true only if year is a leap year.
    if ((year/4)   != Math.floor(year/4))   return false; // Generally leap years are exactly divisable by four.
    if ((year/100) != Math.floor(year/100)) return true;
    if ((year/400) != Math.floor(year/400)) return false;
    return true;
}

// function to check for values in all form fields when page loads
// this can be used to check if any changes have been made

var openingNamesArr = new Array()
var openingValsArr = new Array()

function getChanges() {
 //for each element on this form
 var changeStr = ""
 
 for (z=0; z<document.forms[0].length; z++) {

 	thisName = document.forms[0][z].name
	thisVal = document.forms[0][z].value
	thisFieldType = document.forms[0][z].type

	//if(thisName != 'Updatedby_num' && thisName != 'DateUpdated_num') {
	
		thisType = thisName.split("_")
		thisType = thisType[thisType.length-1]+""
		
		alert(thisType)
	
 		if(thisType == 'num') {
			//could be a checkbox with true or false or a number
			if(!isNaN(thisVal)) {
				for(x=0;x<openingNamesArr.length;x++) {//find name in array
					if((openingNamesArr[x]) == (thisName)) {//has the numerical value changed
						if(parseFloat(openingValsArr[x]) != parseFloat(thisVal) ){
							changeStr += "The value in field "+ thisName +" has changed since the last time this Quotation was saved\n\n"
						}
					}
				}
			} else {
				for(x=0;x<openingNamesArr.length;x++) {//find name in array
					if((openingNamesArr[x]) == (thisName)) {//has the checkbox value changed
						if(openingValsArr[x] != thisVal ){
							changeStr += "The value in field "+ thisName +" has changed since the last time this Quotation was saved\n\n"	
						}
					}
				}
			}
		}



 		if(thisType == 'str') {
			for(x=0;x<openingNamesArr.length;x++) {//find name in array
				if((openingNamesArr[x]) == thisName) {//has the text value changed
					//we have 2 possible matches
					//regular text fields single line
					if(thisFieldType == 'text'){
						if(thisVal != openingValsArr[x]) {		
							changeStr += "The value in field "+ thisName +" has changed since the last time this Quotation was saved\n"
							changeStr += "Value was \n'"+ openingValsArr[x]+"'\n and is now \n '"+ thisVal+"'\n\n"
						}
					} else {//multi line text fields with replaced line breaks
						if(thisVal != openingValsArr[x]) {
							changeStr += "The value in field "+ thisName +" has changed since the last time this Quotation was saved\n"
							changeStr += "Value was \n'"+ openingValsArr[x]+"'\n and is now \n '"+ thisVal+"'\n\n"
						}
					}
				}
			}
		}
		
		
		
 		if(thisType == 'date') {
			for(x=0;x<openingNamesArr.length;x++) {//find name in array
				if((openingNamesArr[x]) == (thisName)) {//has the date value changed
					if(openingValsArr[x] != thisVal ){
						changeStr += "The value in field "+ thisName +" has changed since the last time this Quotation was saved\n\n" 
					}
				}
			}
		}
		
 	}
	
	
		//alert(changeStr)

		if(changeStr != '') {
			var msg = "The Information on this screen has changed since the page was opened\n\nDo you want to save changes\n\n"
			//alert(changeStr)
			if(confirm(msg)) {
				//document.forms[0].changesField.value = changeStr
				if(validateInput()) {
					return true;
				} else {
					return false;
				}
			}
			
		} 

}

function getChanges2() {
	//alert("Looking for changes")
 //for each element on this form
 var changeStr = ""
 
 for (z=0; z<document.forms[0].length; z++) {

 	thisName = document.forms[0][z].name
	thisVal = document.forms[0][z].value
	thisFieldType = document.forms[0][z].type
	
	//alert(thisName)
		  
	for(x=0;x<openingNamesArr.length;x++) {//find name in array
		if((openingNamesArr[x]) == thisName) {//has the text value changed
			//we have 2 possible matches
			//regular text fields single line
			if(thisFieldType == 'text'){
				if(thisVal != openingValsArr[x]) {		
					changeStr += "The value in field "+ thisName +" has changed since the last time this Quotation was saved\n"
					changeStr += "Value was \n'"+ openingValsArr[x]+"'\n and is now \n '"+ thisVal+"'\n\n"
				}
			} else {//multi line text fields with replaced line breaks
				if(thisVal != openingValsArr[x]) {
					changeStr += "The value in field "+ thisName +" has changed since the last time this Quotation was saved\n"
					changeStr += "Value was \n'"+ openingValsArr[x]+"'\n and is now \n '"+ thisVal+"'\n\n"
				}
			}
		}
	}
 }
 
		//alert(changeStr)

		if(changeStr != '') {
			var msg = "The Information on this screen has changed since the page was opened\n\nDo you want to save changes\n\n"
			//alert(changeStr)
			if(confirm(msg)) {
				//document.forms[0].changesField.value = changeStr
				if(validateInput()) {
					return true;
				} else {
					return false;
				}
			}
			
		} 
	
}

/////////////////////////////////////////////////////////////////////////////
// function to output properly formated currency values to 2 decimal places//
/////////////////////////////////////////////////////////////////////////////
	function formatCurrency(inputNum, commas) {
	
		inputNum = parseFloat(inputNum)
		
		if (isNaN(inputNum)) { 
			inputNum = 0 
		}
			
		x = round(inputNum).toString();
		OutputNum = x
		
		//out put comma delimited currencies
		if(commas == true) {
			//does the number include a decimal point already
			if(OutputNum.search(/\./i) == -1){//no decimal point so we add
				currLength = OutputNum.length
				xtraDigits = ".00"
				//DEBUG("a----"+currLength)
			} else {//must be a decimal point
				xtraDigits = "."+OutputNum.split(".")[1]
				OutputNum = OutputNum.split(".")[0]
				currLength = OutputNum.length
				//DEBUG(xtraDigits)
				//DEBUG("b----"+currLength)
			}
		
			
		
			if (currLength > 3) {
				if(currLength == 4) {
					OutputNum = OutputNum.substr(0,1)+","+OutputNum.substr(1,currLength-1)+xtraDigits
				}
				if(currLength == 5) {
					OutputNum = OutputNum.substr(0,2)+","+OutputNum.substr(2,currLength-1)+xtraDigits
				}
				if(currLength == 6) {
					OutputNum = OutputNum.substr(0,3)+","+OutputNum.substr(3,currLength-1)+xtraDigits
				}
				if(currLength == 7) {
					OutputNum = OutputNum.substr(0,1)+","+ OutputNum.substr(1,3)+","+OutputNum.substr(4,currLength-1)+xtraDigits
				}
				if(currLength == 8) {
					OutputNum = OutputNum.substr(0,2)+","+ OutputNum.substr(2,3)+","+OutputNum.substr(5,currLength-1)+xtraDigits
				}
			}
		}

		//DEBUG(OutputNum)


 		y = OutputNum.split(".");
 		if(y[1]) {//number contains decimal point
  			a = y[1].length;
  				if (a == 1) {
  					OutputNum = OutputNum + "0";
	 			}
	 	} else {
	 			OutputNum = OutputNum + ".00";
	 	}
		return OutputNum;
	}

///////////////////////////////
//display to 2 decimal places//
///////////////////////////////
	function round(x) {
		return Math.round(x*100)/100;
	}

function IsNumeric(sText) {
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;
 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
}

function checkPCode (toCheck) {
	//alert("Checking Postcode")
  // 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 = toCheck;

  // 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) {return postCode;} else return false;
}
