///////////////////////////////////////////////////////
// LOCAL VARIABLES / CONSTANTS                       ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////

var interval;					// store the timer obj ref
var IorTB=0;					// intro ducer or TB
var OSRecCount;					// current number of OS Pending Policies
//var calc_head = 105;			// grid header height
//var calc_head = 165;			// grid header height
var calc_head = 185;			// grid header height
var calc_row = 28;				// grid row height
var page_sizze = 20;			// current page size
var currPage = 1;				// current page number
var MorF=0;						// manual or from file
var lastFormat="AUTO DETECT";	// the last format used for import
var bStartUp="T";				// flag still initialising
var bNewPageSize="F";			// flag save new page size
var bRegistered;				// store whether is registered
var bDoneAlreadyUFuckingShiteProgram;
var iManualAddCnt=0;            // count up number added in this session

///////////////////////////////////////////////////////
// CHANGE INPUT TYPE FUNCs                           ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////

// hide one div + show another
function showHide(hidethisDiv,showthisDiv)  {
	document.getElementById(showthisDiv).style.display="block";
	document.getElementById(hidethisDiv).style.display="none";
}

// set the form to Introducer
function setIntroducer(bDontRefreshYet) {
	document.getElementById('tradebonusM').style.display='none'; 
	IorTB=0;
	if (bStartUp == "F") {
		getExistingOSRecCountFTID();	
	}

	AddManualPolicy(1);
}

// set the form to TB
function setTradeBonus(bDontRefreshYet) {
	document.getElementById('tradebonusM').style.display='block'; 
	IorTB=1;
	if (bStartUp == "F") { 
		getExistingOSRecCountFTID();	 
	}

	AddManualPolicy(1);
}

// set manual load
function setManual() {
	MorF=0;
	showHide('fromfile','manual');
	clearInterval(interval);
}

// set load from file
function setFromFile() {
	MorF=1;
	showHide('manual','fromfile');	
	document.getElementById("browseForFile").innerHTML = "<iframe src=upload.aspx?FTID=" + MySession + " name=upload id=upload width=100% height=80px scrolling=no frameborder=no></iframe>";
    //window.setTimeout("startFileCheck()",5000);  // delay start so that the upload iframe is loaded
	bDoneAlreadyUFuckingShiteProgram = "F";
}

function delayStartFileCheck() {
    document.getElementById("disable").style.display = "none";
	window.setTimeout("startFileCheck()",10000);
}

function startFileCheck() {
	interval = window.setInterval('checkFinishedLoad()', 1000); 
	
}

// set start up import mode
function setDefaultMode() {
	refreshLevelAnYears("MANUAL",DefCoverLevel,-1);
	refreshLevelAnYears("DEFAULT",DefCoverLevel,-1);
	document.getElementById("manualStatus").style.display = "none";

    if (MyAssocPolType == 2) { 
        setTradeBonus(); 
    } else {
        setIntroducer();
    }
  
	if (whichIsSelected("rdMode") == "Load Policies From File") {
		setFromFile();
	} else if (whichIsSelected("rdMode") == "Manual Policy Entry") {
		setManual();
	}

	// show login screen, if 1st load
	if (MyLogin == "") {		
		document.getElementById("manual").style.display = "none";
		document.getElementById("fromfile").style.display = "none";
		registerNewUser("T");
		attemptLogin("T");
		sIsFTIDRegistered();		
	} else {
		checkForDelete();
		if (MyLogin == "SUPER") { // check for an existing reject file
			check4RejectFile();
		}
	}
	bStartUp = "F";	
}

// check for an existing reject file
function check4RejectFile() {
	index.check4RejectFile(MySession, callback_check4RejectFile);
}
function callback_check4RejectFile(res) {
	if (res.value == "T") {
		document.getElementById("rejectDownload").innerHTML = 
			"<b>or</b> Click <a href=./upload/" + MySession + "_rejected.csv>here</a> to download the last reject file.";
	}
}

// return which radio/checkbox is selected
function whichIsSelected(control) {
	var returnVal = "NULL";
	var list = document.getElementById(control);

	var options = list.getElementsByTagName("input");
	for (x = 0; x < options.length; ++x) {
		if (options[x].type == "radio" && options[x].checked ) {
			returnVal = options[x].value;
			break;
		}
	}
	return returnVal;
}

// refresh trade and cover levels combo z
function refreshLevelAnYears(type, iLevel, iYears) { 
	if (type == "MANUAL") {
		document.getElementById("mCoverYears").innerHTML = "<iframe src=coveryears.aspx?TRADE=" + 
		document.getElementById("lstWorkType").value + "&DEF=" + iYears + "&FROM=MANUAL&FTID=" + MySession +
		" name=manualYearsFrame id=manualYearsFrame width=60px height=22px scrolling=none frameborder=no></iframe>";

		document.getElementById("mCoverLevel").innerHTML = "<iframe src=coverlevel.aspx?TRADE=" + 
		document.getElementById("lstWorkType").value + "&TYPE=2" + "&DEF=" + iLevel + 
		    "&FTID=" + MySession + "&YEARS=" + iYears + 
		    " name=manualLevelFrame id=manualLevelFrame width=147px height=22px scrolling=none frameborder=no></iframe>";

		// extra detail boxes dependant on trade type
		var t = document.getElementById("lstWorkType").value;
		//sarnafil
		if (t == 117) {
		    document.getElementById("showSarnafilDetail").style.display = "block";
		} else {
	    	document.getElementById("showSarnafilDetail").style.display = "none";
		}
	    
	    if (t == 86 || t == 120 || t == 124) {
	        document.getElementById("chkFENSAOutBound").checked = true;
	        document.getElementById("FENSARelevent").style.display = "block";
	        document.getElementById("showWindowsNDoorz").style.display = "block";	 
	    } else { 
	        document.getElementById("chkFENSAOutBound").checked = false;
	        document.getElementById("FENSARelevent").style.display = "none";
	        document.getElementById("showWindowsNDoorz").style.display = "none";
	    }
	    document.getElementById("txtWindows").value = "0";
	    document.getElementById("txtDoors").value = "0";
	} else {  // refresh defaults
		document.getElementById("mDefaultYears").innerHTML = "<iframe src=coveryears.aspx?TRADE=" + 
		document.getElementById("cboDefaultTrade").value + "&DEF=" + iYears + "&FROM=DEFAULT&FTID=" + MySession +
		    " name=defaultYearsFrame id=defaultYearsFrame width=60px height=22px scrolling=none frameborder=no></iframe>";

		document.getElementById("mDefaultLevel").innerHTML = "<iframe src=coverlevel.aspx?TRADE=" + 
		document.getElementById("cboDefaultTrade").value + "&TYPE=2" + "&DEF=" + iLevel + 
		    "&FTID=" + MySession + "&YEARS=" + iYears +
		    " name=defaultLevelFrame id=defaultLevelFrame width=147px height=22px scrolling=none frameborder=no></iframe>";
	} 
}

///////////////////////////////////////////////////////
// PAF SEARCH                          ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////
// type
// 0 NORMAL (installation)
// 1 WORK

function PAFSearch(type) {
    var postCode 
    var houseNo

    //clear other fields/get fields
    if (type == 0) {
    postCode = document.getElementById("txtPostCode").value;
    houseNo = document.getElementById("txtAddress1").value;
    
    document.getElementById("txtAddress1").value = "";
    document.getElementById("txtAddress2").value = "";
    document.getElementById("txtAddress3").value = "";
    document.getElementById("txtTown").value = "";
    document.getElementById("txtCounty").value = "";}
    else {  //work
    postCode = document.getElementById("txtWorkPostCode").value;
    houseNo = document.getElementById("txtWorkAddress1").value;
    
    document.getElementById("txtWorkAddress1").value = "";
    document.getElementById("txtWorkAddress2").value = "";
    document.getElementById("txtWorkAddress3").value = "";
    document.getElementById("txtWorkTown").value = "";
    document.getElementById("txtWorkCounty").value = "";  
    }
    
    if (postCode.length < 5) {
        alert("Invalid Postcode, please complete");
    } else {
    
        //Valid so run PAF search
        if (houseNo.length < 1) { 
            houseNo = "-1"
        } else {
            houseNo = houseNo.substr(0,10)
        }   
        
        if (type == 0) {
        document.getElementById("DIVtxtAddress1").style.display = "none";
        document.getElementById("cboPAFAddressesTd").innerHTML = "<div id='DIVcboPAFAddresses' style='display:none'><SELECT name='cboPAFAddresses' id='cboPAFAddresses'><OPTION>Loading...</OPTION></SELECT></div>";
        document.getElementById("cboPAFAddresses").disabled  = true;}
        else { //work
        document.getElementById("DIVtxtAddress1Work").style.display = "none";
        document.getElementById("cboPAFAddressesTdWork").innerHTML = "<div id='DIVcboPAFAddressesWork' style='display:none'><SELECT name='cboPAFAddressesWork' id='cboPAFAddressesWork'><OPTION>Loading...</OPTION></SELECT></div>";
        document.getElementById("cboPAFAddressesWork").disabled  = true;
        }       

        index.PAF_Search(postCode,houseNo,2,true, callback_PAFSearch);
    } //valid postcode
}

function cboPAFAddresses_focusGone(type) {
         //return address1 back to textbox display
         cboPAFAddresses_change(type);
         if (type == 0) {
         document.getElementById("DIVcboPAFAddresses").style.display = "none";
         document.getElementById("DIVtxtAddress1").style.display = "block";
         }
         else {
         document.getElementById("DIVcboPAFAddressesWork").style.display = "none";
         document.getElementById("DIVtxtAddress1Work").style.display = "block";
         }         
}

function callback_PAFSearch(res) {
    var ds = res.value;
    var noerror="ERROR";
    var type = 0; //default to normal
    
    //detect which search we're doing
    if (document.getElementById("cboPAFAddressesWork").disabled == true) {
        type = 1;
    }
      
    if (ds != null && typeof(ds) == "object" && ds.Tables != null)  {    
             noerror = "NOPE";
             var s="";
                try {
                noerror = ds.Tables[0].Rows[0].ERROR;  
                if (typeof(noerror) == "undefined") noerror = "NOPE";
                } catch(e) { noerror="NOPE"; }
                 if (ds != null && typeof(ds) == "object" && ds.Tables != null && noerror == "NOPE")  { 
                    //check for results    
                     if (ds.Tables[0].Rows.length == 0 || noerror == "ERROR") {
                     alert("Record not found, please check your details.");
                     }
                     else {
//                        for (var i=0; i<ds.Tables[0].Rows.length; i++) {
//                            s += "<option value='" + ds.Tables[0].Rows[i].FullAddress + "'>" + toProperCase(ds.Tables[0].Rows[i].AddressLine1) + "</option>";
//                        }
                        for (var i = 0; i < ds.Tables[0].Rows.length; i++) {
                            s += "<option value='" + ds.Tables[0].Rows[i].Id + "'>" + ds.Tables[0].Rows[i].Description + "</option>";
                        }
                     if (type == 0) {    
                     document.getElementById("cboPAFAddressesTd").innerHTML = "<div id='DIVcboPAFAddresses'><select name='cboPAFAddresses' id='cboPAFAddresses' onchange='cboPAFAddresses_change(0);' onfocusout='cboPAFAddresses_focusGone(0);'>" + s + "</select></div>";
                     document.getElementById("cboPAFAddresses").disabled = false;
                     document.getElementById("DIVtxtAddress1").style.display = "none";
                     document.getElementById("cboPAFAddresses").focus();}
                     else {
                     document.getElementById("cboPAFAddressesTdWork").innerHTML = "<div id='DIVcboPAFAddressesWork'><select name='cboPAFAddressesWork' id='cboPAFAddressesWork' onchange='cboPAFAddresses_change(1);' onfocusout='cboPAFAddresses_focusGone(1);'>" + s + "</select></div>";
                     document.getElementById("cboPAFAddressesWork").disabled = false;
                     document.getElementById("DIVtxtAddress1Work").style.display = "none";
                     document.getElementById("cboPAFAddressesWork").focus();
                     }
                     
                     //cboPAFAddresses_change(type); //display first set of data
                  } //got records
                }//try
    } //if null ds
    
    if (noerror == "ERROR") {
         alert("Postcode not found, please check your details.");
         if (type == 0) {
         document.getElementById("DIVcboPAFAddresses").style.display = "none";
         document.getElementById("DIVtxtAddress1").style.display = "block";}
         else {
         document.getElementById("DIVcboPAFAddressesWork").style.display = "none";
         document.getElementById("DIVtxtAddress1Work").style.display = "block";  
         }
     }
}

var lastType;
function cboPAFAddresses_change(type) {
    var selectedAddress
    if (type == 0) {
        selectedAddress = document.getElementById("cboPAFAddresses").options[document.getElementById("cboPAFAddresses").selectedIndex].value;
    } else {
        selectedAddress = document.getElementById("cboPAFAddressesWork").options[document.getElementById("cboPAFAddressesWork").selectedIndex].value;
    }
    lastType = type;
    index.dsPAFSearch_Specific(selectedAddress, callback_PAFSearch_Specific);
    
//    var i = 0, m = 0, idx = 0;
//    var line = 1;
//    var str = "";
//        
//    if (selectedAddress.length > 0) {
//        do {
//             idx = selectedAddress.indexOf("$",m); //get next position (line)
// 
//             //grab the address line
//             if ( ((idx-m) > 2) ) {
//                str = selectedAddress.substr(m,idx-m);
//             } else {str = "";}             
//             
//             //get next position
//             if (idx > -1) {
//                m = idx+1; //move pointer
//             } else {
//                selectedAddress.length;} //end
//                
//             //format the string
//             if ((line !=4) && (str.length > 0)){
//                str = toProperCase(str);
//             }
//                if (type == 0) {    
//                switch (line) {
//                    case 1 :
//                         document.getElementById("txtAddress1").value = str;
//                         break;
//                    case 2 :
//                         document.getElementById("txtAddress2").value = str;
//                         break;
//                    case 3 :
//                         document.getElementById("txtAddress3").value = str;
//                         break;     
//                    case 4 :
//                         document.getElementById("txtTown").value = str;
//                         break;    
//                    case 5 :
//                         document.getElementById("txtCounty").value = str;
//                         break;                        
//                    default :
//                         m+=1;
//                 } //switch
//                 } else { //work
//                 switch (line) {
//                    case 1 :
//                         document.getElementById("txtWorkAddress1").value = str;
//                         break;
//                    case 2 :
//                         document.getElementById("txtWorkAddress2").value = str;
//                         break;
//                    case 3 :
//                         document.getElementById("txtWorkAddress3").value = str;
//                         break;     
//                    case 4 :
//                         document.getElementById("txtWorkTown").value = str;
//                         break;    
//                    case 5 :
//                         document.getElementById("txtWorkCounty").value = str;
//                         break;                        
//                    default :
//                         m+=1;
//                 } //switch
//                 } //work or not type
//                         
//             line+=1; //next address line       
//          
//        } //do
//        while (m<selectedAddress.length&&line<=5);        
//        
//        if (type == 0) {    
//        document.getElementById("txtPostCode").value = document.getElementById("txtPostCode").value.toUpperCase(); //upper postcode
//        } else {
//        document.getElementById("txtWorkPostCode").value = document.getElementById("txtWorkPostCode").value.toUpperCase(); //upper postcode
//        }
//    }   //if
}

