var resTblCells = new Array();
function ajaxXMLRPCProvider(){
    var req;
    var ready;
    var sync;
    var reqType;
    
    
    var oThis = this;
    
    this.loadXMLDoc = function(url,reqType,sync,postData){
        if (window.XMLHttpRequest){
            req = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                req = false;
            }
        }
        
        req.onreadystatechange = processStateChange;
        req.open(reqType,url,sync);
        req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        req.send(postData);
    }
    
    var processStateChange = function() {
        var STATE_COMPLETED = 4;
        var STATUS_200 = 200;
        
        if (req.readyState == STATE_COMPLETED){
            if (req.status == STATUS_200) {
                oThis.onComplete(req.responseText);
            } else {
            	alert("Problem with request");
                oThis.onFailure(req.status+"<br/>"+req.responseText);
            }
        }
    }
    
    this.onComplete = function(responseText) {
    
        var responseArray = responseText.split("\n\n");
        var frm_msg = responseArray[1];
        var prem = responseArray[2];
        var pdf = responseArray[3];
        var sys_msg = responseArray[4];
        var underwriting_medical = responseArray[12];
		var underwriting_financial = responseArray[13];
        document.getElementById("error").innerHTML = frm_msg;
        document.getElementById('error').style.display = "block";
        document.getElementById("result").innerHTML = prem;
    
    }
    
    this.onFailure = function(resp) {
        document.getElementById("result").innerHTML = "<p>Error code: "+resp+"</p>";
    }
}

function getResults(url){
	// Post form data & get quote id
	document.getElementById("submit").style.display = "none";
	document.getElementById("stopcalc").style.display = "inline";
	postData(url);
	statusAll = 0;

	//Disable all form elements
	disableform();

    for (var i=0;i<productList.length;i++){
		productList[i].request = document.getElementById("life1_is_check_"+productList[i].sid).checked;
		productList[i].complete = !document.getElementById("life1_is_check_"+productList[i].sid).checked;
		productList[i].status = 0;
		if (productList[i].request){
			statusAll += 1;
		}
	}
	
	// check the quote status at regular intervals
	// - need to wait for an interval to allow time for the  
	// quoteId to be retrieved.
	clearInterval(tid);
	setTimeout('checkQuoteId();',10000);
}

function requote(sysId,quoteId,url){
	var onComplete = function(responseText){
        var responseArray = responseText.split("|");
        var result = responseArray[1];
        var excpts = responseArray[2];
        if (result == 'true'){
	        return true;
        } else {
        	return false;
        }
	}
    
    var provider = new ajaxXMLRPCProvider();
    provider.onComplete = onComplete;
    provider.loadXMLDoc(url,'GET',true,null);

	document.getElementById("submit").style.display = "none";
	document.getElementById("stopcalc").style.display = "inline";

    for (var i=0;i<productList.length;i++){
    	if (productList[i].sid == sysId){
			productList[i].request = true;
			productList[i].complete = false;
			productList[i].status = 0;
    		systemLabel = productList[i].label;
			statusAll++;
    	}
    }
    // document.getElementById("system_result_"+sysId).innerHTML = resTblCells[sysId];
	// document.getElementById("app_link_"+sysId).innerHTML = "<img name=\"progress\" src=\"../_img/progress.gif\" alt=\"progress\" border=\"0\" />";
	if (navigator.appName == "Microsoft Internet Explorer"){
		var oCell = document.getElementById("system_result_"+sysId).cells;
		for(var dc = oCell.length; dc > 0; dc--) {
    	//	alert("Delete Cell "+dc+" of "+oCell.length);
			document.getElementById("system_result_"+sysId).deleteCell();
		}
		oCell = document.getElementById("system_result_"+sysId).insertCell(0);
	  	oCell.innerText = systemLabel;
	  	oCell = document.getElementById("system_result_"+sysId).insertCell(1);
		oCell.colSpan = "6";
		oCell.style.width = "540px";
	  	oCell.innerHTML = "<img name=\"progress\" src=\"../_img/progress.gif\" alt=\"progress\" border=\"0\" />";
	} else {
		document.getElementById("system_result_"+sysId).innerHTML = "<td>"+systemLabel+"</td><td colspan=\"7\"><img name=\"progress\" src=\"../_img/progress.gif\" alt=\"progress\" border=\"0\" /></td>";
	}
	// Disable all form elements
	disableform();

	// check the quote status at regular intervals
	// - need to wait for an interval to allow time for the  
	// quoteId to be retrieved.
	// alert(statusAll);
	if (statusAll == 1){ 
		clearInterval(tid);
		setTimeout('checkQuoteId();',10000);
	}
}