function callback_PAFSearch_Specific(res) {
    var ds = res.value;
    if (ds != null && typeof (ds) == "object" && ds.Tables != null) {    
        //check for results    
        if (ds.Tables[0].Rows.length == 0) {
            alert("Record not found, please check your details.");
        } else {
            if (lastType == 0) {
                document.getElementById("txtAddress1").value = ds.Tables[0].Rows[0].Addr1;
                document.getElementById("txtAddress2").value = ds.Tables[0].Rows[0].Addr2;
                document.getElementById("txtAddress3").value = ds.Tables[0].Rows[0].Addr3;
                document.getElementById("txtTown").value = ds.Tables[0].Rows[0].PostTown;
                document.getElementById("txtCounty").value = ds.Tables[0].Rows[0].County;
                document.getElementById("txtPostCode").value = ds.Tables[0].Rows[0].PostCode;
                showHide("DIVcboPAFAddresses", "DIVtxtAddress1");
            } else {
                document.getElementById("txtWorkAddress1").value = ds.Tables[0].Rows[0].Addr1;
                document.getElementById("txtWorkAddress2").value = ds.Tables[0].Rows[0].Addr2;
                document.getElementById("txtWorkAddress3").value = ds.Tables[0].Rows[0].Addr3;
                document.getElementById("txtWorkTown").value = ds.Tables[0].Rows[0].PostTown;
                document.getElementById("txtWorkCounty").value = ds.Tables[0].Rows[0].County;
                document.getElementById("txtWorkPostCode").value = ds.Tables[0].Rows[0].PostCode;
                showHide("DIVcboPAFAddressesWork", "DIVtxtAddress1Work");
            }
        } 
    }
}

///////////////////////////////////////////////////////
// LOAD FROM CSV FILE STUFF                          ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////

// check for uploaded file completion
function checkFinishedLoad() {
	if (frames['upload'].document.links.length==0) {  // no links, file has been uploaded
		clearInterval(interval);		
		
		if (bDoneAlreadyUFuckingShiteProgram == "F") {
		    validateCSV();	
		    bDoneAlreadyUFuckingShiteProgram = "T";
		}    
	} 
}

// validate the imported file
var bValidationPassed;
function validateCSV()  {
	bValidationPassed = 0;
	document.getElementById("status").innerHTML = "<b>Validating File Contents</b>...<BR>";
	document.getElementById("policyType").style.display="none";
	document.getElementById("fileSelect").style.display="none";
    index.validateCSV(MySession, IorTB, callback_validateCSV);
}	



// process the validation results
function callback_validateCSV(res)  {
	var ds = res.value;
	
    if (ds != null && typeof(ds) == "object" && ds.Tables != null)  {
		// ensure interval loop is wiped out
		clearInterval(interval);
		document.getElementById("status").innerHTML = "";

		// show the check column form + errors
		document.getElementById("selColumns").style.display = "block";
		document.getElementById("colText").style.display = "block";
		document.getElementById("browseForFile").style.display="none";
		document.getElementById("fileDetails").style.display = "block";
		document.getElementById("disable").style.display = "none";

		var policyType;
		if (IorTB==0) {
			policyType = "Homeowner Direct (Introducer)";
		} else {
			policyType = "HomePro Insurance (Trade Bonus)";
		}

		if (document.getElementById("showFileDetails").innerHTML == "") {
			document.getElementById("showFileDetails").innerHTML = 
				"<table><tr><td class=steps><b>Import File</b></td><td class=steps id=ffpath>" + 
				frames['upload'].document.getElementById("fpath").innerHTML + "</td></tr>" + 
				"<tr><td class=steps><b>File Size</b></td><td class=steps id=ffsize>" +
				frames['upload'].document.getElementById("fsize").innerHTML + "</td></tr>" + 
				"<tr><td class=steps><b>Content</b></td><td class=steps id=fftype>" + 
				frames['upload'].document.getElementById("ftype").innerHTML + "</td></tr>" +
				"<tr><td class=steps><b>Policy Type</b></td><td class=steps>" + 
				policyType + "</td></tr></table>";
		}
		document.getElementById("fromfile").style.display="block";
		document.getElementById("add").style.display="none";
		if (IorTB == 1) {
			document.getElementById("nodefaults").style.display="none";
			document.getElementById("defaults").style.display="block";
		} else {
			document.getElementById("defaults").style.display="none";
			document.getElementById("nodefaults").style.display="block";
		}

		// process fields into form text boxes	
//alert(ds.Tables[0].Rows[0].ERR);  // enable if u wanna c the code behind errors
		addToForm(1, ds.Tables[0].Rows[0].col0, ds.Tables[0].Rows[0].type0,0);
		addToForm(2, ds.Tables[0].Rows[0].col1, ds.Tables[0].Rows[0].type1,0);
		addToForm(3, ds.Tables[0].Rows[0].col2, ds.Tables[0].Rows[0].type2,0);
		addToForm(4, ds.Tables[0].Rows[0].col3, ds.Tables[0].Rows[0].type3,0);
		addToForm(5, ds.Tables[0].Rows[0].col4, ds.Tables[0].Rows[0].type4,0);
		addToForm(6, ds.Tables[0].Rows[0].col5, ds.Tables[0].Rows[0].type5,0);
		addToForm(7, ds.Tables[0].Rows[0].col6, ds.Tables[0].Rows[0].type6,0);
		addToForm(8, ds.Tables[0].Rows[0].col7, ds.Tables[0].Rows[0].type7,0);
		addToForm(9, ds.Tables[0].Rows[0].col8, ds.Tables[0].Rows[0].type8,0);
		addToForm(10, ds.Tables[0].Rows[0].col9, ds.Tables[0].Rows[0].type9,0);
		addToForm(11, ds.Tables[0].Rows[0].col10, ds.Tables[0].Rows[0].type10,0);
		addToForm(12, ds.Tables[0].Rows[0].col11, ds.Tables[0].Rows[0].type11,0);
		addToForm(13, ds.Tables[0].Rows[0].col12, ds.Tables[0].Rows[0].type12,0);
		addToForm(14, ds.Tables[0].Rows[0].col13, ds.Tables[0].Rows[0].type13,0);
		addToForm(15, ds.Tables[0].Rows[0].col14, ds.Tables[0].Rows[0].type14,0);
		addToForm(16, ds.Tables[0].Rows[0].col15, ds.Tables[0].Rows[0].type15,0);
		addToForm(17, ds.Tables[0].Rows[0].col16, ds.Tables[0].Rows[0].type16,0);
		addToForm(18, ds.Tables[0].Rows[0].col17, ds.Tables[0].Rows[0].type17,0);
		addToForm(19, ds.Tables[0].Rows[0].col18, ds.Tables[0].Rows[0].type18,0);
		addToForm(20, ds.Tables[0].Rows[0].col19, ds.Tables[0].Rows[0].type19,0);
		addToForm(21, ds.Tables[0].Rows[0].col20, ds.Tables[0].Rows[0].type20,0);
		addToForm(22, ds.Tables[0].Rows[0].col21, ds.Tables[0].Rows[0].type21,0);
		addToForm(23, ds.Tables[0].Rows[0].col22, ds.Tables[0].Rows[0].type22,0);
		addToForm(24, ds.Tables[0].Rows[0].col23, ds.Tables[0].Rows[0].type23,0);
		addToForm(25, ds.Tables[0].Rows[0].col24, ds.Tables[0].Rows[0].type24,0);
		addToForm(26, ds.Tables[0].Rows[0].col25, ds.Tables[0].Rows[0].type25,0);
		addToForm(27, ds.Tables[0].Rows[0].col26, ds.Tables[0].Rows[0].type26,0);
		addToForm(28, ds.Tables[0].Rows[0].col27, ds.Tables[0].Rows[0].type27,0);
		addToForm(29, ds.Tables[0].Rows[0].col28, ds.Tables[0].Rows[0].type28,0);
		addToForm(30, ds.Tables[0].Rows[0].col29, ds.Tables[0].Rows[0].type29,0);
		if (document.getElementById("cboFormats").value != "AUTO DETECT") {
			changeFormats();
		}

		checkColumns();	
    } else {  // bad dataset
		document.getElementById("browseForFile").style.display="none";
		document.getElementById("fileDetails").style.display = "block";

		var policyType;
		if (IorTB==0) {
			policyType = "Homeowner Direct (Introducer)";
		} else {
			policyType = "HomePro Insurance (Trade Bonus)";
		}

		document.getElementById("showFileDetails").innerHTML = 
			"<table><tr><td class=steps><b>Import File</b></td><td class=steps id=ffpath>" + 
			frames['upload'].document.getElementById("fpath").innerHTML + "</td></tr>" + 
			"<tr><td class=steps><b>File Size</b></td><td class=steps id=ffsize>" +
			frames['upload'].document.getElementById("fsize").innerHTML + "</td></tr>" + 
			"<tr><td class=steps><b>Content</b></td><td class=steps id=fftype>" + 
			frames['upload'].document.getElementById("ftype").innerHTML + "</td></tr>" +
			"<tr><td class=steps><b>Policy Type</b></td><td class=steps>" + 
			policyType + "</td></tr></table>";

		document.getElementById("status").innerHTML += "Internal Error - Please try <a href=index.aspx>again</a>.<BR>";
		
		if (frames['upload'].document.getElementById("ftype").innerHTML == "application/vnd.ms-excel") {
			alert("The IBG Import ONLY accepts comma delemited files (*.CSV), this is an excel file.  To correct this problem, open this file in excel, choose SaveAs and change the save type to CSV. The form will now be reset.");
		} else {
			alert("The IBG Import ONLY accepts comma delemited files (*.CSV), the form will now be reset.");
		}
		document.location.reload();
    }
}

// update the form with values from file validation
function addToForm(index, data, type, justCols) {
	if (data != null) {
		if (justCols == 0) {
			// add another line 2 tha form
			document.getElementById("col" + index).style.display = "block";

			// display the text value from the file
			document.getElementById("Textbox" + index).value = data;	
		}
		
		// update the field type
		if (type == "PHONE" || type == "Contact Number") {
			document.getElementById("Dropdownlist" + index).value = "Contact Number"; 
		} else if (type == "#PHONE") {
			document.getElementById("Dropdownlist" + index).value = "Contact Number";
			document.getElementById("row" + index).style.backgroundColor = "RED";
		} else if (type == "PCODE1" || type == "PostCode") {
			document.getElementById("Dropdownlist" + index).value = "PostCode"; 
		} else if (type == "PCODE2" || type == "PostCode (Work)") {
			document.getElementById("Dropdownlist" + index).value = "PostCode (Work)"; 
		} else if (type == "#PCODE") {
			document.getElementById("Dropdownlist" + index).value = "PostCode";
			document.getElementById("row" + index).style.backgroundColor = "RED";
		} else if (type == "SDATE" || type == "Start Date") {
			document.getElementById("Dropdownlist" + index).value = "Start Date"; 
		} else if (type == "EDATE" || type == "End Date") {
			document.getElementById("Dropdownlist" + index).value = "End Date"; 
		} else if (type == "#DATE") {
			document.getElementById("Dropdownlist" + index).value = "Start Date";
			document.getElementById("row" + index).style.backgroundColor = "RED";
		} else if (type == "FULLNAME" || type == "Full Name") {
			document.getElementById("Dropdownlist" + index).value = "Full Name"; 
		} else if (type == "#FULLNAME") {
			document.getElementById("Dropdownlist" + index).value = "Full Name";
			document.getElementById("row" + index).style.backgroundColor = "RED";
		} else if (type == "TITLE" || type == "Title") {
			document.getElementById("Dropdownlist" + index).value = "Title"; 
		} else if (type == "#TITLE") {
			document.getElementById("Dropdownlist" + index).value = "Title";
			document.getElementById("row" + index).style.backgroundColor = "RED";
		} else if (type == "VALUE" || type == "Value") {
			document.getElementById("Dropdownlist" + index).value = "Value"; 
		} else if (type == "#VALUE") {
			document.getElementById("Dropdownlist" + index).value = "Value";
			document.getElementById("row" + index).style.backgroundColor = "RED";
		} else if (type == "ADDR11" || type == "Address Line 1") {
			document.getElementById("Dropdownlist" + index).value = "Address Line 1"; 
		} else if (type == "ADDR21" || type == "Address Line 2") {
			document.getElementById("Dropdownlist" + index).value = "Address Line 2"; 
		} else if (type == "ADDR31" || type == "Address Line 3") {
			document.getElementById("Dropdownlist" + index).value = "Address Line 3"; 
		} else if (type == "ADDR12" || type == "Address Line 1 (Work)") {
			document.getElementById("Dropdownlist" + index).value = "Address Line 1 (Work)"; 
		} else if (type == "ADDR22" || type == "Address Line 2 (Work)") {
			document.getElementById("Dropdownlist" + index).value = "Address Line 2 (Work)"; 
		} else if (type == "ADDR32" || type == "Address Line 3 (Work)") {
			document.getElementById("Dropdownlist" + index).value = "Address Line 3 (Work)"; 
		} else if (type == "#ADDR1") {
			document.getElementById("Dropdownlist" + index).value = "Address Line 1";
			document.getElementById("row" + index).style.backgroundColor = "RED";
		} else if (type == "ADDRTOWN1" || type == "Town") {
			document.getElementById("Dropdownlist" + index).value = "Town"; 
		} else if (type == "ADDRCOUNTY1" || type == "County") {
			document.getElementById("Dropdownlist" + index).value = "County"; 
		} else if (type == "ADDRTOWN2" || type == "Town (Work)") {
			document.getElementById("Dropdownlist" + index).value = "Town (Work)"; 
		} else if (type == "ADDRCOUNTY2" || type == "County (Work)") {
			document.getElementById("Dropdownlist" + index).value = "County (Work)"; 
		} else if (type == "FORENAME" || type == "First Name(s)") {
			document.getElementById("Dropdownlist" + index).value = "First Name(s)"; 
		} else if (type == "LASTNAME" || type == "Last Name") {
			document.getElementById("Dropdownlist" + index).value = "Last Name"; 
		} else if (type == "NAME" || type == "Name") {
			document.getElementById("Dropdownlist" + index).value = "Full Name"; 
		} else if (type == "EMAIL" || type == "Email Address") {
			document.getElementById("Dropdownlist" + index).value = "Email Address"; 
		} else if (type == "WINDOWS" || type == "Num Windows") {
			document.getElementById("Dropdownlist" + index).value = "Num Windows"; 
		} else if (type == "DOORS" || type == "Num Doors") {
			document.getElementById("Dropdownlist" + index).value = "Num Doors"; 
		} else {
			document.getElementById("Dropdownlist" + index).value = "IGNORE THIS COLUMN";
		}
	}
}