function checkQuoteId(){
	if (quoteId > 0){
		counter = 0;
		tid = setInterval('checkQuoteStatus();',5000);
	}	
}

function checkQuoteStatus(){
    for (var i=0;i<productList.length;i++){
    	if (!productList[i].complete){
    		systemId = productList[i].sid;
    		systemLabel = productList[i].label;
    		// Get the quote status for each system
    		getQuoteStatus(quoteId,systemId);
    	}
    }
    //alert(counter+":"+statusAll);
	if (counter > 60 || statusAll == 0){
		clearInterval(tid);
		var message = "Unable to obtain quote - please try again later.";
	    for (var i=0;i<productList.length;i++){
			//alert("ProdList.Status (at end)"+productList[i].status);
	    	if (productList[i].request && productList[i].status != 2){
	    		if (navigator.appName == "Microsoft Internet Explorer"){
	    			var oCell = document.getElementById("system_result_"+productList[i].sid).cells;
					for(var dc = oCell.length; dc > 0; dc--) {
    				//	alert("Delete Cell "+dc+" of "+oCell.length);
						document.getElementById("system_result_"+productList[i].sid).deleteCell();
					}
				  	oCell = document.getElementById("system_result_"+productList[i].sid).insertCell(0);
					oCell.innerText = productList[i].label;
					oCell = document.getElementById("system_result_"+productList[i].sid).insertCell(1);
					oCell.colSpan = "6";
					oCell.style.width = "540px";
				  	oCell.innerText = message;
					if ( requote ){
					  	oCell = document.getElementById("system_result_"+productList[i].sid).insertCell(2);
					  	oCell.innerHTML = "<input id=\"requote_"+productList[i].sid+"\" name=\"requote_"+productList[i].sid+"\" onfocus=\"this.blur();\" class=\"requote\" type=\"button\" value=\"Re-Quote\" onclick=\"javascript:requote("+productList[i].sid+","+quoteId+",'../_lib/_base/requote.php?quote_id="+quoteId+"&system_id="+productList[i].sid+"');\" onmouseover=\"this.className='requoteHover'\" onmouseout=\"this.className='requote'\"/>";
				  	}
				} else {
					document.getElementById("system_result_"+productList[i].sid).innerHTML = "<td>"+productList[i].label+"</td><td colspan=\"6\">"+message+"</td><td><input id=\"requote_"+productList[i].sid+"\" name=\"requote_"+productList[i].sid+"\" onfocus=\"this.blur();\" class=\"requote\" type=\"button\" value=\"Re-Quote\" onclick=\"javascript:requote("+productList[i].sid+","+quoteId+",'../_lib/_base/requote.php?quote_id="+quoteId+"&system_id="+productList[i].sid+"');\" onmouseover=\"this.className='requoteHover'\" onmouseout=\"this.className='requote'\" /></td>";
				}
	    	}
	    }
	    statusAll = 0;
		document.getElementById("submit").style.display = "inline";
		document.getElementById("stopcalc").style.display = "none";
	    if (createSummaryPDF){
			document.getElementById('summary_pdf').style.display = "block";
		}
		crosscheck_form('');
	}
	counter++;
}

function getQuoteStatus(quoteId,systemId){
    var url = "../_lib/_base/getQuoteStatus.php?qid="+quoteId+"&sid="+systemId;
    //alert(url);
	var onComplete = function(responseText){
        var responseArray = responseText.split("|");
        var quote = responseArray[1];
        var sysId = responseArray[2];
        var status = responseArray[3];
        
        //alert(quote+":"+sysId+":"+status);
	    for (var i=0;i<productList.length;i++){
	    	if (productList[i].sid == systemId){
    			productList[i].status = status;
	    	}
	    }
        if (status == 2){
        	getQuoteResult(quote,sysId);
		    for (var i=0;i<productList.length;i++){
		    	if (productList[i].sid == sysId && productList[i].complete == false && productList[i].status == 2){
	    			productList[i].complete = true;
	    			statusAll--;
		    	}
		    }
	        return true;
        } else {
        	return false;
        }
	}
    
    var provider = new ajaxXMLRPCProvider();
    provider.onComplete = onComplete;
    provider.loadXMLDoc(url,'GET',true,null);
}

function getQuoteResult(qid,sid){
    var request = null;
    var url = "../_lib/_base/getQuoteResult.php?qid="+qid+"&sid="+sid;
    
    //alert(url);
    
    var onComplete = function(responseText) {
        var responseArray = responseText.split("|");
        var quote = responseArray[1];
        var sysId = responseArray[2];
        var sysLabel = responseArray[3];
        var instalment_premium = responseArray[4];
        var premium = responseArray[5];
        var annual_premium = "Annual Premium: "+responseArray[6];
        var pdf = responseArray[7];
        var occupation = responseArray[8];
        var message = responseArray[9];
        var cumulative_5_year = numberFormatter('$#,##0.##')(responseArray[12]);
		var cumulative_10_year = numberFormatter('$#,##0.##')(responseArray[13]);
		var underwriting_medical = responseArray[14];
		var underwriting_financial = responseArray[15];
		var commission_initial = numberFormatter('$#,##0.##')(responseArray[16]);
		var commission_renewal = numberFormatter('$#,##0.##')(responseArray[17]);
		var source = responseArray[18];
		var src_yr1_comm = responseArray[19];
		var src_yr2_comm = responseArray[20];
		var requote = false;
		
		// Set values blank instead of $0.00
		if (floatVal(responseArray[12]) == 0)
			cumulative_5_year = '';
		if (floatVal(responseArray[13]) == 0)
			cumulative_10_year = '';
		if (floatVal(responseArray[16]) == 0)
			commission_initial = '';
		if (floatVal(responseArray[17]) == 0)
			commission_renewal = '';
	
		if (message == -1){
			message = "Quote system unavailable at this time";
		}
		if (premium  < -1 || ( premium  > -2 && premium < 0 && message == "")){
			requote = true;
		}
		if (instalment_premium  < -1 || ( instalment_premium  > -2 && instalment_premium < 0 && message == "")){
			requote = true;
		}
		if (instalment_premium  < 0 || premium < 0){
			if (message == "" || message == "-1"){
				message = "Quote system unavailable at this time.";
				requote = true;
			}
		}
        var pdf_link = "<a class=\"pdf_link\" target=\"_blank\" href=\"../_lib/_base/getpdf.php?id="+pdf+"\"><span class=\"resultDisplayLabel\">"+sysLabel+"<\/span><span class=\"resultHoverLabel\">View PDF!<\/span><\/a>";
        var app_link = "&nbsp;";
		if (sysId == 10){
			app_link = "<a class=\"pdf_link\" target=\"_blank\" href=\"../_lib/_base/getpdf.php?id="+pdf+"-app\"><span class=\"resultDisplayLabel\">Application<\/span><span class=\"resultHoverLabel\">View PDF!<\/span><\/a>";
		}
		if (navigator.appName == "Microsoft Internet Explorer"){
			if (message != "" || message == -1 || message == null){
				var oCell = document.getElementById("system_result_"+sysId).cells;
				for(var dc = oCell.length; dc > 0; dc--) {
    			//	alert("Delete Cell "+dc+" of "+oCell.length);
					document.getElementById("system_result_"+sysId).deleteCell();
				}
			  	oCell = document.getElementById("system_result_"+sysId).insertCell(0);
				oCell.innerText = sysLabel;
				oCell = document.getElementById("system_result_"+sysId).insertCell(1);
				oCell.colSpan = "6";
				oCell.style.width = "540px";
				oCell.innerText = message;
				if ( requote ){
				  	oCell = document.getElementById("system_result_"+sysId).insertCell(2);
				  	oCell.innerHTML = "<input id=\"requote_"+sysId+"\" name=\"requote_"+sysId+"\" onfocus=\"this.blur();\" class=\"requote\" type=\"button\" value=\"Re-Quote\" onclick=\"javascript:requote("+sysId+","+quoteId+",'../_lib/_base/requote.php?quote_id="+quoteId+"&system_id="+sysId+"');\" />";
			  	}
			} else {
				var oCell = document.getElementById("system_result_"+sysId).cells;
    			for(var dc = oCell.length; dc > 0; dc--) {
    			//	alert("Delete Cell "+dc+" of "+oCell.length);
	    			document.getElementById("system_result_"+sysId).deleteCell();
	    		}
				oCell = document.getElementById("system_result_"+sysId).insertCell(0);
			  	oCell.innerHTML = pdf_link;
				oCell = document.getElementById("system_result_"+sysId).insertCell(1);
				oCell.innerHTML = app_link;
				oCell = document.getElementById("system_result_"+sysId).insertCell(2);
				oCell.align = "right";
				oCell.innerText = instalment_premium;
				oCell = document.getElementById("system_result_"+sysId).insertCell(3);
				oCell.align = "right";
				oCell.innerText = premium;
				oCell = document.getElementById("system_result_"+sysId).insertCell(4);
				oCell.align = "right";
				oCell.innerText = cumulative_5_year;
				oCell = document.getElementById("system_result_"+sysId).insertCell(5);
				oCell.align = "right";
				oCell.innerText = cumulative_10_year;
				oCell = document.getElementById("system_result_"+sysId).insertCell(6);
				oCell.align = "right";
				oCell.innerHTML = commission_initial + (src_yr1_comm > 0?'<sup>&dagger;</sup>':'');
				oCell = document.getElementById("system_result_"+sysId).insertCell(7);
				oCell.align = "right";
				oCell.innerHTML = commission_renewal + (commission_renewal != ''?'<sup>&Dagger;</sup>':'');
			}
		} else {
	        if (message != "" || message == -1 || message == null){
	//            pdf = "";
	//            pdf_link = "";
	//            document.getElementById("res_"+sysId).innerHTML = "";
	//            var errText = "<div class=\"clearfix\">"
	//                + "<span class=\"res_quoteid\" style = \"width:120px;padding:2px;\">"+sysLabel+"<\/span>"
	//                + "<span class=\"res_pdfloc\" style = \"width:500px;padding:2px;\">"+message+"<\/span>";
	//			alert(instalment_premium+":"+premium+":"+(instalment_premium  < -1)+":"+(premium  == -2));
				if ( requote ){
					document.getElementById("system_result_"+sysId).innerHTML = "<td>"+sysLabel+"</td><td colspan=\"6\">"+message+"</td><td><input id=\"requote_"+sysId+"\" name=\"requote_"+sysId+"\" onfocus=\"this.blur();\" class=\"requote\" type=\"button\" value=\"Re-Quote\" onclick=\"javascript:requote("+sysId+","+quoteId+",'../_lib/_base/requote.php?quote_id="+quoteId+"&system_id="+sysId+"');\" /></td>";
	//            	document.getElementById("ren_comm_"+sysId).innerHTML = "<input id=\"requote_"+sysId+"\" name=\"requote_"+sysId+"\" onfocus=\"this.blur();\" class=\"requote\" type=\"button\" value=\"Re-Quote\" onclick=\"javascript:requote("+sysId+","+quoteId+",'../_lib/_base/requote.php?quote_id="+quoteId+"&system_id="+sysId+"');\" />";
	//                errText += "<span class=\"res_requote\" style = \"width:75px;padding:2px;\"><input id=\"requote_"+sysId+"\" name=\"requote_"+sysId+"\" onfocus=\"this.blur();\" class=\"requote\" type=\"button\" value=\"Re-Quote\" onclick=\"javascript:requote("+sysId+","+quoteId+",'../_lib/_base/requote.php?quote_id="+quoteId+"&system_id="+sysId+"');\" /><\/span>";
				} else {
	            	document.getElementById("system_result_"+sysId).innerHTML = "<td>"+sysLabel+"</td><td colspan=\"7\">"+message+"</td>";
	            }
	        } else {
	        	instalment_premium = responseArray[4];
	        	premium = responseArray[5];
				document.getElementById("error").innerHTML = "";
	            document.getElementById('error').style.display = "none";
	            //alert(commission_initial);
	            document.getElementById("system_result_"+sysId).innerHTML = "<td>"+pdf_link+"</td><td>"+app_link+"</td><td class=\"numberAlign\">"+instalment_premium+"</td><td class=\"numberAlign\">"+premium+"</td><td class=\"numberAlign\">"+cumulative_5_year+"</td><td class=\"numberAlign\">"+cumulative_10_year+"</td><td class=\"numberAlign\">"+commission_initial + (src_yr1_comm > 0?"<sup>&dagger;</sup>":"")+"</td><td class=\"numberAlign\">"+commission_renewal + (commission_renewal != ''?"<sup>&Dagger;</sup>":"")+"</td>";
	        }
	    }
	    if (createSummaryPDF){
			document.getElementById('summary_pdf').style.display = "block";
		}
        if (underwriting_medical != "" || underwriting_financial != ""){
        	if (source == "COMPARATOR"){
				document.getElementById("uw_"+sysId).innerHTML =
					"<div class=\"clearfix\" style=\"clear:left;\">"
					+ "<p class=\"clearfix\">"+sysLabel+"<\/p>"
					+ "<textarea name=comments rows=6 WRAP=ON readonly>"+underwriting_medical+"</textarea>"
					+ "<textarea name=comments rows=6 WRAP=ON readonly>"+underwriting_financial+"</textarea>"
					+ "<\/div>";
			} else {
				document.getElementById("uw_"+sysId).innerHTML =
					"<div class=\"clearfix\" style=\"clear:left;\">"
					+ "<p class=\"clearfix\">"+sysLabel+"<\/p>"
					+ "<textarea name=comments rows=12 WRAP=ON readonly>"+underwriting_medical+"</textarea>"
					+ "<textarea name=comments rows=12 WRAP=ON readonly>"+underwriting_financial+"</textarea>"
					+ "<\/div>";
			}
		} else {
			if ( requote ){
				document.getElementById("uw_"+sysId).innerHTML =
					"<div class=\"clearfix\" style=\"clear:left;\">"
					+ "<p class=\"clearfix\">"+sysLabel+"<\/p>"
					+ "<\/div>";
			} else {
				document.getElementById("uw_"+sysId).innerHTML =
					"<div class=\"clearfix\" style=\"clear:left;\">"
					+ "<p class=\"clearfix\">"+sysLabel+" :: Not Available<\/p>"
					+ "<\/div>";
			}
		}
		crosscheck_form('');
    }
    
    var provider = new ajaxXMLRPCProvider();
    provider.onComplete = onComplete;
    provider.loadXMLDoc(url,'GET',true,null);
}