// generate warnings as the column order is changed
function checkColumns() {
	var iTitle = new Array();
	var iFirstNames = new Array();
	var iLastName = new Array();
	var iName = new Array();
	var iFullName = new Array();
	var iAddressLine1 = new Array();
	var iAddressLine2 = new Array();
	var iAddressLine3 = new Array();
	var iTown = new Array();
	var iCounty = new Array();
	var iPostCode = new Array();
	var iContactNumber = new Array();
	var iAddressLine1Work = new Array();
	var iAddressLine2Work = new Array();
	var iAddressLine3Work = new Array();
	var iTownWork = new Array();
	var iCountyWork = new Array();
	var iPostCodeWork = new Array();
	var iValue = new Array();
	var iStartDate = new Array();
	var iEndDate = new Array();
	var iEmail = new Array();
	var iWindows = new Array();
	var iDoors = new Array();

	// count number of each type of field
	for (var i=1; i<=30; i++)  { 
		switch (document.getElementById("Dropdownlist" + i).value) {
		case "Title":
			iTitle[iTitle.length] = i;
			break;
		case "First Name(s)":
			iFirstNames[iFirstNames.length] = i;
			break;
		case "Last Name":
			iLastName[iLastName.length] = i;
			break;
		case "Name":
			iName[iName.length] = i;
			break;
		case "Full Name":
			iFullName[iFullName.length] = i;
			break;
		case "Address Line 1":
			iAddressLine1[iAddressLine1.length] = i;
			break;
		case "Address Line 2":
			iAddressLine2[iAddressLine2.length] = i;
			break;
		case "Address Line 3":
			iAddressLine3[iAddressLine3.length] = i;
			break;
		case "Town":
			iTown[iTown.length] = i;
			break;
		case "County":
			iCounty[iCounty.length] = i;
			break;
		case "PostCode":
			iPostCode[iPostCode.length] = i;
			break;
		case "Contact Number":
			iContactNumber[iContactNumber.length] = i;
			break;
		case "Address Line 1 (Work)":
			iAddressLine1Work[iAddressLine1Work.length] = i;
			break;
		case "Address Line 2 (Work)":
			iAddressLine2Work[iAddressLine2Work.length] = i;
			break;
		case "Address Line 3 (Work)":
			iAddressLine3Work[iAddressLine3Work.length] = i;
			break;
		case "Town (Work)":
			iTownWork[iTownWork.length] = i;
			break;
		case "County (Work)":
			iCountyWork[iCountyWork.length] = i;
			break;
		case "PostCode (Work)":
			iPostCodeWork[iPostCodeWork.length] = i;
			break;
		case "Value":
			iValue[iValue.length] = i;
			break;
		case "Start Date":
			iStartDate[iStartDate.length] = i;
			break;
		case "End Date":
			iEndDate[iEndDate.length] = i;
			break;
		case "Email Address":
			iEmail[iEmail.length] = i;
			break;
		case "Num Windows":
			iWindows[iWindows.length] = i;
			break;
		case "Num Doors":
			iDoors[iDoors.length] = i;
			break;
		}
	}

	// re init the status div
	document.getElementById("status").innerHTML = "";

	// clear all previously RED columns
	for (var i=1; i<=30; i++)  { 
		document.getElementById("row" + i).style.backgroundColor = "";
	}

	// check name columns
	if (iTitle.length == 0 && iFirstNames.length == 0 && iLastName.length == 0 && iFullName.length == 0 && iName.length == 0) {
		document.getElementById("status").innerHTML += "WARNING - Missing Name Columns.<BR>";
	} else {
		if (iTitle.length > 1) {
			document.getElementById("status").innerHTML += "WARNING - Extra Title Column(s), the Import file should ONLY have one Name.<BR>";
			for (var i=1; i<iTitle.length; i++)  { 
				document.getElementById("row" + iTitle[i]).style.backgroundColor = "RED";
			}
		}
		if (iFirstNames.length > 1) {
			document.getElementById("status").innerHTML += "WARNING - Extra First Name Column(s), the Import file should ONLY have one Name.<BR>";
			for (var i=1; i<iFirstNames.length; i++)  { 
				document.getElementById("row" + iFirstNames[i]).style.backgroundColor = "RED";
			}
		}
		if (iLastName.length > 1) {
			document.getElementById("status").innerHTML += "WARNING - Extra Last Name Column(s), the Import file should ONLY have one Name.<BR>";
			for (var i=1; i<iLastName.length; i++)  { 
				document.getElementById("row" + iLastName[i]).style.backgroundColor = "RED";
			}
		}
		if (iName.length > 1) {
			document.getElementById("status").innerHTML += "WARNING - Extra Name Column(s), the Import file should ONLY have one Name.<BR>";
			for (var i=1; i<iName.length; i++)  { 
				document.getElementById("row" + iName[i]).style.backgroundColor = "RED";
			}
		}
		if (iFullName.length > 1) {
			document.getElementById("status").innerHTML += "WARNING - Extra Full Name Column(s), the Import file should ONLY have one Name.<BR>";
			for (var i=1; i<iFullName.length; i++)  { 
				document.getElementById("row" + iFullName[i]).style.backgroundColor = "RED";
			}
		}
	}

	// check main address
	//if (iAddressLine1.length == 0 && iAddressLine2.length == 0 && iAddressLine3.length == 0 && iTown.length == 0 && iCounty.length == 0 && iPostCode.length == 0) {
	if (iAddressLine1.length == 0 && iTown.length == 0 && iPostCode.length == 0) {
		document.getElementById("status").innerHTML += "WARNING - Missing Main Address Columns.<BR>";
	} else {
		//if (iAddressLine1.length == 0 || iAddressLine2.length == 0 || iTown.length == 0 || iCounty.length == 0 || iPostCode.length == 0) {
		if (iAddressLine1.length == 0 || iTown.length == 0 || iPostCode.length == 0) {
			document.getElementById("status").innerHTML += "WARNING - Partial Main Address, Missing Columns.<BR>";
			if (iAddressLine1.length == 0) {
				document.getElementById("status").innerHTML += "WARNING - Missing Address Line 1 Column.<BR>";
			}
//			if (iAddressLine2.length == 0) {
//				document.getElementById("status").innerHTML += "WARNING - Missing Address Line 2 Column.<BR>";
//			}
			if (iTown.length == 0) {
				document.getElementBId("status").innerHTML += "WARNING - Missing Town Column.<BR>";
			}
//			if (iCounty.length == 0) {
//				document.getElementById("status").innerHTML += "WARNING - Missing County Column.<BR>";
//			}
			if (iPostCode.length == 0) {
				document.getElementById("status").innerHTML += "WARNING - Missing PostCode Column.<BR>";
			}
		}
		if (iAddressLine1.length > 1) {
			document.getElementById("status").innerHTML += "WARNING - Extra Address Line 1 Column(s), the Import file should ONLY have one Main Address.<BR>";
			for (var i=1; i<iAddressLine1.length; i++)  { 
				document.getElementById("row" + iAddressLine1[i]).style.backgroundColor = "RED";
			}
		}
		if (iAddressLine2.length > 1) {
			document.getElementById("status").innerHTML += "WARNING - Extra Address Line 2 Column(s), the Import file should ONLY have one Main Address.<BR>";
			for (var i=1; i<iAddressLine2.length; i++)  { 
				document.getElementById("row" + iAddressLine2[i]).style.backgroundColor = "RED";
			}
		}
		if (iAddressLine3.length > 1) {
			document.getElementById("status").innerHTML += "WARNING - Extra Address Line 3 Column(s), the Import file should ONLY have one Main Address.<BR>";
			for (var i=1; i<iAddressLine3.length; i++)  { 
				document.getElementById("row" + iAddressLine3[i]).style.backgroundColor = "RED";
			}
		}
		if (iTown.length > 1) {
			document.getElementById("status").innerHTML += "WARNING - Extra Town Column(s), the Import file should ONLY have one Main Address.<BR>";
			for (var i=1; i<iTown.length; i++)  { 
				document.getElementById("row" + iTown[i]).style.backgroundColor = "RED";
			}
		}
		if (iCounty.length > 1) {
			document.getElementById("status").innerHTML += "WARNING - Extra County Column(s), the Import file should ONLY have one Main Address.<BR>";
			for (var i=1; i<iCounty.length; i++)  { 
				document.getElementById("row" + iCounty[i]).style.backgroundColor = "RED";
			}
		}
		if (iPostCode.length > 1) {
			document.getElementById("status").innerHTML += "WARNING - Extra PostCode Column(s), the Import file should ONLY have one Main Address.<BR>";
			for (var i=1; i<iPostCode.length; i++)  { 
				document.getElementById("row" + iPostCode[i]).style.backgroundColor = "RED";
			}
		}
	}

	// check work address
	if (iAddressLine1Work.length == 0 && iAddressLine2Work.length == 0 && iAddressLine3Work.length == 0 && iTownWork.length == 0 && iCountyWork.length == 0 && iPostCodeWork.length == 0) {
		// ignore, work address not req
	} else {
//		if (iAddressLine1Work.length == 0 || iAddressLine2Work.length == 0 || iTownWork.length == 0 || iCountyWork.length == 0 || iPostCodeWork.length == 0) {
		if (iAddressLine1Work.length == 0 || iTownWork.length == 0 || iPostCodeWork.length == 0) {
			document.getElementById("status").innerHTML += "WARNING - Partial Work Address, Missing Columns.<BR>";
			if (iAddressLine1Work.length == 0) {
				document.getElementById("status").innerHTML += "WARNING - Missing Address Line 1 (Work) Column.<BR>";
			}
//			if (iAddressLine2Work.length == 0) {
//				document.getElementById("status").innerHTML += "WARNING - Missing Address Line 2 (Work) Column.<BR>";
//			}
			if (iTown.lengthWork == 0) {
				document.getElementById("status").innerHTML += "WARNING - Missing Town (Work) Column.<BR>";
			}
//			if (iCountyWork.length == 0) {
//				document.getElementById("status").innerHTML += "WARNING - Missing County (Work) Column.<BR>";
//			}
			if (iPostCodeWork.length == 0) {
				document.getElementById("status").innerHTML += "WARNING - Missing PostCode (Work) Column.<BR>";
			}
		}
		if (iAddressLine1Work.length > 1) {
			document.getElementById("status").innerHTML += "WARNING - Extra Address Line 1 (Work) Column(s), the Import file should ONLY have one Work Addr.<BR>";
			for (var i=1; i<iAddressLine1Work.length; i++)  { 
				document.getElementById("row" + iAddressLine1Work[i]).style.backgroundColor = "RED";
			}
		}
		if (iAddressLine2Work.length > 1) {
			document.getElementById("status").innerHTML += "WARNING - Extra Address Line 2 (Work) Column(s), the Import file should ONLY have one Work Addr.<BR>";
			for (var i=1; i<iAddressLine2Work.length; i++)  { 
				document.getElementById("row" + iAddressLine2Work[i]).style.backgroundColor = "RED";
			}
		}
		if (iAddressLine3Work.length > 1) {
			document.getElementById("status").innerHTML += "WARNING - Extra Address Line 3 (Work) Column(s), the Import file should ONLY have one Work Addr.<BR>";
			for (var i=1; i<iAddressLine3Work.length; i++)  { 
				document.getElementById("row" + iAddressLine3Work[i]).style.backgroundColor = "RED";
			}
		}
		if (iTownWork.length > 1) {
			document.getElementById("status").innerHTML += "WARNING - Extra Town (Work) Column(s), the Import file should ONLY have one Work Address.<BR>";
			for (var i=1; i<iTownWork.length; i++)  { 
				document.getElementById("row" + iTownWork[i]).style.backgroundColor = "RED";
			}
		}
		if (iCountyWork.length > 1) {
			document.getElementById("status").innerHTML += "WARNING - Extra County (Work) Column(s), the Import file should ONLY have one Work Address.<BR>";
			for (var i=1; i<iCountyWork.length; i++)  { 
				document.getElementById("row" + iCountyWork[i]).style.backgroundColor = "RED";
			}
		}
		if (iPostCodeWork.length > 1) {
			document.getElementById("status").innerHTML += "WARNING - Extra PostCode (Work) Column(s), the Import file should ONLY have one Work Address.<BR>";
			for (var i=1; i<iPostCodeWork.length; i++)  { 
				document.getElementById("row" + iPostCodeWork[i]).style.backgroundColor = "RED";
			}
		}
	}

	// check contact number column
//	if (iContactNumber.length == 0) {
//		document.getElementById("status").innerHTML += "WARNING - Missing Contact Number Column.<BR>";
//	} else 
	if (iContactNumber.length > 1) {
		document.getElementById("status").innerHTML += "WARNING - Extra Contact Number Column(s), the Import file should ONLY have one Contact Number.<BR>";
		for (var i=1; i<iContactNumber.length; i++)  { 
			document.getElementById("row" + iContactNumber[i]).style.backgroundColor = "RED";
		}
	}

	// check value column
	if (IorTB==1) { // trade bonus only cols
		if (iValue.length == 0) {
			document.getElementById("status").innerHTML += "WARNING - Missing Value Column.<BR>";
		} else if (iValue.length > 1) {
			document.getElementById("status").innerHTML += "WARNING - Extra Value Column(s), the Import file should ONLY have one Policy Value.<BR>";
			for (var i=1; i<iValue.length; i++)  { 
				document.getElementById("row" + iValue[i]).style.backgroundColor = "RED";
			}
		}

		// check start date column
		if (iStartDate.length == 0) {
			document.getElementById("status").innerHTML += "WARNING - Missing Start Date Column.<BR>";
		} else if (iStartDate.length > 1) {
			document.getElementById("status").innerHTML += "WARNING - Extra Start Date Column(s), the Import file should ONLY have one Start Date.<BR>";
			for (var i=1; i<iStartDate.length; i++)  { 
				document.getElementById("row" + iStartDate[i]).style.backgroundColor = "RED";
			}
		}

		// check end date column
		if (iEndDate.length == 0) {
			// document.getElementById("status").innerHTML += "WARNING - Missing End Date Column.<BR>";  end date not required
		} else if (iEndDate.length > 1) {
			document.getElementById("status").innerHTML += "WARNING - Extra End Date Column(s), the Import file should ONLY have one End Date.<BR>";
			for (var i=1; i<iEndDate.length; i++)  { 
				document.getElementById("row" + iEndDate[i]).style.backgroundColor = "RED";
			}
		}
	}
	
	// check email column
	if (iEmail.length == 0) {
		// document.getElementById("status").innerHTML += "WARNING - Missing End Date Column.<BR>";  end date not required
	} else if (iEmail.length > 1) {
		document.getElementById("status").innerHTML += "WARNING - Extra Email Address Column(s), the Import file should ONLY have one Email Address.<BR>";
		for (var i=1; i<iEmail.length; i++)  { 
			document.getElementById("row" + iEmail[i]).style.backgroundColor = "RED";
		}
	}
	
	// check window column (2many check
	if (iWindows.length > 1) {
		document.getElementById("status").innerHTML += "WARNING - Extra Num Windows Column(s), the Import file should ONLY have one Num Windows column.<BR>";
		for (var i=1; i<iWindows.length; i++)  { 
			document.getElementById("row" + iWindows[i]).style.backgroundColor = "RED";
		}
	}
	
	// check doors column (2many check
	if (iDoors.length > 1) {
		document.getElementById("status").innerHTML += "WARNING - Extra Num Doors Column(s), the Import file should ONLY have one Num Doors column.<BR>";
		for (var i=1; i<iWindows.length; i++)  { 
			document.getElementById("row" + iDoors[i]).style.backgroundColor = "RED";
		}
	}
	
	// check have both windows & doors if trade type double glazed
	if ( ((document.getElementById("cboDefaultTrade").value == 86) || (document.getElementById("cboDefaultTrade").value == 120) || (document.getElementById("cboDefaultTrade").value == 124)) && MyFENSAOutBoundYes == "block") {
	    if (iWindows.length == 0) {
		    document.getElementById("status").innerHTML += "WARNING - Missing Num Windows Column, required for FENSA Submission.<BR>";
		}
		if (iDoors.length == 0) {
		    document.getElementById("status").innerHTML += "WARNING - Missing Num Doors Column, required for FENSA Submission.<BR>";
		}
	}
	

	// see if validated OK
	if (document.getElementById("status").innerHTML == "") {
		bValidationPassed = 1;
	}
}

// process the upload file into www policy pending table
function loadCSVIntoSQL()  {
	var colTypes=""; 
	var defTradeType;
	var defCoverLevel;
	var defCoverYears;
	var defFormat;

	// build comma separated of all column types
	for (var i=1; i<=30; i++)  {
		colTypes += document.getElementById("Dropdownlist" + i).value + ",";
	}

	// grab the default trade etc 
	defTradeType = document.getElementById("cboDefaultTrade").value;	
	defCoverLevel = frames['defaultLevelFrame'].document.getElementById("lstLevel").value;
	defCoverYears = frames['defaultYearsFrame'].document.getElementById("lstYears").value;

	// swap column confirm form for loading file
	document.getElementById("colText").style.display="none";
	document.getElementById("selColumns").style.display="none";
	document.getElementById("loadingFile").style.display="block";

	// grab the import format 2 save
	if (IorTB == 1) {
		if (document.getElementById("cboSaveFormatTB").value == ".NEW FORMAT") {
			defFormat = document.getElementById("txtNewFormatTB").value;
		} else if (document.getElementById("cboSaveFormatTB").value == ".DON'T SAVE") {
			defFormat = "AUTO DETECT";
		} else {
			defFormat = document.getElementById("cboSaveFormatTB").value;
		}
	} else {
		if (document.getElementById("cboSaveFormatIntro").value == ".NEW FORMAT") {
			defFormat = document.getElementById("txtNewFormatIntro").value;
		} else if (document.getElementById("cboSaveFormatIntro").value == ".DON'T SAVE") {
			defFormat = "AUTO DETECT";
		} else {
			defFormat = document.getElementById("cboSaveFormatIntro").value;
		}
	}
	
	// check for training mode
	var trainOn=0;
	if (document.getElementById("chkTraining").checked == true) { trainOn=1; }
	
	// check for FENSA outbound
	var FENOUT=0;
	if (MyFENSAOutBoundYes == "block") { FENOUT=1; }

	// load the file into policy details
    index.loadCSVIntoSQL(MySession, colTypes, IorTB, defFormat, defTradeType,defCoverLevel,defCoverYears, trainOn, FENOUT, callback_loadCSVIntoSQL);
}	

// process the validation results
function callback_loadCSVIntoSQL(res)  {
	var ds = res.value;
    if (ds != null && typeof(ds) == "object" && ds.Tables != null)  {
		if (parseInt(ds.Tables[0].Rows[ds.Tables[0].Rows.length - 1].badrows) > 0) {
			document.getElementById("fromFileResults").style.display = "block";
			document.getElementById("fromFileResultsDisp").innerHTML = "<div class=steps><BR><center><font size=+1><b>Import Results</b></font><BR><b>" + ds.Tables[0].Rows[ds.Tables[0].Rows.length - 1].okrows + "</b> rows imported, <b>" + 
				ds.Tables[0].Rows[ds.Tables[0].Rows.length - 1].badrows + "</b> rows rejected.</center><BR><BR>" + 
				"Click <a href=./upload/" + MySession + "_rejected.csv>here</a> to save the rejected Policy Lines in CSV format, " + 
				"please correct the errors listed below and import the modified reject file." + 
				"<div><BR><table border=1 width=588px><tr><td align=center class=steps><b>Row</b></td><td class=steps><b>The CSV File contained Errors, these Policies have NOT been Imported.</b></td>" +
				ds.Tables[0].Rows[ds.Tables[0].Rows.length - 1].rowerrors + "</table></font>";
		} else {
			alert(ds.Tables[0].Rows[ds.Tables[0].Rows.length - 1].okrows + " rows imported, " + 
				ds.Tables[0].Rows[ds.Tables[0].Rows.length - 1].badrows + " rows rejected.");
			//history.go(0);
			//document.location.reload(); 
		    //window.location = "http://www.fairtrades.co.uk/IBGImport.aspx";
		    //setFromFile();
		    window.location=window.location; 
		}
	} else { 
		alert("INTERNAL ERROR - Unable to Load File with current column selection."); 
	}
}

///////////////////////////////////////////////////////
// MANUAL LOAD POLICY                                ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////

// validate and add the policy
function AddManualPolicy(dontAddJustValidate) {
	// validate input form
	document.getElementById("manualStatus").innerHTML = "";
	if (document.getElementById("txtLName").value.replace(" ","") == "") {
		document.getElementById("manualStatus").innerHTML += "WARNING - Empty Last Name Field.<BR>";
		document.getElementById("mRow1").style.backgroundColor = "RED";
	} else { document.getElementById("mRow1").style.backgroundColor = ""; }

//	if (document.getElementById("txtAddress1").value == "" || document.getElementById("txtAddress2").value == "" || document.getElementById("txtTown").value == "" || document.getElementById("txtCounty").value == "" || document.getElementById("txtPostCode").value == "") {
	if (document.getElementById("txtAddress1").value.replace(" ","") == "" || document.getElementById("txtTown").value.replace(" ","") == "" || document.getElementById("txtPostCode").value.replace(" ","") == "") {
		document.getElementById("manualStatus").innerHTML += "WARNING - Partial Address.<BR>";
	}
	if (document.getElementById("txtAddress1").value.replace(" ","") == "") {
		document.getElementById("manualStatus").innerHTML += "WARNING - Empty Address Line 1 Field.<BR>";
//		if (dontAddJustValidate == 0) {	
//		document.getElementById("mRow2").style.backgroundColor = "RED";}
	} else { document.getElementById("mRow2").style.backgroundColor = ""; }

//	if (document.getElementById("txtAddress2").value == "") {
//		document.getElementById("manualStatus").innerHTML += "WARNING - Empty Address Line 2 Field.<BR>";
//		document.getElementById("mRow3").style.backgroundColor = "RED";
//	} else { document.getElementById("mRow3").style.backgroundColor = ""; }

	if (document.getElementById("txtTown").value.replace(" ","") == "") {
		document.getElementById("manualStatus").innerHTML += "WARNING - Empty Town Field.<BR>";
		//document.getElementById("mRow4").style.backgroundColor = "RED";
	} else { document.getElementById("mRow4").style.backgroundColor = ""; }

//	if (document.getElementById("txtCounty").value == "") {
//		document.getElementById("manualStatus").innerHTML += "WARNING - Empty County Field.<BR>";
//		document.getElementById("mRow5").style.backgroundColor = "RED";
//	} else { document.getElementById("mRow5").style.backgroundColor = ""; }

	if (document.getElementById("txtPostCode").value.replace(" ","") == "") {
	    //alert(document.getElementById("txtPostCode").value.replace(" ",""));
		document.getElementById("manualStatus").innerHTML += "WARNING - Empty PostCode Field.<BR>";
		document.getElementById("mRow61").style.backgroundColor = "RED";
	} else { 
	    if (!postit(document.getElementById("txtPostCode").value)) {
	        document.getElementById("manualStatus").innerHTML += "WARNING - Invalid PostCode Field.<BR>";
	        document.getElementById("mRow61").style.backgroundColor = "RED";
	    } else {
	        document.getElementById("mRow61").style.backgroundColor = ""; 
	    }	    
	}

//	if (document.getElementById("txtDayPhone").value == "") {
//		document.getElementById("manualStatus").innerHTML += "WARNING - Empty Day Phone Field.<BR>";
//		document.getElementById("mRow62").style.backgroundColor = "RED";
//	} else { document.getElementById("mRow62").style.backgroundColor = ""; }

	if (document.getElementById("txtWorkAddress1").value.replace(" ","") != "" || document.getElementById("txtWorkAddress2").value.replace(" ","") != "" || document.getElementById("txtWorkTown").value.replace(" ","") != "" || document.getElementById("txtWorkCounty").value.replace(" ","") != "" || document.getElementById("txtWorkPostCode").value.replace(" ","") != "") {
//		if (document.getElementById("txtWorkAddress1").value == "" || document.getElementById("txtWorkAddress2").value == "" || document.getElementById("txtWorkTown").value == "" || document.getElementById("txtWorkCounty").value == "" || document.getElementById("txtWorkPostCode").value == "") {
		if (document.getElementById("txtWorkAddress1").value.replace(" ","") == "" || document.getElementById("txtWorkTown").value == "" || document.getElementById("txtWorkPostCode").value == "") {
			document.getElementById("manualStatus").innerHTML += "WARNING - Work Partial Address.<BR>";
		}
		if (document.getElementById("txtWorkAddress1").value.replace(" ","") == "") {
			document.getElementById("manualStatus").innerHTML += "WARNING - Empty Work Address Line 1 Field.<BR>";
			if (dontAddJustValidate == 0) {	
			document.getElementById("mRow7").style.backgroundColor = "RED";}
		} else { document.getElementById("mRow7").style.backgroundColor = ""; }

//		if (document.getElementById("txtWorkAddress2").value == "") {
//			document.getElementById("manualStatus").innerHTML += "WARNING - Empty Work Address Line 2 Field.<BR>";
//			document.getElementById("mRow8").style.backgroundColor = "RED";
//		} else { document.getElementById("mRow8").style.backgroundColor = ""; }

		if (document.getElementById("txtWorkTown").value.replace(" ","") == "") {
			document.getElementById("manualStatus").innerHTML += "WARNING - Empty Work Town Field.<BR>";
			//document.getElementById("mRow9").style.backgroundColor = "RED";
		} else { document.getElementById("mRow9").style.backgroundColor = ""; }

//		if (document.getElementById("txtWorkCounty").value == "") {
//			document.getElementById("manualStatus").innerHTML += "WARNING - Empty Work County Field.<BR>";
//			document.getElementById("mRow10").style.backgroundColor = "RED";
//		} else { document.getElementById("mRow10").style.backgroundColor = ""; }

		if (document.getElementById("txtWorkPostCode").value.replace(" ","") == "") {
			document.getElementById("manualStatus").innerHTML += "WARNING - Empty Work PostCode Field.<BR>";
			document.getElementById("mRow11").style.backgroundColor = "RED";
		} else { 
		    if (!postit(document.getElementById("txtWorkPostCode").value)) {
	            document.getElementById("manualStatus").innerHTML += "WARNING - Invalid Work PostCode Field.<BR>";
	            document.getElementById("mRow11").style.backgroundColor = "RED";
	        } else {
	            document.getElementById("mRow11").style.backgroundColor = ""; 
	        }	    
		}
	}

	if (IorTB==1) { // also validate the trade bonus fields
		if (document.getElementById("txtValue").value.replace(" ","") == "") {
			document.getElementById("manualStatus").innerHTML += "WARNING - Empty Value Field.<BR>";
			document.getElementById("mRow12").style.backgroundColor = "RED";
		//} else if (frames['manualLevelFrame'].document.getElementById("lstLevel").value == 5 &&
		//	parseFloat(document.getElementById("txtValue").value) > 250000) {
		//	document.getElementById("manualStatus").innerHTML += "WARNING - Commercial policies must be £250,000 or below.<BR>";
		//} else if (frames['manualLevelFrame'].document.getElementById("lstLevel").value != 5 &&
		//	parseFloat(document.getElementById("txtValue").value) > 30000) {
		//	document.getElementById("manualStatus").innerHTML += "WARNING - Homepro policies must be £30,000 or below.<BR>";
		} else { document.getElementById("mRow12").style.backgroundColor = ""; }

		if (document.getElementById("txtStartDate").value.replace(" ","") == "") {
			document.getElementById("manualStatus").innerHTML += "WARNING - Empty Start Date Field.<BR>";
			document.getElementById("mRow14").style.backgroundColor = "RED";
		} else { 
//			if ((parseInt(document.getElementById("txtStartDate").value.slice(0,2)) > 31) ||
//				(parseInt(document.getElementById("txtStartDate").value.slice(0,2)) < 1)) {
//				document.getElementById("manualStatus").innerHTML += "WARNING - Invalid Day in Start Date Field.<BR>";
//				document.getElementById("mRow14").style.backgroundColor = "RED";
//			} else if ((parseInt(document.getElementById("txtStartDate").value.slice(3,5)) > 12) && 
//				(parseInt(document.getElementById("txtStartDate").value.slice(3,5)) < 1)) {
//				document.getElementById("manualStatus").innerHTML += "WARNING - Invalid Month in Start Date Field.<BR>";
//				document.getElementById("mRow14").style.backgroundColor = "RED";
//			} else if ((parseInt(document.getElementById("txtStartDate").value.slice(6,10)) < 2000) ||
//				(parseInt(document.getElementById("txtStartDate").value.slice(6,10)) > 2020)) {
//				document.getElementById("manualStatus").innerHTML += "WARNING - Invalid Year in Start Date Field.<BR>";
//				document.getElementById("mRow14").style.backgroundColor = "RED";
//			} else {			
//				document.getElementById("mRow14").style.backgroundColor = ""; 
//			}

        if (dateCheck(document.getElementById("txtStartDate").value,'%dd/%mm/%y')) { 
            document.getElementById("mRow14").style.backgroundColor = ""; 
        } else {
            document.getElementById("manualStatus").innerHTML += "WARNING - Invalid Date in Start Date Field.<BR>";
			document.getElementById("mRow14").style.backgroundColor = "RED";
        }
		}		
	}
	
	if (document.getElementById("txtEndDate").value.replace(" ","") == "") { 
	    if (document.getElementById("FENSAOutBound").style.display == "block" && 
	        document.getElementById("chkFENSAOutBound").checked == true && 
	        (IorTB==1)) {  
		        document.getElementById("manualStatus").innerHTML += "WARNING - Empty End Date Field (Required for FENSA Exports).<BR>";
		        document.getElementById("mRow15").style.backgroundColor = "RED";
		} else {
		    document.getElementById("mRow15").style.backgroundColor = ""; 
		}
	} else { 
//		if ((parseInt(document.getElementById("txtEndDate").value.slice(0,2)) > 31) ||
//			(parseInt(document.getElementById("txtEndDate").value.slice(0,2)) < 1)) { 
//			document.getElementById("manualStatus").innerHTML += "WARNING - Invalid Day in End Date Field.<BR>";
//			document.getElementById("mRow15").style.backgroundColor = "RED";
//		} else if ((parseInt(document.getElementById("txtEndDate").value.slice(3,5)) > 12) && 
//			(parseInt(document.getElementById("txtEndDate").value.slice(3,5)) < 1)) {
//			document.getElementById("manualStatus").innerHTML += "WARNING - Invalid Month in End Date Field.<BR>";
//			document.getElementById("mRow15").style.backgroundColor = "RED";
//		} else if ((parseInt(document.getElementById("txtEndDate").value.slice(6,10)) < 2000) ||
//			(parseInt(document.getElementById("txtEndDate").value.slice(6,10)) > 2020)) {
//			document.getElementById("manualStatus").innerHTML += "WARNING - Invalid Year in End Date Field.<BR>";
//			document.getElementById("mRow15").style.backgroundColor = "RED";
//		} else {			
//			document.getElementById("mRow15").style.backgroundColor = ""; 
//		}
        if (dateCheck(document.getElementById("txtEndDate").value,'%dd/%mm/%y')) { 
            document.getElementById("mRow15").style.backgroundColor = ""; 
        } else {
            document.getElementById("manualStatus").innerHTML += "WARNING - Invalid Day in End Date Field.<BR>";
			document.getElementById("mRow15").style.backgroundColor = "RED";
        }
	}
	
	if (document.getElementById("FENSAOutBound").style.display == "block" &&
	    document.getElementById("showWindowsNDoorz").style.display == "block" &&
	    document.getElementById("chkFENSAOutBound").checked == true) {
	    
	    if ((document.getElementById("txtWindows").value == "" || document.getElementById("txtWindows").value == "0") &&
	        (document.getElementById("txtDoors").value == "" || document.getElementById("txtDoors").value == "0") &&
	        (IorTB==1))  {
	       
	       	    document.getElementById("manualStatus").innerHTML += "WARNING - Number of Windows/Doors (Required for FENSA Exports).<BR>";
			    document.getElementById("mRow16").style.backgroundColor = "RED";
			    document.getElementById("mRow17").style.backgroundColor = "RED";
		} else { 
		    document.getElementById("mRow16").style.backgroundColor = "";
			document.getElementById("mRow17").style.backgroundColor = ""; 
		}
	} else {
	    document.getElementById("mRow16").style.backgroundColor = "";
		document.getElementById("mRow17").style.backgroundColor = "";
    }

    //if (document.getElementById("showSarnafilDetail").style.display == "block") {          
    //}	

	// validated OK
	if (document.getElementById("manualStatus").innerHTML == "" && dontAddJustValidate == 0) {
		loadSinglePolicyIntoSQL();
	} else if (dontAddJustValidate == 0) {		
		document.getElementById("manualStatus").style.display = "block";
		window.scroll(0,0);
	}
}