function postData(url){
    document.getElementById("error").innerHTML = "";
    document.getElementById('error').style.display = "none";
	document.getElementById("quote_label").innerHTML = "<strong>Contacting Server ...</strong>";    
    setDOB();
    
    var request = null;
    //var url = "./doQuote.php";
    var data = formData2QueryString(document.forms[0]);
    var quoteOK;
    var systemId;
    
    var onComplete = function(responseText) {
        // Parse the response text
        var responseArray = responseText.split("\n\n");
        quoteOK = responseArray[1];
        var frm_msg = responseArray[2];
        quoteId = responseArray[3];
        //alert(quoteOK);
        //alert(frm_msg);
        //alert(quoteId);
        if (quoteOK == 'true'){
			displayProgress(responseArray);
			return quoteId;
        } else {
        	displayError(responseArray);
        	return;
        }
    }
    
    var provider = new ajaxXMLRPCProvider();
    provider.onComplete = onComplete;
    provider.loadXMLDoc(url,'POST',true,data);
	
}

function displayProgress(responseArray){
    var quoteOK = responseArray[1];
    var frm_msg = responseArray[2];
    quoteId = responseArray[3];
//	var uwText = "<h3>Underwriting</h3>";
//    var resultText = "";
//    if (createSummaryPDF)
//    	resultText += "<a class=\"pdf_link\" target='_blank' href='../pdfreport/report.php?id="+quoteId+"&pdf=1' >View Summary</a>";
//   resultText += "</div>";
	document.getElementById("quote_label").innerHTML = "Quote Reference: "+quoteId;
    if (createSummaryPDF){
    	document.getElementById("summary_cell").innerHTML = "<a id=\"summary_pdf\" class=\"pdf_link\" target='_blank' href='../pdfreport/report.php?id="+quoteId+"&pdf=1' ><span class=\"resultDisplayLabel\">View Summary</span><span class=\"resultHoverLabel\">Load PDF!</span></a>";
    	document.getElementById('summary_pdf').style.display = "none";
    }
    document.getElementById("underwriting").style.display = "block";
    document.getElementById("underwriting").innerHTML = "<h3>Underwriting</h3>";
    var count = 0;
    for (var i=0;i<productList.length;i++){
    	if (productList[i].request){
    	//	resTblCells[productList[i].sid]=document.getElementById("system_result_"+productList[i].sid).innerHTML;
    		if (navigator.appName == "Microsoft Internet Explorer"){
    			var oCell = document.getElementById("system_result_"+productList[i].sid).cells;
    			for(var dc = oCell.length; dc > 0; dc--) {
    			//	alert("Delete Cell "+dc+" of "+oCell.length);
	    			document.getElementById("system_result_"+productList[i].sid).deleteCell();
	    		}
			  	oCell = document.getElementById("system_result_"+productList[i].sid).insertCell(0);
			  	oCell.innerText = productList[i].label;
			  	oCell = document.getElementById("system_result_"+productList[i].sid).insertCell(1);
			  	oCell.colSpan = "6";
				oCell.style.width = "540px";
			  	oCell.innerHTML = "<img name=\"progress\" src=\"../_img/progress.gif\" alt=\"progress\" border=\"0\" />";
			} else {
				document.getElementById("system_result_"+productList[i].sid).innerHTML = "<td>"+productList[i].label+"</td><td colspan=\"7\"><img name=\"progress\" src=\"../_img/progress.gif\" alt=\"progress\" border=\"0\" /></td>";
			}
			if (navigator.appName == "Microsoft Internet Explorer"){	
            	document.getElementById("system_result_"+productList[i].sid).style.display = "block";
            	document.getElementById("result_header0").style.display = "block";
			    document.getElementById('calculate_notes').style.display = "none";
        	} else {	
            	document.getElementById("system_result_"+productList[i].sid).style.display = "table-row";
            	document.getElementById("result_header0").style.display = "table-row";
			    document.getElementById('calculate_notes').style.display = "none";
        	}
        	// alert(count);
        	if (count>0)
				document.getElementById("underwriting").innerHTML += "<hr>"
			document.getElementById("underwriting").innerHTML += "<div id=\"uw_"+productList[i].sid+"\" class=\"clearfix\" style=\"clear:left;padding:5px;\"><p class=\"clearfix\" style = \"width:120px;padding:2px;\">"+productList[i].label+"</p></div>";
			count++;
    	}
    }
    document.getElementById("error").innerHTML = "The quotation you requested will take approximately 1 minute to complete";
    document.getElementById('error').style.display = "block";
    if (frm_msg == ""){
        document.getElementById('error').style.display = "none";
    } else {
    	document.getElementById("error").innerHTML = frm_msg;
        document.getElementById('error').style.display = "block";
    }
}

function displayError(responseArray){
    var quoteOK = responseArray[1];
    var frm_msg = responseArray[2];
    var quoteId = responseArray[3];
    interuptRequest();
    document.getElementById("error").innerHTML = frm_msg;
    document.getElementById('error').style.display = "block";
//    alert(frm_msg);
}
    
function formData2QueryString(docForm) {

    var submitContent = '';
    var formElem;
    var lastElemName = '';
    var pairs = [];
    var re_space = /%20/g;
    var re_pc = /%25(\d\d)/g;
    
    for (i = 0; i < docForm.elements.length; i++) {
        var pair;
        formElem = docForm.elements[i];
        switch (formElem.type) {
            // Text fields, hidden form elements
            case 'text':
            case 'hidden':
            case 'password':
            case 'textarea':
            case 'radio':
               	formElem.value = formElem.value.replace(/[,]/g , '');
				//submitContent += formElem.name + '=' + (formElem.value) + '&';
				pair = encodeURIComponent(formElem.name).replace(re_space,"+")
					+'='
					+encodeURIComponent(formElem.value).replace(re_space,"+").replace(re_pc,"%$1");
				pairs.push(pair);
	            break;
            case 'checkbox':
            	if (formElem.checked){
					pair = encodeURIComponent(formElem.name).replace(re_space,"+")
						+'='
						+encodeURIComponent(formElem.value).replace(re_space,"+").replace(re_pc,"%$1");
					pairs.push(pair);
				}
	            break;
            case 'select-one':
            	if ((formElem.name).substring(0,22) == 'life1_commission_type_' || (formElem.name).substring(0,23) == 'life1_commission_level_'){
                	//submitContent += formElem.name + '=' + (document.getElementById(formElem.name).options[document.getElementById(formElem.name).selectedIndex].text) + '&';
                	pair = formElem.name + '=' + (document.getElementById(formElem.name).options[document.getElementById(formElem.name).selectedIndex].text) + '&';
					pairs.push(pair);
                } else {
                	//submitContent += formElem.name + '=' + (document.getElementById(formElem.name).value) + '&';
					pair = encodeURIComponent(formElem.name).replace(re_space,"+")
						+'='
						+encodeURIComponent(formElem.value).replace(re_space,"+").replace(re_pc,"%$1");
					pairs.push(pair);
                }
    	        break;
            
        }
    }
    // Remove trailing separator
    //submitContent = submitContent.substr(0, submitContent.length - 1);

    //return submitContent;
    return pairs.join('&');
}
/*
function getOccupations(key){
    
    var request = null;
    var url = "./getOccupations.php?keyword="+key;
    var quoteOK;
    var quoteId;
    
    var onComplete = function(responseText) {
        var responseArray = responseText.split("\n\n");
        quoteOK = responseArray[1];
        var frm_msg = responseArray[2];
        quoteId = responseArray[3];
        if (quoteOK == 'true'){
            document.getElementById("result").innerHTML += "<div id=\"res_"+quoteId+"\"><span class=\"res_quoteid\" style = \"width:220px;padding:2px;\">Quote Reference: "+quoteId+"</span>"+"<img name=\"progress\" src=\"../_img/progress.gif\" alt=\"progress\" border=\"0\" /></div>";
            document.getElementById("error").innerHTML = "The quotation you requested will take approximately 1 minute to complete";
            document.getElementById('error').style.display = "block";
        } else {
            document.getElementById("error").innerHTML = frm_msg;
            document.getElementById('error').style.display = "block";
        }
    }
    
    var provider = new ajaxXMLRPCProvider();
    provider.onComplete = onComplete;
    provider.loadXMLDoc(url,'GET',true,data);
    
}
*/          
function interuptRequest(){
	setTimeout('clearInterval(tid)',5000);
    document.getElementById("quote_label").innerHTML = "Quotation request interrupted";
    if (createSummaryPDF){
    	document.getElementById("summary_pdf").style.display = "none";
    }
    for (var i=0;i<productList.length;i++){
	    if (productList[i].request){
    	    document.getElementById("system_result_"+productList[i].sid).style.display = "none";
        }
    }
    document.getElementById("underwriting").style.display = "none";
    document.getElementById("result").innerHTML = "";
    document.getElementById("error").innerHTML = "";
	document.getElementById("submit").style.display = "inline";
	document.getElementById("stopcalc").style.display = "none";
	reset_form();
	crosscheck_form(null);
}