// add single policy
function loadSinglePolicyIntoSQL()  {
	var proposalID;
	if (document.getElementById("editPolicyID").innerHTML == "") {
		proposalID = "";
	} else {
		proposalID = document.getElementById("editPolicyID").innerHTML;
	}
	var trainOn=0;
	if (document.getElementById("chkTraining").checked == true) { trainOn=1; }
	var fensa=0;
	if (document.getElementById("chkFENSAOutBound").checked == true && 
	    document.getElementById("FENSAOutBound").style.display == "block" && 
	    document.getElementById("FENSARelevent").style.display == "block" ) { fensa=1; }
	var win=0;
	var doors=0;
	if (document.getElementById("showWindowsNDoorz").style.display == "block") {
	    win = parseInt(document.getElementById("txtWindows").value);
	    doors = parseInt(document.getElementById("txtDoors").value);
	}

    index.loadSinglePolicyIntoSQL(MySession, IorTB, proposalID,
		document.getElementById("cboTitle").value, 
		document.getElementById("txtFName").value, 
		document.getElementById("txtLName").value, 
		document.getElementById("txtAddress1").value, 
		document.getElementById("txtAddress2").value, 
		document.getElementById("txtAddress3").value, 
		document.getElementById("txtTown").value, 
		document.getElementById("txtCounty").value, 
		document.getElementById("txtPostCode").value.toUpperCase(), 
		document.getElementById("txtDayPhone").value, 
		document.getElementById("txtWorkAddress1").value, 
		document.getElementById("txtWorkAddress2").value, 
		document.getElementById("txtWorkAddress3").value, 
		document.getElementById("txtWorkTown").value, 
		document.getElementById("txtWorkCounty").value, 
		document.getElementById("txtWorkPostCode").value, 
		frames['manualLevelFrame'].document.getElementById("lstLevel").value, 
		frames['manualYearsFrame'].document.getElementById("lstYears").value, 
		document.getElementById("lstWorkType").value, 
		document.getElementById("txtValue").value, 
		document.getElementById("txtStartDate").value, 
		document.getElementById("txtEndDate").value, 
		trainOn, fensa, win, doors, document.getElementById("txtEmail").value,
		document.getElementById("txtInternalRef").value, 
		callback_loadSinglePolicyIntoSQL);
}	

// process the validation results
function callback_loadSinglePolicyIntoSQL(res)  {
	if (res.value != "ERROR") { 
		// refresh added records iframe
		document.getElementById("add").style.display="block";	
		iManualAddCnt += 1;	
		document.getElementById("addManualCnt").innerHTML = " (<b>" + iManualAddCnt + "</b>) ";

		// blank the existing fields
		document.getElementById("cboTitle").value = 0;
		document.getElementById("txtFName").value = "";
		document.getElementById("txtLName").value = ""; 
		document.getElementById("txtAddress1").value = "";
		document.getElementById("txtAddress2").value = ""; 
		document.getElementById("txtAddress3").value = ""; 
		document.getElementById("txtTown").value = ""; 
		document.getElementById("txtCounty").value = "";  
		document.getElementById("txtPostCode").value = "";  
		document.getElementById("txtDayPhone").value = ""; 
		document.getElementById("txtWorkAddress1").value = ""; 
		document.getElementById("txtWorkAddress2").value = ""; 
		document.getElementById("txtWorkAddress3").value = ""; 
		document.getElementById("txtWorkTown").value = ""; 
		document.getElementById("txtWorkCounty").value = ""; 
		document.getElementById("txtWorkPostCode").value = ""; 
		document.getElementById("txtValue").value = ""; 
		document.getElementById("txtStartDate").value = ""; 
		document.getElementById("txtEndDate").value = ""; 
		document.getElementById("txtWindows").value = "0";
		document.getElementById("txtDoors").value = "0"; 
		document.getElementById("txtEmail").value = ""; 
		document.getElementById("txtInternalRef").value = "";

		// clear edit form if from edit
		if (document.getElementById("editPolicyID").innerHTML != "") {
			cancelUpdatePolicy();
		}
	} else { // error adding policy
		if (document.getElementById("editPolicyID").innerHTML == "") {
			alert("ERROR - Add New Policy Failed, please check your data.");
		} else {
			alert("ERROR - Update Policy " + document.getElementById("editPolicyID").innerHTML + " Failed, please check your data.");
		}
	}
	//getExistingOSRecCountFTID();
	document.location.reload();
}

///////////////////////////////////////////////////////
// REFRESH THE ONSCREEN HEIGHTS N FADES              ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////

// get outstanding record count
function getExistingOSRecCountFTID()  {
	var trainOn=0; 
	if (document.getElementById("chkTraining").checked == true) { trainOn=1;} 
    index.getExistingOSRecCountFTID(MySession, trainOn, callback_getExistingOSRecCountFTID);
}	

// process the returned rec count
function callback_getExistingOSRecCountFTID(res)  {
	OSRecCount = parseInt(res.value);
	changePage(currPage,OSRecCount,page_sizze);
}

// get outstanding record count
function confirmOSPolicies()  {
	if (OSRecCount == 0) {
		alert("No Policies are Currently UnConfirmed.");
	} else if (MyLogin == "SUPER") {
		alert("You are logged in as the super user and therefore CANNOT update policies into the live system.");
	} else {
		if (confirm("Are you sure these Policies are Correct?")) {
		    iManualAddCnt = 0;
			document.getElementById("disable").style.display = "block";	
			document.getElementById("ttitle").style.display = "none";
			frames['editFrame'].document.getElementById("ppageSize").style.display = "none";
			if (IorTB == 1) {
				frames['editFrame'].document.getElementById("mCoverLevel").style.display = "none";
				frames['editFrame'].document.getElementById("mCoverYears").style.display = "none";
				frames['editFrame'].document.getElementById("mTradeType").style.display = "none";
				document.getElementById("tradebonusM").style.display = "none";
			}
			var trainOn=0; 
			if (document.getElementById("chkTraining").checked == true) { trainOn=1;} 
			index.confirmOSPolicies(MySession, trainOn, IorTB, callback_confirmOSPolicies);
		}
	}
}	

// process the returned rec count
function callback_confirmOSPolicies(res)  {
	if (res.value == "BADEMAIL") {
		alert("All Outstanding Pending Policies Confirmed, however an error occurred sending a Summary of this Action via Email..");
	}

	document.location.reload();
}

// reset the form to load from file
function back2FromFile() {
	document.location.reload();
}

///////////////////////////////////////////////////////
// EDIT THE POLICY                                   ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////

// load the policy details from d/b
function loadEditPolicy(PolicyID) { 
	index.loadEditPolicy(PolicyID, callback_loadEditPolicy);
}

function callback_loadEditPolicy(res) {
	var ds = res.value;
    if (ds != null && typeof(ds) == "object" && ds.Tables != null)  {
		// header
		window.scroll(0,0);
		document.getElementById("fileSelect").style.display = "none";
		showHide('fromfile','manual');
		document.getElementById("editPolicyID").innerHTML = ds.Tables[0].Rows[0].proposalid;
		document.getElementById("editDetail").style.display = "block";

		// process returned data into the add form
		document.getElementById("cboTitle").value = ds.Tables[0].Rows[0].title;
		document.getElementById("txtFName").value = ds.Tables[0].Rows[0].fname;
		document.getElementById("txtLName").value = ds.Tables[0].Rows[0].lname;
		document.getElementById("txtAddress1").value = ds.Tables[0].Rows[0].add1;
		document.getElementById("txtAddress2").value = ds.Tables[0].Rows[0].add2;
		document.getElementById("txtAddress3").value = ds.Tables[0].Rows[0].add3;
		document.getElementById("txtTown").value = ds.Tables[0].Rows[0].add4;
		document.getElementById("txtCounty").value = ds.Tables[0].Rows[0].county;
		document.getElementById("txtPostCode").value = ds.Tables[0].Rows[0].postcode;
		document.getElementById("txtDayPhone").value = ds.Tables[0].Rows[0].contactnumber;

		document.getElementById("txtWorkAddress1").value = ds.Tables[0].Rows[0].workadd1;
		document.getElementById("txtWorkAddress2").value = ds.Tables[0].Rows[0].workadd2;
		document.getElementById("txtWorkAddress3").value = ds.Tables[0].Rows[0].workadd3;
		document.getElementById("txtWorkTown").value = ds.Tables[0].Rows[0].workadd4;		
		document.getElementById("txtWorkCounty").value = ds.Tables[0].Rows[0].workcounty;
		document.getElementById("txtWorkPostCode").value = ds.Tables[0].Rows[0].workpostcode;

		document.getElementById("lstWorkType").value = ds.Tables[0].Rows[0].category;
		//refreshLevelAnYears("MANUAL",DefCoverLevel, ds.Tables[0].Rows[0].cover);
		refreshLevelAnYears("MANUAL",ds.Tables[0].Rows[0].coverlevel, ds.Tables[0].Rows[0].cover);
		document.getElementById("txtValue").value = ds.Tables[0].Rows[0].contractvalue;

		document.getElementById("txtStartDate").value = ds.Tables[0].Rows[0].startdate;
		if (ds.Tables[0].Rows[0].compdate != null) {
			document.getElementById("txtEndDate").value = ds.Tables[0].Rows[0].compdate;
		} else {
		    document.getElementById("txtEndDate").value = "";
		}
		if (ds.Tables[0].Rows[0].code == "FENSAOUT") {
		    document.getElementById("chkFENSAOutBound").checked = true;
		} else {
		    document.getElementById("chkFENSAOutBound").checked = false;
		}
		document.getElementById("txtWindows").value = ds.Tables[0].Rows[0].countwindows;
		document.getElementById("txtDoors").value = ds.Tables[0].Rows[0].countdoors;
		document.getElementById("txtEmail").value = ds.Tables[0].Rows[0].email;
		document.getElementById("txtInternalRef").value = ds.Tables[0].Rows[0].refno;

		if (ds.Tables[0].Rows[0].furtherdesc != null || ds.Tables[0].Rows[0].policy_desc != null) {
		    document.getElementById("txtSarnafilHeight").value = ds.Tables[0].Rows[0].furtherdesc;
		    document.getElementById("txtSarnafilArea").value = ds.Tables[0].Rows[0].policy_desc;
		}

		// show the edit controls div
		showHide("addPolicy","editPolicy");

	} else {  // table not returned, hmmm
		alert("ERROR - Unable to Edit Policy.");
	}
}

// cancel update, reset the form
function cancelUpdatePolicy() {
	showHide("editPolicy","addPolicy");
	document.getElementById("cboTitle").value = 0;
	document.getElementById("txtFName").value = "";
	document.getElementById("txtLName").value = ""; 
	document.getElementById("txtAddress1").value = "";
	document.getElementById("txtAddress2").value = ""; 
	document.getElementById("txtAddress3").value = ""; 
	document.getElementById("txtTown").value = ""; 
	document.getElementById("txtCounty").value = "";  
	document.getElementById("txtPostCode").value = "";  
	document.getElementById("txtDayPhone").value = ""; 
	document.getElementById("txtWorkAddress1").value = ""; 
	document.getElementById("txtWorkAddress2").value = ""; 
	document.getElementById("txtWorkAddress3").value = ""; 
	document.getElementById("txtWorkTown").value = ""; 
	document.getElementById("txtWorkCounty").value = ""; 
	document.getElementById("txtWorkPostCode").value = ""; 
	document.getElementById("txtValue").value = ""; 
	document.getElementById("txtStartDate").value = ""; 
	document.getElementById("txtEndDate").value = "";  
	document.getElementById("editPolicyID").innerHTML = "";
	document.getElementById("editDetail").style.display = "none";
	document.getElementById("txtWindows").value = "0";
	document.getElementById("txtDoors").value = "0"; 
	document.getElementById("txtEmail").value = ""; 
	document.getElementById("txtInternalRef").value = ""; 
	if (MorF == 1) {  
		showHide('manual','fromfile');
	}
	document.getElementById("fileSelect").style.display = "block";
}

///////////////////////////////////////////////////////
// VALIDATE FILE CHECKS AND FORMAT CHANGERS          ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////

// show hide new format textbox
function check4New() {
	var sSelected;
	if (IorTB == 1) {
		if (document.getElementById("cboSaveFormatTB").value == ".NEW FORMAT") {
			document.getElementById("addNewFTB").style.display = "block";
			//document.getElementById("delFormatTB").style.display = "none";
			redTextBox("txtNewFormatTB","saveFormatT");
		} else if (document.getElementById("cboSaveFormatTB").value == ".DON'T SAVE") {
			//document.getElementById("delFormatTB").style.display = "none";
			document.getElementById("addNewFTB").style.display = "none";
		} else {
			document.getElementById("addNewFTB").style.display = "none";
			//document.getElementById("delFormatTB").style.display = "block";
		}
	} else {
		if (document.getElementById("cboSaveFormatIntro").value == ".NEW FORMAT") {
			document.getElementById("addNewFIntro").style.display = "block";
			//document.getElementById("delFormatI").style.display = "none";
			redTextBox("txtNewFormatIntro","saveFormatI");
		} else if (document.getElementById("cboSaveFormatI").value == ".DON'T SAVE") {
			//document.getElementById("delFormatI").style.display = "none";
			document.getElementById("addNewFIntro").style.display = "none";
		} else {
			document.getElementById("addNewFIntro").style.display = "none";
			//document.getElementById("delFormatTB").style.display = "block";
		}
	}
}

// flag textbox red when empty (ie req.
function redTextBox(name,border) { 
	if (document.getElementById(name).value == "") {
		document.getElementById(border).style.backgroundColor = "RED";
	} else { 
		document.getElementById(border).style.backgroundColor = "";
	}	
}


// query server for new format information
function changeFormats() {
	if (document.getElementById("cboFormats").value != lastFormat) {
		index.changeFormats(MySession, document.getElementById("cboFormats").value, callback_changeFormats);
	}
}

// apply returned column format
function callback_changeFormats(res) {
	var ds = res.value;
    if (ds != null && typeof(ds) == "object" && ds.Tables != null)  {
		lastFormat = document.getElementById("cboFormats").value;
		
		// apply returned format information
		document.getElementById("status").innerHTML = "";
		addToForm(1, "", ds.Tables[0].Rows[0].col0,1);
		addToForm(2, "", ds.Tables[0].Rows[0].col1,1);
		addToForm(3, "", ds.Tables[0].Rows[0].col2,1);
		addToForm(4, "", ds.Tables[0].Rows[0].col3,1);
		addToForm(5, "", ds.Tables[0].Rows[0].col4,1);
		addToForm(6, "", ds.Tables[0].Rows[0].col5,1);
		addToForm(7, "", ds.Tables[0].Rows[0].col6,1);
		addToForm(8, "", ds.Tables[0].Rows[0].col7,1);
		addToForm(9, "", ds.Tables[0].Rows[0].col8,1);
		addToForm(10, "", ds.Tables[0].Rows[0].col9,1);
		addToForm(11, "", ds.Tables[0].Rows[0].col10,1);
		addToForm(12, "", ds.Tables[0].Rows[0].col11,1);
		addToForm(13, "", ds.Tables[0].Rows[0].col12,1);
		addToForm(14, "", ds.Tables[0].Rows[0].col13,1);
		addToForm(15, "", ds.Tables[0].Rows[0].col14,1);
		addToForm(16, "", ds.Tables[0].Rows[0].col15,1);
		addToForm(17, "", ds.Tables[0].Rows[0].col16,1);
		addToForm(18, "", ds.Tables[0].Rows[0].col17,1);
		addToForm(19, "", ds.Tables[0].Rows[0].col18,1);
		addToForm(20, "", ds.Tables[0].Rows[0].col19,1);
		addToForm(21, "", ds.Tables[0].Rows[0].col20,1);
		addToForm(22, "", ds.Tables[0].Rows[0].col21,1);
		addToForm(23, "", ds.Tables[0].Rows[0].col22,1);
		addToForm(24, "", ds.Tables[0].Rows[0].col23,1);
		addToForm(25, "", ds.Tables[0].Rows[0].col24,1);
		addToForm(26, "", ds.Tables[0].Rows[0].col25,1);
		addToForm(27, "", ds.Tables[0].Rows[0].col26,1);
		addToForm(28, "", ds.Tables[0].Rows[0].col27,1);
		addToForm(29, "", ds.Tables[0].Rows[0].col28,1);
		addToForm(30, "", ds.Tables[0].Rows[0].col29,1);

		// set trade defaults 
		if (IorTB == 1 && document.getElementById("cboFormats").value != "AUTO DETECT") {
			document.getElementById("cboDefaultTrade").value = ds.Tables[0].Rows[0].defTrade;
			refreshLevelAnYears("DEFAULT",DefCoverLevel,ds.Tables[0].Rows[0].defCoverYears);//ds.Tables[0].Rows[0].defCoverLevel
		}

		// set the save format combo to same format
		if (IorTB == 1) {
			if (document.getElementById("cboFormats").value == "AUTO DETECT") {
				document.getElementById("cboSaveFormatTB").value = ".DON'T SAVE";
				document.getElementById("delFormatTB").style.display = "none";
			} else {
				document.getElementById("cboSaveFormatTB").value = document.getElementById("cboFormats").value;
				document.getElementById("delFormatTB").style.display = "block";
			}
		} else {
			if (document.getElementById("cboFormats").value == "AUTO DETECT") {
				document.getElementById("cboSaveFormatIntro").value = ".DON'T SAVE";
				document.getElementById("delFormatI").style.display = "none";
			} else {
				document.getElementById("cboSaveFormatIntro").value = document.getElementById("cboFormats").value;
				document.getElementById("delFormatI").style.display = "block";
			}
		}

		// apply validation
		checkColumns();
	} else {
		alert("ERROR - Unable to Apply New Column Format.");
	}
}

// delete format from server
function delFormats() { 
	if (document.getElementById("cboFormats").value != "AUTO DETECT") {
		if (confirm("Confirm Delete of Format " + document.getElementById("cboFormats").value + "?")) { 
			if (document.getElementById("chkTraining").checked == true) { 
				alert("WARNING - Delete Format is disabled in training mode.");
			} else { 
				index.delFormats(MySession, document.getElementById("cboFormats").value, IorTB, 
					document.getElementById("ffpath").innerHTML, document.getElementById("ffsize").innerHTML, 
					document.getElementById("fftype").innerHTML, callback_delFormats);
			}
		}
	}
}

// refresh the format list, if sucess
function callback_delFormats(res) {
	if (res.value != "") { 
		alert("Import Format " + res.value + " has been deleted.");
		document.location.reload();
	} else {
		alert("ERROR - Unable to Delete this Format, please try again later.");
	}
}

// on reload check for format just deleted
function checkForDelete() {
	index.checkForDelete(MySession, callback_checkForDelete);
}

// refresh the format list, if sucess
function callback_checkForDelete(res) {
	var ds = res.value;
    if (ds != null && typeof(ds) == "object" && ds.Tables != null)  { 
		// set the form back 2 the previous screen
		if (ds.Tables[0].Rows[0].sLastImportFile != "") {
			document.getElementById("showFileDetails").innerHTML = 
				"<table><tr><td class=steps><b>Import File</b></td><td class=steps id=ffpath>" + 
				ds.Tables[0].Rows[0].sLastImportFile + "</td></tr>" + 
				"<tr><td class=steps><b>File Size</b></td><td class=steps id=ffsize>" +
				ds.Tables[0].Rows[0].sLastFileSize + "</td></tr>" + 
				"<tr><td class=steps><b>Content</b></td><td class=steps id=fftype>" + 
				ds.Tables[0].Rows[0].sLastFileType + "</td></tr>" +
				"<tr><td class=steps><b>Policy Type</b></td><td class=steps>" + 
				policyType + "</td></tr></table>";

			validateCSV();
		}

		// set the page size
		page_sizze = ds.Tables[0].Rows[0].iLastPageSize;

		// check for training flagged
		if (ds.Tables[0].Rows[0].bTrainingOn == 1 && MyLogin != "") {
			document.getElementById("chkTraining").checked = true;
			document.getElementById("trainWarning").style.display = "block";
			document.body.style.filter="progid:DXImageTransform.Microsoft.Gradient(GradientType=0, EndColorStr='DARKRED', StartColorStr='RED')";
			document.getElementById("chkPopUpHelp").checked = true;
			document.getElementById("chkPopUpHelp").disabled = true;
		} else if (ds.Tables[0].Rows[0].bHelpOn == 1 && MyLogin != "") { // check for help flagged
			document.getElementById("chkPopUpHelp").checked = true;
		}
	} 
	getExistingOSRecCountFTID();
}

///////////////////////////////////////////////////////
// UPDATE THE CONTROL REC WITH NEW LAST USED OPTS    ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////

// change page viewed
function changePage(newPage, totRecs, pageSize) {
	document.getElementById("add").style.display="block";
	var numRows;
	if ((newPage * pageSize) > totRecs) {
		numRows = totRecs - ((newPage - 1) * pageSize);
	} else {
		numRows = pageSize;
	}
	page_sizze = pageSize;
	if (bNewPageSize == "T") {
		bNewPageSize = "F";
		savePageSize();
	}
	currPage = newPage;

	var trainOn=0;
	if (document.getElementById("chkTraining").checked == true) { trainOn=1; }
	var calc = calc_head + (calc_row * numRows); 	
	document.getElementById("addThese").innerHTML = "<iframe src=editUpload.aspx?FTID=" + 
		MySession + "&TYPE=" + IorTB + "&PAGENUM=" + newPage + "&PAGESIZE=" + pageSize + "&TRAINON=" + trainOn + "&ASSOC=" + MyAssocID +
		" name=editFrame id=editFrame width=100% height=" + calc + "px scrolling=both frameborder=no></iframe><br>";

	

}

// save the current page size
function savePageSize() {
	index.savePageSize(MySession, page_sizze, callback_savePageSize);
}

// refresh the format list, if sucess
function callback_savePageSize(res) { 
	// do nothing, ignore empty return
}

// save enter/exit training mode
function enterExitTraining() {
	var trainOn=0;
	if (document.getElementById("chkTraining").checked == true) { trainOn=1; }
	index.enterExitTraining(MySession, trainOn, callback_enterExitTraining);
}

// enter/exit training mode warnings
function callback_enterExitTraining() {
	if (document.getElementById("chkTraining").checked == true) { 
		alert("WARNING - Training Mode Enabled, Imported Policies will not affect the Live System.");
		document.location.reload();
	} else {
		alert("WARNING - Training Mode Disabled.");
		document.location.reload();
	}
}

// save enter/exit help
function enterExitHelp() {
	var helpOn=0;
	if (document.getElementById("chkPopUpHelp").checked == true) { helpOn=1; }
	index.enterExitHelp(MySession, helpOn, callback_enterExitHelp);
}

// enter/exit training mode warnings
function callback_enterExitHelp() {
	// do nothing on call back from server side
}

///////////////////////////////////////////////////////
// CONFIRM IMPORT OF POLICIES INPUT                  ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////

// column order validated, import the file into our temp d/b
function startImport() {
	// check that the validation is complete
	if (bValidationPassed == 0) { // still got errors
		alert("Please correct ALL Column Warnings shown above before attempting to Import this file.");
	} else if (confirm("Are you sure the Column Order is Correct?")) {  // check for new format + ensure has been named
		if (IorTB==1) {
			if ((document.getElementById("cboSaveFormatTB").value == ".NEW FORMAT" && 
				document.getElementById("txtNewFormatTB").value != "") ||
				(document.getElementById("cboSaveFormatTB").value != ".NEW FORMAT")) {
				loadCSVIntoSQL();
			} else {
				alert("Please Input a Name for this Format.");
			}
		} else {
			if ((document.getElementById("cboSaveFormatIntro").value == ".NEW FORMAT" && 
				document.getElementById("txtNewFormatIntro").value != "") || 
				(document.getElementById("cboSaveFormatIntro").value != ".NEW FORMAT")) {
				loadCSVIntoSQL();
			} else {
				alert("Please Input a Name for this Format.");				
			}
		}	
	}
}