function getText(id){
	if (document.getElementById("helpdisplay").checked){
		var d = MochiKit.Async.doSimpleXMLHttpRequest('../_lib/_base/getText.php?id='+id);
		d.addCallback(show_overlib);
	}
	
}
function getAwardText(id){
	var d = MochiKit.Async.doSimpleXMLHttpRequest('../_lib/_base/getAwardText.php?id='+id);
	d.addCallback(show_award_text);
}
function show_overlib(request) {
	if (document.getElementById("helpdisplay").checked){
		return overlib('<h4>Help</h4>'+request.responseText, WIDTH, 400, CSSCLASS,TEXTFONTCLASS,'fontClass',FGCLASS,'fgClass', BGCLASS,'bgClass',CAPTIONFONTCLASS,'capfontClass', CLOSEFONTCLASS, 'capfontClass');
	} else {
		return false;
	}
}
function show_award_text(request) {
	return overlib(request.responseText, WIDTH, 400, CSSCLASS,TEXTFONTCLASS,'awardTextClass',FGCLASS,'fgClass', BGCLASS,'bgClass',CAPTIONFONTCLASS,'capfontClass', CLOSEFONTCLASS, 'capfontClass');
}

/* 
 * **************** OCCUPATION SEARCH ********************* 
 * Argument of -1 gets occupations matching keyword for all companies
 */