///////////////////////////////////////////////////////
// LOGIN AND REGISTER                                ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////
function attemptLogin(bJustCheck) {
	// validate the form contents
	document.getElementById("lblLoginErrors").innerHTML = "VALIDATION FAIL - Missing ";
	if (document.getElementById("txtEmailLogin").value == "") {		
		document.getElementById("lblLoginErrors").innerHTML += "Email, ";
		document.getElementById("emailLog").style.backgroundColor = "RED";		
	} else {
		document.getElementById("emailLog").style.backgroundColor = "";
	}
	if (document.getElementById("txtPasswordLogin").value == "" ||
		document.getElementById("txtPasswordLogin").value.length < 8) {
		document.getElementById("lblLoginErrors").innerHTML += "Password";
		document.getElementById("passwordLog").style.backgroundColor = "RED";
	} else {
		document.getElementById("passwordLog").style.backgroundColor = "";
	}
	
	if (document.getElementById("lblLoginErrors").innerHTML == "VALIDATION FAIL - Missing ") {
		document.getElementById("lblLoginErrors").innerHTML = "VALIDATED OK";
	} 

	// login user when all validation passed
	if (bJustCheck == "F") { 
		if (document.getElementById("lblLoginErrors").innerHTML == "VALIDATED OK") {
			index.attemptLogin(MySession,document.getElementById("txtEmailLogin").value, 
				document.getElementById("txtPasswordLogin").value, callback_attemptLogin);
		}
	} else {
		document.getElementById("lblLoginErrors").innerHTML = "";
	}

}
function callback_attemptLogin(res) {
	if (res.value != "FAIL") {
		//MyLogin = "OK";
		//document.getElementById("loginPopUp").style.display = "none";
		setCookie("fairTrades_login_FTIDNEW", res.value)
		document.location.reload();//setDefaultMode();
	} else {
		document.getElementById("lblLoginErrors").innerHTML = "LOGIN FAIL";
		document.getElementById("txtPasswordLogin").value = "";
		//document.getElementById("txtEmailLogin").value = "";		
	}
}


function registerNewUser(bJustCheck) {
	// validate the form contents
	document.getElementById("lblJoinErrorsReg").innerHTML = "VALIDATION FAIL - Missing ";
	try {
	if (document.getElementById("txtFTIDReg").value == "") {
		document.getElementById("lblJoinErrorsReg").innerHTML += "FTID, ";
		document.getElementById("regFTID").style.backgroundColor = "RED";
	} else {
		document.getElementById("regFTID").style.backgroundColor = "";
	}
	if (document.getElementById("txtPCodeReg").value == "") {
		document.getElementById("lblJoinErrorsReg").innerHTML += "PCode, ";
		document.getElementById("regPCode").style.backgroundColor = "RED";
	} else {
		document.getElementById("regPCode").style.backgroundColor = "";
	}
	} catch (e) {}
	if (document.getElementById("txtSNameReg").value == "") {
		document.getElementById("lblJoinErrorsReg").innerHTML += "Surname, ";
		document.getElementById("regFName").style.backgroundColor = "RED";
	} else {
		document.getElementById("regFName").style.backgroundColor = "";
	}
	if (document.getElementById("txtJobTitleReg").value == "") {
		document.getElementById("lblJoinErrorsReg").innerHTML += "Job Title, ";
		document.getElementById("regJobTit").style.backgroundColor = "RED";
	} else {
		document.getElementById("regJobTit").style.backgroundColor = "";
	}
	if (document.getElementById("txtEmailReg").value == "") {
		document.getElementById("lblJoinErrorsReg").innerHTML += "Email, ";
		document.getElementById("regEmail").style.backgroundColor = "RED";
	} else {
		if (document.getElementById("txtEmailReg").value.search("@") <= 0) {
			document.getElementById("lblJoinErrorsReg").innerHTML += "Valid Email, ";
			document.getElementById("regEmail").style.backgroundColor = "RED";
		} else {
			document.getElementById("regEmail").style.backgroundColor = "";				
		}
	}
	if (document.getElementById("lblJoinErrorsReg").innerHTML == "VALIDATION FAIL - Missing ") {
		document.getElementById("lblJoinErrorsReg").innerHTML = "VALIDATED OK";
	}

	// register the user when all validation passed
	if (bJustCheck == "F") { 	    	
		if (document.getElementById("lblJoinErrorsReg").innerHTML == "VALIDATED OK") {
			showHide("reg","thinking");
			
			// check the FTID / PostCode is valid
	        var sFTID = MySession;
	        var sPCode = "";
	        try {
	            sFTID = document.getElementById("txtFTIDReg").value;	 
	                  
                if (!isDigit(sFTID.substr(0,1))) {
                    sFTID = sFTID.substr(0,1).toUpperCase() + zeroPad(sFTID.substr(1),7);
                } else {
                    sFTID = zeroPad(sFTID,8)
                }
 
                document.getElementById("txtFTIDReg").value = sFTID;
	            sPCode = document.getElementById("txtPCodeReg").value;
	        } catch (e) {  
	            sFTID = MySession;
	            sPCode = "";
	        }
			
			index.registerNewUser(sFTID, sPCode, document.getElementById("cboTitleReg").value, 
				document.getElementById("txtFNameReg").value, 
				document.getElementById("txtSNameReg").value, 
				document.getElementById("txtJobTitleReg").value, 
				document.getElementById("txtEmailReg").value, callback_registerNewUser);
		}
	}
}

// check the user state and update da screen
function callback_registerNewUser(res) {
	if (res.value == "") {  // user reg ok
		showHide("registerPopUp","thanksPopUp");	
	} else {  // output reg error
	    if (res.value == "BADFTID") {
	        showHide("thinking","reg");
	        alert("SORRY, FTID and PostCode Combination NOT FOUND in our Database.");
	    } else {
	        if (res.value == "ALREADYREG") {
	            showHide('registerPopUp','loginPopUp');
	            alert("SORRY, FTID and PostCode Combination is already Registered.");
	        } else {
		        showHide('registerPopUp','loginPopUp');
		        alert("New Registration Failed with " + res.value);		
		    }
		}
	}
}

// check FTID isn't already registered
function sIsFTIDRegistered() {
	index.sIsFTIDRegistered(MySession,callback_sIsFTIDRegistered);	
}
function callback_sIsFTIDRegistered(res) {
	bRegistered = res.value;
	document.getElementById("loginPopUp").style.display = "block";
	if (bRegistered != "F") {
		document.getElementById("txtEmailLogin").value = bRegistered;
		document.getElementById("emailLog").style.backgroundColor = "";
	}
}


function startNewUserReg() {
	if (bRegistered != "F") {
		alert("A User Account has already been created, please use your registered email address to continue.");
	} else {  // allow register to continue
		showHide("thinking","reg");
		showHide("loginPopUp","registerPopUp");		
	}
}

// send user a mail with their lost password details
function sLostPassword() {
	if (document.getElementById("txtEmailLogin").value != "") {
		if (bRegistered != "F") {
			index.sLostPassword(MySession,document.getElementById("txtEmailLogin").value,callback_sLostPassword);	
		} else {
			alert("No Active Email Addresses Found, Please Register.");
		}
	} else {
		alert("Please Input Your Email Address.");
	}
}
function callback_sLostPassword(res) {
	if (res.value == "Y") {
		alert("Your Password has been sent by Email to " + document.getElementById("txtEmailLogin").value + ".");
	} else if (res.value == "E") {
		alert("Login Details Found, however the password mail sent to this address was returned.  Please contact HomePro.");
	} else {
		alert("Email Address " + document.getElementById("txtEmailLogin").value + " NOT FOUND.");
	}
} 

function zeroPad(str, len) {
  while (str.toString().length < len) {
    str = '0' + str;
  }

  return str;
}

function isDigit(num) {
	if (num.length>1){return false;}
	var string="1234567890";
	if (string.indexOf(num)!=-1){return true;}
	return false;
	}

//// just 4 debug, remove all calls on release
//function sDebugLog(whereFrom) {
//	index.sDebugLog(MySession, whereFrom, callback_sDebugLog);
//}

//function callback_sDebugLog(res) {
//	if (res.value != "") { alert(res.value); }
//}

///////////////////////////////////////////////////////
// EDIT ACCOUNT US/PASS                              ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////
function showEditAccount() {
    index.sReturnAccountDetails(MySession,callback_showEditAccount);	
}

function callback_showEditAccount(res) {
    if (res.value != "F") {
        document.getElementById("editAccountPopUp").style.display = "block";
        document.getElementById("txtEDACC_Email").value = res.value.slice(8);
        document.getElementById("txtEDACC_Password").value = res.value.slice(0,8);
        document.getElementById("lblEditAccErrors").innerHTML == "VALIDATED OK";
        showHide("thinkingEdit","divEdit");
        saveEditAccount("T");
     }
}

function saveEditAccount(bJustCheck) {
    // validate the form contents
	document.getElementById("lblEditAccErrors").innerHTML = "VALIDATION FAIL - InValid ";
	if (document.getElementById("txtEDACC_Email").value == "") {
		document.getElementById("lblEditAccErrors").innerHTML += "Email, ";
		document.getElementById("emailLog2").style.backgroundColor = "RED";
	} else {
	    if (document.getElementById("txtEDACC_Email").value.search("@") <= 0) {
			document.getElementById("lblEditAccErrors").innerHTML += " Email, ";
			document.getElementById("emailLog2").style.backgroundColor = "RED";
		} else {
		    document.getElementById("emailLog2").style.backgroundColor = "";
		}
	}
	if (document.getElementById("txtEDACC_Password").value == "") {
		document.getElementById("lblEditAccErrors").innerHTML += " Password  ";
		document.getElementById("passLog2").style.backgroundColor = "RED";
	} else {
	    if (document.getElementById("txtEDACC_Password").value.length != 8) {
	        document.getElementById("passLog2").style.backgroundColor = "RED";
	        document.getElementById("lblEditAccErrors").innerHTML += " Password";
	    } else {
		    document.getElementById("passLog2").style.backgroundColor = "";
		}
	}
	
	if (document.getElementById("lblEditAccErrors").innerHTML == "VALIDATION FAIL - InValid ") {
		document.getElementById("lblEditAccErrors").innerHTML = "VALIDATED OK";
	
	    // save the updated login info
	    
		if (bJustCheck == "F") {
		    showHide("divEdit","thinkingEdit");
		    index.saveEditAccount(MySession, document.getElementById("txtEDACC_Email").value, 
			    document.getElementById("txtEDACC_Password").value, callback_saveEditAccount);		    
	    }
	 }
}

function callback_saveEditAccount(res) {
    document.getElementById("editAccountPopUp").style.display = "none";
}


















/* 
<!-- Original:  Sandeep Tamhankar (stamhankar@hotmail.com) -->

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->

<!-- Begin
Here's the list of tokens we support:
   m (or M) : month number, one or two digits.
   mm (or MM) : month number, strictly two digits (i.e. April is 04).
   d (or D) : day number, one or two digits.
   dd (or DD) : day number, strictly two digits.
   y (or Y) : year, two or four digits.
   yy (or YY) : year, strictly two digits.
   yyyy (or YYYY) : year, strictly four digits.
   mon : abbreviated month name (April is apr, Apr, APR, etc.)
   Mon : abbreviated month name, mixed-case (i.e. April is Apr only).
   MON : abbreviated month name, all upper-case (i.e. April is APR only).
   mon_strict : abbreviated month name, all lower-case (i.e. April is apr 
         only).
   month : full month name (April is april, April, APRIL, etc.)
   Month : full month name, mixed-case (i.e. April only).
   MONTH: full month name, all upper-case (i.e. APRIL only).
   month_strict : full month name, all lower-case (i.e. april only).
   h (or H) : hour, one or two digits.
   hh (or HH) : hour, strictly two digits.
   min (or MIN): minutes, one or two digits.
   mins (or MINS) : minutes, strictly two digits.
   s (or S) : seconds, one or two digits.
   ss (or SS) : seconds, strictly two digits.
   ampm (or AMPM) : am/pm setting.  Valid values to match this token are
         am, pm, AM, PM, a.m., p.m., A.M., P.M.
*/
// Be careful with this pattern.  Longer tokens should be placed before shorter
// tokens to disambiguate them.  For example, parsing "mon_strict" should 
// result in one token "mon_strict" and not two tokens "mon" and a literal
// "_strict".

var tokPat=new RegExp("^month_strict|month|Month|MONTH|yyyy|YYYY|mins|MINS|mon_strict|ampm|AMPM|mon|Mon|MON|min|MIN|dd|DD|mm|MM|yy|YY|hh|HH|ss|SS|m|M|d|D|y|Y|h|H|s|S");

// lowerMonArr is used to map months to their numeric values.

var lowerMonArr={jan:1, feb:2, mar:3, apr:4, may:5, jun:6, jul:7, aug:8, sep:9, oct:10, nov:11, dec:12}

// monPatArr contains regular expressions used for matching abbreviated months
// in a date string.

var monPatArr=new Array();
monPatArr['mon_strict']=new RegExp(/jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec/);
monPatArr['Mon']=new RegExp(/Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec/);
monPatArr['MON']=new RegExp(/JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC/);
monPatArr['mon']=new RegExp("jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec",'i');

// monthPatArr contains regular expressions used for matching full months
// in a date string.

var monthPatArr=new Array();
monthPatArr['month']=new RegExp(/^january|february|march|april|may|june|july|august|september|october|november|december/i);
monthPatArr['Month']=new RegExp(/^January|February|March|April|May|June|July|August|September|October|November|December/);
monthPatArr['MONTH']=new RegExp(/^JANUARY|FEBRUARY|MARCH|APRIL|MAY|JUNE|JULY|AUGUST|SEPTEMBER|OCTOBER|NOVEMBER|DECEMBER/);
monthPatArr['month_strict']=new RegExp(/^january|february|march|april|may|june|july|august|september|october|november|december/);

// cutoffYear is the cut-off for assigning "19" or "20" as century.  Any
// two-digit year >= cutoffYear will get a century of "19", and everything
// else gets a century of "20".

var cutoffYear=50;

// FormatToken is a datatype we use for storing extracted tokens from the
// format string.

function FormatToken (token, type) {
this.token=token;
this.type=type;
}

function parseFormatString (formatStr) {
var tokArr=new Array;
var tokInd=0;
var strInd=0;
var foundTok=0;
    
while (strInd < formatStr.length) {
if (formatStr.charAt(strInd)=="%" &&
(matchArray=formatStr.substr(strInd+1).match(tokPat)) != null) {
strInd+=matchArray[0].length+1;
tokArr[tokInd++]=new FormatToken(matchArray[0],"symbolic");
} else {

// No token matched current position, so current character should 
// be saved as a required literal.

if (tokInd>0 && tokArr[tokInd-1].type=="literal") {

// Literal tokens can be combined.Just add to the last token.

tokArr[tokInd-1].token+=formatStr.charAt(strInd++);
}
else {
tokArr[tokInd++]=new FormatToken(formatStr.charAt(strInd++), "literal");
      }
   }
}
return tokArr;
}

/* buildDate does all the real work.It takes a date string and format string,
 tries to match the two up, and returns a Date object (with the supplied date
 string value).If a date string doesn't contain all the fields that a Date
 object contains (for example, a date string with just the month), all
 unprovided fields are defaulted to those characteristics of the current
 date. Time fields that aren't provided default to 0.Thus, a date string
 like "3/30/2000" in "%mm/%dd/%yyyy" format results in a Date object for that
 date at midnight.formatStr is a free-form string that indicates special
 tokens via the % character.Here are some examples that will return a Date
 object:

 buildDate('3/30/2000','%mm/%dd/%y') // March 30, 2000
 buildDate('March 30, 2000','%Mon %d, %y') // Same as above.
 buildDate('Here is the date: 30-3-00','Here is the date: %dd-%m-%yy')

 If the format string does not match the string provided, an error message
 (i.e. String object) is returned.Thus, to see if buildDate succeeded, the
 caller can use the "typeof" command on the return value.For example,
 here's the dateCheck function, which returns true if a given date is
 valid,and false otherwise (and reports an error in the false case):

 function dateCheck(dateStr,formatStr) {
 var myObj=buildDate(dateStr,formatStr);
 if (typeof myObj=="object") {
 // We got a Date object, so good.
 return true;
 } else {
 // We got an error string.
 alert(myObj);
 return false;
 }
 }

*/

function buildDate(dateStr,formatStr) {
// parse the format string first.
var tokArr=parseFormatString(formatStr);
var strInd=0;
var tokInd=0;
var intMonth;
var intDay;
var intYear;
var intHour;
var intMin;
var intSec;
var ampm="";
var strOffset;

// Create a date object with the current date so that if the user only
// gives a month or day string, we can still return a valid date.

var curdate=new Date();
intMonth=curdate.getMonth()+1;
intDay=curdate.getDate();
intYear=curdate.getFullYear();

// Default time to midnight, so that if given just date info, we return
// a Date object for that date at midnight.

intHour=0;
intMin=0;
intSec=0;

// Walk across dateStr, matching the parsed formatStr until we find a 
// mismatch or succeed.

while (strInd < dateStr.length && tokInd < tokArr.length) {

// Start with the easy case of matching a literal.

if (tokArr[tokInd].type=="literal") {
if (dateStr.indexOf(tokArr[tokInd].token,strInd)==strInd) {

// The current position in the string does match the format 
// pattern.

strInd+=tokArr[tokInd++].token.length;
continue;
}
else {

// ACK! There was a mismatch; return error.

return "\"" + dateStr + "\" does not conform to the expected format: " + formatStr;
   }
}

// If we get here, we're matching to a symbolic token.
switch (tokArr[tokInd].token) {
case 'm':
case 'M':
case 'd':
case 'D':
case 'h':
case 'H':
case 'min':
case 'MIN':
case 's':
case 'S':

// Extract one or two characters from the date-time string and if 
// it's a number, save it as the month, day, hour, or minute, as
// appropriate.

curChar=dateStr.charAt(strInd);
nextChar=dateStr.charAt(strInd+1);
matchArr=dateStr.substr(strInd).match(/^\d{1,2}/);
if (matchArr==null) {

// First character isn't a number; there's a mismatch between
// the pattern and date string, so return error.

switch (tokArr[tokInd].token.toLowerCase()) {
case 'd': var unit="day"; break;
case 'm': var unit="month"; break;
case 'h': var unit="hour"; break;
case 'min': var unit="minute"; break;
case 's': var unit="second"; break;
}
return "Bad " + unit + " \"" + curChar + "\" or \"" + curChar +
nextChar + "\".";
}
strOffset=matchArr[0].length;
switch (tokArr[tokInd].token.toLowerCase()) {
case 'd': intDay=parseInt(matchArr[0],10); break;
case 'm': intMonth=parseInt(matchArr[0],10); break;
case 'h': intHour=parseInt(matchArr[0],10); break;
case 'min': intMin=parseInt(matchArr[0],10); break;
case 's': intSec=parseInt(matchArr[0],10); break;
}
break;
case 'mm':
case 'MM':
case 'dd':
case 'DD':
case 'hh':
case 'HH':
case 'mins':
case 'MINS':
case 'ss':
case 'SS':

// Extract two characters from the date string and if it's a 
// number, save it as the month, day, or hour, as appropriate.

strOffset=2;
matchArr=dateStr.substr(strInd).match(/^\d{2}/);
if (matchArr==null) {

// The two characters aren't a number; there's a mismatch 
// between the pattern and date string, so return an error
// message.

switch (tokArr[tokInd].token.toLowerCase()) {
case 'dd': var unit="day"; break;
case 'mm': var unit="month"; break;
case 'hh': var unit="hour"; break;
case 'mins': var unit="minute"; break;
case 'ss': var unit="second"; break;
}
return "Bad " + unit + " \"" + dateStr.substr(strInd,2) + 
"\".";
}
switch (tokArr[tokInd].token.toLowerCase()) {
case 'dd': intDay=parseInt(matchArr[0],10); break;
case 'mm': intMonth=parseInt(matchArr[0],10); break;
case 'hh': intHour=parseInt(matchArr[0],10); break;
case 'mins': intMin=parseInt(matchArr[0],10); break;
case 'ss': intSec=parseInt(matchArr[0],10); break;
}
break;
case 'y':
case 'Y':

// Extract two or four characters from the date string and if it's
// a number, save it as the year.Convert two-digit years to four
// digit years by assigning a century of '19' if the year is >= 
// cutoffYear, and '20' otherwise.

if (dateStr.substr(strInd,4).search(/\d{4}/) != -1) {

// Four digit year.

intYear=parseInt(dateStr.substr(strInd,4),10);
strOffset=4;
}
else {
if (dateStr.substr(strInd,2).search(/\d{2}/) != -1) {

// Two digit year.

intYear=parseInt(dateStr.substr(strInd,2),10);
if (intYear>=cutoffYear) {
intYear+=1900;
}
else {
intYear+=2000;
}
strOffset=2;
}
else {

// Bad year; return error.

return "Bad year \"" + dateStr.substr(strInd,2) + 
"\". Must be two or four digits.";
   }
}
break;
case 'yy':
case 'YY':

// Extract two characters from the date string and if it's a 
// number, save it as the year.Convert two-digit years to four 
// digit years by assigning a century of '19' if the year is >= 
// cutoffYear, and '20' otherwise.

if (dateStr.substr(strInd,2).search(/\d{2}/) != -1) {

// Two digit year.

intYear=parseInt(dateStr.substr(strInd,2),10);
if (intYear>=cutoffYear) {
intYear+=1900;
}
else {
intYear+=2000;
}
strOffset=2;
} else {
// Bad year; return error
return "Bad year \"" + dateStr.substr(strInd,2) + 
"\". Must be two digits.";
}
break;
case 'yyyy':
case 'YYYY':

// Extract four characters from the date string and if it's a 
// number, save it as the year.

if (dateStr.substr(strInd,4).search(/\d{4}/) != -1) {

// Four digit year.

intYear=parseInt(dateStr.substr(strInd,4),10);
strOffset=4;
}
else {

// Bad year; return error.

return "Bad year \"" + dateStr.substr(strInd,4) + 
"\". Must be four digits.";
}
break;
case 'mon':
case 'Mon':
case 'MON':
case 'mon_strict':

// Extract three characters from dateStr and parse them as 
// lower-case, mixed-case, or upper-case abbreviated months,
// as appropriate.

monPat=monPatArr[tokArr[tokInd].token];
if (dateStr.substr(strInd,3).search(monPat) != -1) {
intMonth=lowerMonArr[dateStr.substr(strInd,3).toLowerCase()];
}
else {

// Bad month, return error.

switch (tokArr[tokInd].token) {
case 'mon_strict': caseStat="lower-case"; break;
case 'Mon': caseStat="mixed-case"; break;
case 'MON': caseStat="upper-case"; break;
case 'mon': caseStat="between Jan and Dec"; break;
}
return "Bad month \"" + dateStr.substr(strInd,3) + 
"\". Must be " + caseStat + ".";
}
strOffset=3;
break;
case 'month':
case 'Month':
case 'MONTH':
case 'month_strict':

// Extract a full month name at strInd from dateStr if possible.

monPat=monthPatArr[tokArr[tokInd].token];
matchArray=dateStr.substr(strInd).match(monPat);
if (matchArray==null) {

// Bad month, return error.

return "Can't find a month beginning at \"" +
dateStr.substr(strInd) + "\".";
}

// It's a good month.

intMonth=lowerMonArr[matchArray[0].substr(0,3).toLowerCase()];
strOffset=matchArray[0].length;
break;
case 'ampm':
case 'AMPM':
matchArr=dateStr.substr(strInd).match(/^(am|pm|AM|PM|a\.m\.|p\.m\.|A\.M\.|P\.M\.)/);
if (matchArr==null) {

// There's no am/pm in the string.Return error msg.

return "Missing am/pm designation.";
}

// Store am/pm value for later (as just am or pm, to make things
// easier later).

if (matchArr[0].substr(0,1).toLowerCase() == "a") {

// This is am.

ampm = "am";
}
else {
ampm = "pm";
}
strOffset = matchArr[0].length;
break;
}
strInd += strOffset;
tokInd++;
}
if (tokInd != tokArr.length || strInd != dateStr.length) {

/* We got through the whole date string or format string, but there's 
 more data in the other, so there's a mismatch. */

return "\"" + dateStr + "\" is either missing desired information or has more information than the expected format: " + formatStr;
}

// Make sure all components are in the right ranges.

if (intMonth < 1 || intMonth > 12) {
return "Month must be between 1 and 12.";
}
if (intDay < 1 || intDay > 31) {
return "Day must be between 1 and 31.";
}

// Make sure user doesn't put 31 for a month that only has 30 days

if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && intDay == 31) {
return "Month "+intMonth+" doesn't have 31 days!";
}

// Check for February date validity (including leap years) 

if (intMonth == 2) {

// figure out if "year" is a leap year; don't forget that
// century years are only leap years if divisible by 400

var isleap=(intYear%4==0 && (intYear%100!=0 || intYear%400==0));
if (intDay > 29 || (intDay == 29 && !isleap)) {
return "February " + intYear + " doesn't have " + intDay + 
" days!";
   }
}

// Check that if am/pm is not provided, hours are between 0 and 23.

if (ampm == "") {
if (intHour < 0 || intHour > 23) {
return "Hour must be between 0 and 23 for military time.";
   }
}
else {

// non-military time, so make sure it's between 1 and 12.

if (intHour < 1|| intHour > 12) {
return "Hour must be between 1 and 12 for standard time.";
   }
}

// If user specified amor pm, convert intHour to military.

if (ampm=="am" && intHour==12) {
intHour=0;
}
if (ampm=="pm" && intHour < 12) {
intHour += 12;
}
if (intMin < 0 || intMin > 59) {
return "Minute must be between 0 and 59.";
}
if (intSec < 0 || intSec > 59) {
return "Second must be between 0 and 59.";
}
return new Date(intYear,intMonth-1,intDay,intHour,intMin,intSec);
}
function dateCheck(dateStr,formatStr) {
var myObj = buildDate(dateStr,formatStr);
if (typeof myObj == "object") {

// We got a Date object, so good.

return true;
}
else {

// We got an error string.

//alert(myObj);
return false;
   }
}

//check postcode format is valid
function postit(testME) { 
 //test = document.details.pcode.value; 
 size = testME.length
 var test = testME.toUpperCase(); //Change to uppercase
 while (test.slice(0,1) == " ") //Strip leading spaces
  {test = test.substr(1,size-1);size = test.length
  }
 while(test.slice(size-1,size)== " ") //Strip trailing spaces
  {test = test.substr(0,size-1);size = test.length
  }
 //document.details.pcode.value = test; //write back to form field
 if (size < 6 || size > 8){ //Code length rule
  //alert(test + " is not a valid postcode - wrong length");
  //document.details.pcode.focus();
  return false;
  }
 if (!(isNaN(test.charAt(0)))){ //leftmost character must be alpha character rule
   //alert(test + " is not a valid postcode - cannot start with a number");
   //document.details.pcode.focus();
   return false;
  }
 if (isNaN(test.charAt(size-3))){ //first character of inward code must be numeric rule
   //alert(test + " is not a valid postcode - alpha character in wrong position");
   //document.details.pcode.focus();
   return false;
  }
 if (!(isNaN(test.charAt(size-2)))){ //second character of inward code must be alpha rule
   //alert(test + " is not a valid postcode - number in wrong position");
   //document.details.pcode.focus();
   return false;
  }
 if (!(isNaN(test.charAt(size-1)))){ //third character of inward code must be alpha rule
   //alert(test + " is not a valid postcode - number in wrong position");
   //document.details.pcode.focus();
   return false;
  }
// if (!(test.charAt(size-4) == " ")){//space in position length-3 rule
//   //alert(test + " is not a valid postcode - no space or space in wrong position");
//   //document.details.pcode.focus();
//   return false;
//   }
 count1 = test.indexOf(" ");count2 = test.lastIndexOf(" ");
 if (count1 != count2){//only one space rule
   //alert(test + " is not a valid postcode - only one space allowed");
   //document.details.pcode.focus();
   return false;
  }
//alert("Postcode Format OK");
return true;
}

function isEmail (s)
{   if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return false;
       else return (isEmail.arguments[1] == true);
   
    // is s whitespace?
    if (isWhitespace(s)) return false;
    
    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;

    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}

function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}



// Returns true if string s is empty or 
// whitespace characters only.

function isWhitespace (s)

{   var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}

//throw in any case string and it will return it perfectly formatted (in case)
function toProperCase(s)
{
  return s.toLowerCase().replace(/^(.)|\s(.)/g, 
          function($1) { return $1.toUpperCase(); });
}





// setCookieEx wrapper
function setCookie(name, value) {
	var now = new Date();
	//fixDate(now);	// fix the bug in Navigator 2.0, Macintosh

	/*	cookie expires in one year (actually, 365 days)
	365 days in a year
	24 hours in a day
	60 minutes in an hour
	60 seconds in a minute
	1000 milliseconds in a second	*/

	now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
	setCookieEx(name, value, now);
}

// write cookie
function setCookieEx(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

// get cookie value
function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

// delete cookie
//function deleteCookie(name, path, domain) {
//  if (getCookie(name)) {
//    document.cookie = name + "=" +
//    ((path) ? "; path=" + path : "") +
//    ((domain) ? "; domain=" + domain : "") +
//    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
//  }
//}

// fix date issues
//function fixDate(date) {
//  var base = new Date(0);
//  var skew = base.getTime();
//  if (skew > 0)
//    date.setTime(date.getTime() - skew);
//}