function getOccupations(system_id){
	total_num_records = 0; //reset variable
    var keyword = document.getElementById('life1_keyword').value;
	
	if(system_id ==-1)
	{
		if (keyword.length<3){
			alert("Please enter a keyword of at least 3 characters");
			return;
		}
		//lets reset all our occupation select lists
		for(var i = 0; i < productList.length; i++)
		{
			var occupation_select = document.getElementById('life1_occupations_'+productList[i].sid);
			occupation_select.options.length = 2;	
		}
	}
    
    var request = null;
    var data='keyword=' + encodeURIComponent(keyword);
    data = data + '&system_id=' + system_id;

    var url = "../_lib/_base/getOccupations.php?" + data;
    var occupationOK;
    
    var firstOnComplete = function(responseText) {

		  var frm_msg = responseText;
        if (frm_msg == ""){
            alert("Occupation list not available");
        } else {
            if(system_id == -1){ //Ie filtered list for all systems
            	startParser(frm_msg);
            	for (var i = 0; i < productList.length; i++){
            		if (document.getElementById('life1_occupations_'+productList[i].sid).options.length > 2){
            			document.getElementById('life1_occupations_'+productList[i].sid).selectedIndex = 2;
            		} else {
            			document.getElementById('life1_occupations_'+productList[i].sid).selectedIndex = 0;
            		}
            	}
            }
            else
            	addOptions(system_id,frm_msg);
        }
		return;
    }
    
    var provider = new ajaxXMLRPCProvider();
    provider.onComplete = firstOnComplete;
    provider.loadXMLDoc(url,'GET',true,null);
    
}

function addOptions(system_id,xml)
{
	var select_box  = document.getElementById("life1_occupations_" + system_id);
	var select_box_parent = select_box.parentNode;
	start_xml = "<option>select occupation<\/option>";
	start_xml += "<option>load all occupations<\/option>";
	xml = start_xml + xml;
	select_box.innerHTML = xml;
	select_box.selectedIndex = 2;
}
function startParser(xml) {
	var parser = new SAXDriver();
	
	var eventHandler = new SAXEventHandler();
	parser.setDocumentHandler(eventHandler);
	parser.setLexicalHandler(eventHandler);
	parser.setErrorHandler(eventHandler);
    occupations = new Array();
	parser.parse(xml);
	
	if(occupations.length == total_num_records)
	{
		if(occupations.length !=0)
			fillOccupationSelects();
		
		addDummyOccupations();
	}
} // end function startParser

function addDummyOccupations()
{
	for(var i = 0; i < selectLists.length; i++)
	{
		var occupation_select = document.getElementById(selectLists[i].occupation_select);
		if(occupation_select.options.length == 2) //standard options only
		{
			occupation_select.options[2] = new Option('No occupation found');
		}
		occupation_select.options[2].selected = true;
	}
}

function fillOccupationSelects()
{
	var select_option_indexes = new Array();

	//ok lets fill up our occupations
	for(var i = 0; i < occupations.length; i++)
	{
		var system_id = occupations[i].system_id;

		var occ_select_name = 'life1_occupations_' + system_id;
		//alert('sel name ' + occ_select_name);
		var occupation_select = document.getElementById(occ_select_name);

		//occupations_
		//if index exist we can add one to it otherwise create it with 2
		if(select_option_indexes['life1_occupations_' + system_id])
		{
			var index = select_option_indexes['life1_occupations_' + system_id];
			index ++;
			select_option_indexes['life1_occupations_' + system_id] = index;
		}
		else
			select_option_indexes['life1_occupations_' + system_id] = 2; //0 and 1 are taken with defaults ie 'load all occs'
			
		occupation_select.options[select_option_indexes['life1_occupations_' + system_id]] = new Option(occupations[i].name,occupations[i].name,occupations[i].id);
	}
}
