/************************************************************************************
* JavaScript Name: model.js
* History: 9/2005 created by UX Prototype Dev Team
* Description:	handles UXPrototype2 data functionality
*************************************************************************************/

/**********************/
/* global variables   */
/**********************/
var ie =  (typeof window.ActiveXObject != 'undefined');
var POLICY_XML="data/customer.xml";
var OPTIONS_XML="data/options.xml";

var customerxmlDoc = null;
var optionsxmlDoc = null;
var newCustomer=null;

var backToPolicyButton="<img src=\"image/backtopolicy.gif\" width=\"110\" height=\"26\" alt=\"back to policy\" align=\"middle\">";
var closePolicyButton="<img src=\"image/close.gif\" width=\"52\" height=\"21\" alt=\"close\" align=\"middle\">";
var cancelEndorsementButton="<img src=\"image/cancel.gif\" width=\"69\" height=\"23\" alt=\"cancel\" align=\"middle\">";
var submitEndorsementButton="<img src=\"image/submit.gif\" width=\"58\" height=\"23\" alt=\"submit\" align=\"middle\">";
var startEndorsementButton="<img src=\"image/start.gif\" width=\"58\" height=\"23\" alt=\"start\" align=\"middle\">";
var yesEndorsementButton="<img src=\"image/yes.gif\" width=\"35\" height=\"25\" alt=\"yes\" align=\"middle\">";
var noEndorsementButton="<img src=\"image/no.gif\" width=\"35\" height=\"25\" alt=\"no\" align=\"middle\">";
var confirmationCheckMark="<img src=\"image/check.gif\" width=\"17\" height=\"17\" alt=\"no\" align=\"middle\">";

var UNKNOWN="Unknown Status";
var INCOMPLETE="Incomplete";
var READYTOQUOTE="Ready to Quote";
var READYTOISSUE="Ready to Issue";
var ISSUEDPOLICY="Issued Policy";
var ENDORSEMENT="Endorsement";
var ENDORSEMENTCOMPLETE="Endorsement Complete";

var PERSONALINFO="personalinfo";
var DRIVER="driver";
var VEHICLE1="vehicle1";
var VEHICLE2="vehicle2";
var COVERAGE="coverage";
var PREMIUM="premium";
var BILLINGINFO="billinginfo";
var QUOTEPREMIUMBILLING="quotepremiumbilling";

/*****************************/
/* functions		     */
/*****************************/
/* 
	loadData()
	loads xml files and validates against DTD 
*/
function loadData(){
	if(ie){
		if (customerxmlDoc == null){
			customerxmlDoc  = new ActiveXObject("Microsoft.XMLDOM");
    			customerxmlDoc.async=false;
    			//customerxmlDoc.validateOnParse="true"
    			customerxmlDoc.load(POLICY_XML);
    			customerxmlDoc.setProperty("SelectionLanguage","XPath");

    			
			//alert("Error Code: "+ customerxmlDoc.parseError.errorCode + "<br>Error Reason: " + customerxmlDoc.parseError.reason + "<br>Error Line: " + customerxmlDoc.parseError.line);
    		}
 		if (optionsxmlDoc == null){
 			optionsxmlDoc  = new ActiveXObject("Microsoft.XMLDOM");
    			optionsxmlDoc.async=false;
    			//optionsxmlDoc.validateOnParse="true"
    			optionsxmlDoc.load(OPTIONS_XML);
    			
			//alert("Error Code: " + optionsxmlDoc.parseError.errorCode +"<br>Error Reason: " + optionsxmlDoc.parseError.reason + "<br>Error Line: " + optionsxmlDoc.parseError.line);
			
		}
	} else{
		alert("Sorry, your browser is not supported.  This application supports Internet Explorer 5.5 and above");
	}
}

/* 
	Customer(node)
	Customer constructor 
*/
function Customer(node) {
    this.node = node;
}

/* 
	getFieldValue(fieldname)
	gets the text value of a Customer node 
*/
Customer.prototype.getFieldValue = function (fieldname) {
	var fieldnode=null;
	if(fieldname==this.node.nodeName){
		return this.node.text;		
	}else{
		fieldnode=this.node.selectNodes('.//' + fieldname);
		if(fieldnode!=null  && fieldnode.length>0){
			return fieldnode.item(0).text;
		}else{
			return null;
		}
	}
}
/* 
	setFieldValue(fieldname,value)
	sets the text value of a Customer  
*/
Customer.prototype.setFieldValue = function (fieldname,value) {
	var fieldnode=null;
	if(fieldname==this.node.nodeName){
		this.node.text=value;		
	}else{
		fieldnode=this.node.selectNodes('.//' + fieldname);	
		fieldnode.item(0).text=value;
	}
}
/* 
	getAttributeValue(fieldname,attributename)
	gets an attribute of a Customer node 
*/
Customer.prototype.getAttributeValue = function (fieldname,attributename) {
	var attribute=null;
	if(fieldname==this.node.nodeName){
		return this.node.getAttribute(attributename);
	}else{
		attribute=this.node.selectNodes('.//'+ fieldname);
		if(attribute!=null && attribute.length>0){
			return attribute.item(0).getAttribute(attributename);
		}
	}
}
/* 
	setAttributeValue(fieldname,attributename,value)
	sets an attribute value of a Customer node 
*/
Customer.prototype.setAttributeValue = function (fieldname,attributename,value) {
	var attribute=null;
	if(fieldname==this.node.nodeName){
		this.node.setAttribute(attributename,value);
	}else{
		attribute=this.node.selectNodes('.//'+ fieldname);
		attribute.item(0).setAttribute(attributename,value);
	}
}

/*
	removeAttribute()
	removes an attribute from a node
*/
Customer.prototype.removeAttribute = function(fieldname,attributename){
	var attribute=null;
	if(fieldname==this.node.nodeName){
		return this.node.removeAttribute(attributename);
	}else{
		attribute=this.node.selectNodes('.//'+ fieldname);
		if(attribute!=null && attribute.length>0){
			return attribute.item(0).removeAttribute(attributename);
		}
	}
}
/*
	findNode(nodeName)
	returns a node of the given name
*/
Customer.prototype.findNode=function(nodeName){
	return this.node.selectNodes('.//'+ nodeName);
}

/*
	addNode(nodeName)
	adds a node to Customer
*/
Customer.prototype.addNode=function(nodeName){

	/* find the existing node by this node name */
	var chNodes=this.findNode(nodeName);
	if(chNodes!= null && chNodes.length>0){
	
		/* get the parent */
		var chparent = chNodes[0].parentNode;
	
		/* copy the node from the default customer */
		var newCust=getNewCustomer();
		var nodeToClone=newCust.findNode(nodeName);
		var newNode=nodeToClone.item(0).cloneNode(true);
		newNode.setAttribute('vehicleid','2');
	
		/* add child node to the parent */
		chparent.appendChild(newNode);
		var chNodes=this.findNode(nodeName);
	}	
}


/* 
	findCustomer(searchcriteria)
	finds customers and sets the searchResultsArray 
*/
function findCustomer(searchcriteria){
	var criteria=searchcriteria;
	var result=null;
	var str=null;
	var customer=null;
	var searchResultsArray=new Array();
	
	//var docroot=customerxmlDoc.documentElement;
	if(criteria.length<1){
		alert("Please enter a policy number or customer name");
		return null;//add null field error handling
	}else{
		//check if policy number
		if(isNum(criteria)){
			
			str='//policy[@pid=\''+ criteria + '\']';
			result=customerxmlDoc.selectNodes(str);
			//add customer nodes to search results
			for(var i=0;i<result.length;i++){
				customer=result[i].parentNode;
				searchResultsArray[i] = new Customer(customer);
			}
		}else{			
			/* perform case insensitive name search */
			var fnamelname=criteria.split(" ");
			if(fnamelname.length==2){
				//check if firstname and last name
				str="//personalinfo[translate(ifirstname,\'ABCDEFGHIJKLMNOPQRSTUVWXYZ\',\'abcdefghijklmnopqrstuvwxyz\')=\'" + fnamelname[0].toLowerCase() + "\' and translate(ilastname,\'ABCDEFGHIJKLMNOPQRSTUVWXYZ\',\'abcdefghijklmnopqrstuvwxyz\')=\'" + fnamelname[1].toLowerCase() + "\']";
			}else if(fnamelname.length=1){			
				//check if lastname
				str="//personalinfo[translate(ilastname,\'ABCDEFGHIJKLMNOPQRSTUVWXYZ\',\'abcdefghijklmnopqrstuvwxyz\')=\'" + fnamelname[0].toLowerCase() + "\']";
			}else{
				alert("please search by name in \'firstname lastname\' format");
				return null;
			}
			//result=customerxmlDoc.selectNodes("//personalinfo[translate(ilastname,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='" + fnamelname[0].toLowerCase() + "']");

			result=customerxmlDoc.selectNodes(str);
			for(var i=0;i<result.length;i++){
				//get the customer policy node and add to search results			
				customer=result.item(i).parentNode.parentNode.parentNode;
				searchResultsArray[i] = new Customer(customer);
			}
		}
		if(searchResultsArray.length>0){
			return searchResultsArray;
		}else{
			return null;
		}
	}			
}
/*
	getNewCustomer()
	returns the new customer node for cloning
*/
function getNewCustomer(){
	if(newCustomer==null){
		var tmp=findCustomer("0");
		newCustomer=tmp[0];
	}
	return newCustomer;
}
/* 
	DelayTracker constructor
	addEvent(o,t) adds object parameter to it's list of Array objects
	runEvent(id) runs the update method of the object at the id's index in the object Array
*/
DelayTracker = {
	currentId: 0,
	objArr: new Array(),
	addEvent: function (o, t) {
		this.objArr[this.currentId] = o;//adds SearchResult object as 1st array element
		setTimeout('DelayTracker.runEvent('+this.currentId+')', t);//delays running of runEvent with SearchResults as object parameter
		this.currentId++;
	},
	runEvent: function (id) { 
		this.objArr[id].update(this);
		this.objArr = new Array();
		}
	};

/* 
	SearchResult constructor
*/
function SearchResult (searchTerm,time,obj) {
	var results=findCustomer(searchTerm);
	this.resultsArray = results;//creates search result array
	this.obj = obj;//adds update function as an object 
	DelayTracker.addEvent(this, time);//adds SearchResult object to DelayTracker
}
/* 
	SearchResult update(o)
	calls it's obj value's update method, passing in itself
*/
SearchResult.prototype.update = function (o) {
	this.obj.update(this);
}
		
/* 
	createQuote()
	creates a new quote and appends it to customer DOM 
*/
function createQuote(){
	var docroot = customerxmlDoc.documentElement;
	
	/* get the default node */
	var defaultnode=customerxmlDoc.selectNodes("//customer[@cid='0']");
	
	/* create a new node */
	var newCustomer=defaultnode.item(0).cloneNode(true);
	
	/* set a random customer id */
	newCustomer.setAttribute('cid',generateId());
	
	/* set a random policy id */
	var newCustomerPolicy=newCustomer.selectNodes("//policy");
	newCustomerPolicy.item(0).setAttribute('pid',generateId());
	newCustomerPolicy.item(0).setAttribute('status','new');
	
	
	/* append quote node to customer DOM */
	docroot.appendChild(newCustomer);

	var newNode=new Customer(newCustomer);
	
	return newNode;
}

/*
	save(document)
	saves a quote or policy	
*/
function save(doc,cust){

	var custnode,id,vid;
	var isMulti=false;

	/* save all fields on dom (hidden and unhidden) */
	var textnodes=doc.getElementsByTagName("input");
	for(var i=0;i<textnodes.length;i++){		
		
		/* scroll through each input field on the document */
		var inputfield=textnodes[i];
		var attrvalue=inputfield.getAttribute("value");
		
		id=inputfield.getAttribute("id");
		if( id != "effectivedate" )	
		{		
			var viewName=checkViewName(inputfield);
			isMulti=isMultiNode(viewName);
		}
		if(isMulti){
			isMulti=true;
			vidarray=parseId(id);
			vid=vidarray[0];
			index=vidarray[1];
		}
		
			
		/* check the input type */
		if(inputfield.getAttribute("type").toLowerCase() =='text'){
			if(!isMulti){
				custnode=cust.findNode(id);
			}else{
				str='.//vehicle[@vehicleid=\''+ index + '\']';
				custnode=cust.node.selectNodes(str);
				str='.//'+vid;
				custnode=custnode[0].selectNodes(str);
				//alert('saving customer='+cust.getAttributeValue("customer","cid"));
			}
			if(custnode){
				/* add field validation here */
				custnode.item(0).text=attrvalue;
				//alert("saved-" +custnode.item(0).nodeName + " " + custnode.item(0).text);
			}			
		}else if(inputfield.getAttribute("type").toLowerCase() =='checkbox'){
			if(!isMulti){
				var custnode=cust.findNode(id);
			}else{
				str='.//vehicle[@vehicleid=\''+ index + '\']';
				custnode=cust.node.selectNodes(str);
				str='.//'+vid;
				custnode=custnode[0].selectNodes(str);
			}
			if(custnode){
				/* add field validation here */
				if(inputfield.getAttribute("checked")){
					custnode.item(0).text="yes";
				}else{						
					if(custnode.item(0).text){
						custnode.item(0).text="no";
					}
				}
				//alert("saved-" +custnode.item(0).nodeName + " " + custnode.item(0).text);
			}
		}else if(inputfield.getAttribute("type").toLowerCase() =='radio'){
			
			var pnode=inputfield.parentNode;
			while(pnode.nodeName.toLowerCase()!="fieldset"){pnode=pnode.parentNode}
			var parentnodeid=pnode.getAttribute("id");
			if (parentnodeid == '') {
				parentnodeid = inputfield.getAttribute('name');
			}
			if(!isMulti){
				//parentnodeid=pnode.getAttribute("id");
				custnode=cust.findNode(parentnodeid);
			}else{
				vid=parseId(parentnodeid)[0];
				index=parseId(parentnodeid)[1];
				str='.//vehicle[@vehicleid=\''+ index + '\']';
				custnode=cust.node.selectNodes(str);
				str='.//'+vid;
				custnode=custnode[0].selectNodes(str);
			}
			if(custnode){
				/* add field validation here */
				/* set customer node if radio button is checked */
				var ckd=inputfield.getAttribute("checked");
				if(ckd){
					custnode.item(0).text=inputfield.getAttribute("value");
				}
				//alert("saved-" +custnode.item(0).nodeName + " " + custnode.item(0).text);
			}
		}
	}
	/* set select boxes for now */
	textnodes=doc.getElementsByTagName("select");
	for(var a=0;a<textnodes.length;a++){			
		var isMulti=false;
		
		inputfield=textnodes[a];
		id=inputfield.getAttribute("id");
		if( id != "effectivedate" )	
		{		
			var viewName=checkViewName(inputfield);
			isMulti=isMultiNode(viewName);
		}
		var options=inputfield.childNodes;		
		for(var c=0;c<options.length;c++){
			opt=options[c];
			if(opt.selected){
				attrvalue=opt.value;
				if(!isMulti){					
					custnode=cust.findNode(inputfield.getAttribute("id"));
				}else{
					vid=parseId(id)[0];
					index=parseId(id)[1];
					str='.//vehicle[@vehicleid=\''+ index + '\']';
					custnode=cust.node.selectNodes(str);
					str='.//'+vid;
					custnode=custnode[0].selectNodes(str);
				}
				if(custnode){
					/* add field validation here */
					custnode.item(0).text=attrvalue;
				}
			}
		} 
	}
}

/*

	getOptions(id)
	retrieves an array of options for a given node name id
*/
function getOptions(id){
 	var optionarray=new Array();
	tmparray=optionsxmlDoc.selectNodes('.//'+ id);
	if(tmparray!=null && tmparray.length>0){
		var optionnodes=tmparray[0].childNodes;
		for(var i=0;i<optionnodes.length;i++){
			optionarray[i]=optionnodes.item(i).text;
		}
	}
	return optionarray;
}

/* 
	function getModels(makeid)
	returns list of models based on make id
*/
function loadModels(document,selectbox){

	/* find the selected option */
	var makeoptions=selectbox.childNodes;
	var selectednode;
	for(var c=0;c<makeoptions.length;c++){
		if(makeoptions[c].selected){
			selectednode=makeoptions[c];	
			break;
		}
	}
	
	/* look up the models based on the make */
	var makeid=selectednode.getAttribute("value").toLowerCase();
	var makenodes=optionsxmlDoc.selectNodes('.//modeldesc[@make=\''+makeid+'\']');
	var index=parseId(selectbox.id)[1];
	var modelnode=document.getElementById("model"+index);
	
	/* remove the existing make options */
	var newoptioncount=makenodes.length;
	var oldoptioncount=modelnode.length;	

	/* add the new make options */
	for(var a=0;a<makenodes.length;a++){
		var optiontext=makenodes.item(a).text;
		modelnode.options(a+1).text=optiontext;
	}
}
/*
	load(viewname)
	loads xhtml based on viewname
	if viewname is null, loads all xhtml docs
*/
function loadView(document,viewname,customer,maxnodes,mode){
	var loaded=false;
	
	/* load html if not present */	
	var appendhere=document.getElementById(viewname);
	var htmlsnippet=appendhere.childNodes;
	if(htmlsnippet==null || htmlsnippet.length==0 
	|| (htmlsnippet.length < maxnodes) || viewname==COVERAGE){
		var tmpcust=null;
		var origvname=viewname;
		var viewdoc=new ActiveXObject("Microsoft.XMLDOM");
    		viewdoc.async=false;    		
    		if(viewname==VEHICLE1 || viewname==VEHICLE2){
    			viewname=parseId(viewname)[0];
    		//}else if(viewname==BILLINGINFO){
    			/* load proper billing section */
			//var qpi=findQuotePolicyItem(customer);
			//if(qpi.status==ISSUEDPOLICY  || qpi.status==ENDORSEMENT || qpi.status==ENDORSEMENTCOMPLETE){
				//viewname="policybillinginfo";
			//}		
		}else if(viewname==PREMIUM){
    			/* load proper billing section */
			var qpi=findQuotePolicyItem(customer);
			if(qpi.status!=ISSUEDPOLICY & qpi.status!=ENDORSEMENT & qpi.status!=ENDORSEMENTCOMPLETE){
				viewname=QUOTEPREMIUMBILLING;
			}		
		}
    		var xmldocpath='data/' + viewname + '.xml';
    		viewdoc.load(xmldocpath);
    		
    		/* load a view */
		if(viewname==COVERAGE){
		    loadCoverages(document,viewdoc,customer,viewname,mode);
		}  else{
		    viewdoc=populateFields(document,viewdoc,customer,origvname,mode);
		    addElementToDom(document,viewdoc,origvname,customer);
		}		
    		loaded=true; 
    	}
	if(viewname==PREMIUM || viewname==QUOTEPREMIUMBILLING){
		hideShowPremium(customer);
	}
	if(viewname==COVERAGE){
		hideShowCoverages(customer);
	}
	
	return loaded;
}
/*
	populateFields(doc,viewdoc,customer,viewname,mode)
	given a view and customer node, set the html value
*/
function populateFields(doc,viewdoc,customer,viewname,mode){

	var id,tnodeid,pnodeid,tnode,pnodeid,vnode,htmlstring,nodetext,labelnode,index,cnodes;
	var isDisabled;
	var origviewname=viewname;
	
	/* determine display mode */
	if(mode=="disabled"){isDisabled=true;}else{isDisabled=false;}
	
	/* determine if multi type node, just vehicle for now */
	var isMulti=isMultiNode(viewname);
	if(isMulti){
		id=getViewNameId(viewname);
		viewname=parseId(viewname)[0];
		index=parseId(origviewname)[1];
	}
	
	/* look for the customer node with that id */
	cnodes=customer.node.selectNodes('.//'+viewname);
			
	/* get input fields */
	var textnodes=viewdoc.getElementsByTagName("input");
	
	/* get the node with this id */
	var cnode=cnodes[0];
	if(isMulti){
		if(origviewname=="coverage1" || origviewname=="coverage2"){
			var str='.//vehicle[@vehicleid=' + index + ']/coverage';
			cnode=customer.node.selectNodes(str);
		}else{		
			var selectstring='.//'+viewname +'[@' + id + '=' + index +']';
			cnode=customer.node.selectNodes(selectstring);
		}
	}	
	
	/* scroll through each input field */
	for(var i=0;i<textnodes.length;i++){		
		
		var tnode = textnodes[i];
		tnodeid=tnode.getAttribute('id');
					
		if(tnode.getAttribute("type").toLowerCase() =='text'){
			
			/* set the text */
			if(isMulti){
				/* set the field label id */
				labelnode=findSibling(tnode,'label');
				labelnode.setAttribute('for',tnodeid);
				var vnode=cnode[0].selectNodes('.//'+tnodeid);
				nodetext=vnode.item(0).text;
			}else{
				nodetext=customer.getFieldValue(tnodeid);
			}
			if(nodetext!=null && nodetext.length>0){
				tnode.setAttribute("value",nodetext);				
			}else{				
				tnode.setAttribute("value","");
			}
		}else if(tnode.getAttribute("type").toLowerCase() =='checkbox'){
			tnodeid=tnode.getAttribute('id');
			if(isMulti){
				vnode=cnode[0].selectNodes('.//'+tnodeid);
				nodetext=vnode.item(0).text;
			}else{
				nodetext=customer.getFieldValue(tnodeid);
			}
			
			if(nodetext=="yes"){
				tnode.setAttribute("checked","checked");
			}else if(tnode.getAttribute("checked")=="checked"){
				tnode.removeAttribute("checked");
			}
		}else if(tnode.getAttribute("type").toLowerCase() =='radio'){
			
			pnode=tnode.parentNode;
			while(pnode.nodeName!="fieldset"){pnode=pnode.parentNode}
			pnodeid=pnode.getAttribute("id");
			if(isMulti){
				str='.//'+pnodeid;
				vnode=cnode[0].selectNodes(str);
				if(vnode==null || vnode.length<1){
					/* fieldset name has already been changed */
					vid=parseId(pnodeid)[0];
					str='.//'+vid;
					vnode=cnode[0].selectNodes(str);
					tnode.setAttribute("name",pnodeid);
				}else{
					/* set the fieldset id if first time through */
					pnode.setAttribute("id",pnodeid + index);
					tnode.setAttribute("name",pnodeid + index);
				}
				nodetext=vnode.item(0).text;
			}else{
				nodetext=customer.getFieldValue(pnodeid);
			}				
			if(nodetext==null || nodetext.length<1){
				continue;
			}
			/* check/uncheck the radio button according to customer node value */
			if(tnode.getAttribute("value")==nodetext){
				tnode.setAttribute("checked","checked");
			}else if(tnode.getAttribute("checked")=="checked"){
				tnode.removeAttribute("checked");
			}	
		}
		/* set display mode */
		if(isDisabled){
			var tnodeType = tnode.getAttribute('type');
			if ((tnodeType.indexOf('radio') >= 0) || (tnodeType.indexOf('checkbox') >= 0)) {
				tnode.setAttribute("disabled","disabled");
			} else {
				var c = 'disabled ' + tnode.getAttribute('class');
				tnode.setAttribute('class', c);
			}
		}
		/* make a unique id if this is a multi-value node */
		if(isMulti){
			if(tnode.getAttribute("type").toLowerCase() !='radio'){
				tnode.setAttribute("id",tnodeid + index);
			}
			/* set the tab index for the second multi-value node */
			if(index=="2"){
				var tindex=parseInt(tnode.getAttribute("tabindex"));
				tnode.setAttribute("tabindex",String(tindex + 500));
			
			}
		}	
	}
		
	/* set the select boxes */	
	textnodes=viewdoc.getElementsByTagName("select");
	for(var a=0;a<textnodes.length;a++){
	
		var tnode = textnodes[a];	
		tnodeid=tnode.getAttribute('id');
		if(isMulti){
			/* set the field label */
			//labelnode=findSibling(tnode,'label');
			//labelnode.setAttribute('for',tnodeid);
			var vnode=cnode[0].selectNodes('.//'+tnodeid);
			nodetext=vnode.item(0).text;
			tnode.setAttribute("id",tnodeid + index);
		}else{
			nodetext=customer.getFieldValue(tnodeid);
		}
				
		var optionsarray=new Array();
		if(tnodeid=="model"){
			var firstmodel;
			var firstmodelid;
			var customerMake=cnode[0].selectNodes('.//make');
			/* set model value according to customer make, if present */
			if(customerMake && customerMake.item(0).text.length>0){
				firstmodeltext=customerMake.item(0).text; //Jeep
				var str='.//makedesc[text()=\'' + firstmodeltext + '\']';
				firstmodel=optionsxmlDoc.selectNodes(str);			
			}else{
				firstmodel=optionsxmlDoc.selectNodes('.//makedesc');				
			}
			firstmodelid=firstmodel[0].getAttribute("id");
			var modelnodes=optionsxmlDoc.selectNodes('.//modeldesc[@make=\''+firstmodelid+'\']');
			for(var d=0;d<modelnodes.length;d++){
				optionsarray[d]=modelnodes.item(d).text;
			}
		}else{
			optionsarray=getOptions(tnodeid);
		}
		
		for (var b=0;b<optionsarray.length;b++){  
			var opt=optionsarray[b];
			var newOpt = viewdoc.createElement("option");
		  	newOpt.text = opt;
		  	newOpt.setAttribute("value",opt);
		  	if(newOpt.getAttribute("value") == nodetext){				
				newOpt.setAttribute("selected","selected");
			}
			tnode.appendChild(newOpt);  
		}
		/* set display mode */
		if(isDisabled){
//			tnode.setAttribute("disabled","disabled");
			var c = 'disabled ' + tnode.getAttribute('class');
			tnode.setAttribute('class', c);
		}
		/* set the tab index for the second multi-value node */
		if(index=="2"){
			var tindex=parseInt(tnode.getAttribute("tabindex"));
			tnode.setAttribute("tabindex",String(tindex + 500));
		}
	}
	
	return viewdoc;
}

/* 
	loadCoverages(document,viewdoc,customer,viewname,mode)
	loads a coverage for each vehicle 
*/
function loadCoverages(document,viewdoc,customer,viewname,mode){
	var vehicles=customer.findNode("vehicle");
    	var vehiclecount=vehicles.length;
    	var index=0;
    	
	var labelviewdoc=new ActiveXObject("Microsoft.XMLDOM");
    	labelviewdoc.async=false;    		
    	
    	var labelxmldocpath='data/' + viewname + 'label.xml';
    	labelviewdoc.load(labelxmldocpath);
    	
	/* save the original xml */
    	var pureXML=viewdoc.xml;
    	var vehicleHTML=labelviewdoc.xml;
    	
 	for(var a=0;a<vehiclecount;a++){
    		index++;
    		var viewname="coverage"+index;
    		viewdoc=populateFields(document,viewdoc,customer,viewname,mode);
 		
 		/* set the coverage ids */
		var labels = viewdoc.getElementsByTagName("td");
 		for(var i=0;i<labels.length;i++){
 			var labelnode=labels[i];
 			var labelid=labelnode.getAttribute("id");
 			if(labelid=="premiumAmount1" || labelid=="premiumAmount2"|| labelid=="coveragepremium"){
 				labelnode.setAttribute("id",labelid + index);
 				/* set vehicle 2 premium differently */
 				if(index=="2"){
 					if(labelid=="premiumAmount1"){
 						labelnode.text="$265.00";
 					}else if(labelid=="premiumAmount2"){
 						labelnode.text="$55.00";
 					}else if(labelid=="coveragepremium"){
 						labelnode.text="$320.00";
 					}
				}
 			}
		}
		
    		/* set the make, model, year, premium in section */
    		var makeModelYearTxt=getMakeModelYear(document,customer,index);

    		var legenddnode=viewdoc.getElementsByTagName("th");
		for(var b=0;b<legenddnode.length;b++){
			var lnode=legenddnode[b];
			if(lnode.getAttribute("id")=="yearmakemodel"){
				lnode.setAttribute("id",("yearmakemodel"+index));
				lnode.text=makeModelYearTxt;
			}
		}    		

    		vehicleHTML=vehicleHTML+viewdoc.xml;
    		viewdoc.loadXML(pureXML);
    	}
    	vehicleHTML="<div class=\"threeColumns\"> "+vehicleHTML +"<div class=\"clear\"></div></div>";
    	viewdoc.loadXML(vehicleHTML);     	
    	addElementToDom(document,viewdoc,COVERAGE,customer);
    	
}
function addElementToDom(doc,viewdoc,viewname,customer){
	
	/* append node */
	var appendhere=doc.getElementById(viewname);
	appendhere.innerHTML=viewdoc.xml;
	
	/* set up smartpicks */
	doc.SmartPickController.setupSmartPicks(appendhere);

	/* append onchange event to each node 
	event must occur after the field is created in the browser */
	var pid=customer.getAttributeValue('policy','pid');
	//textnodes=doc.getElementsByTagName("input");
	textnodes=findChildElements(appendhere, function (e) { if (e.tagName) { if(e.tagName.toLowerCase() == 'input'){return e; } }});
	for(var i=0;i<textnodes.length;i++){
		addEvent(textnodes[i], "focus", function () { QuotePolicyController.focusField(pid); });
		addEvent(textnodes[i], "blur", function () { QuotePolicyController.unfocusField(pid); });
		if (!hasClassName(textnodes[i], 'smartPick')) // this event is set up for smart picks already
			addEvent(textnodes[i],"change",function(){QuotePolicyController.updateSectionLocation(pid,viewname,doc,this)});
	}
	textnodes=doc.getElementsByTagName("select");
	for(var i=0;i<textnodes.length;i++){
		addEvent(textnodes[i],"change",function(){QuotePolicyController.updateSectionLocation(pid,viewname,doc,this)});
	}
}

defaultDriverMarital = {
	doc: null,
	customer: null,
	tnode: null,
	execute: function () {
		var imaritalstatus=this.tnode.getAttribute("value");
		if(imaritalstatus){
			this.customer.setFieldValue("dmaritalstatus",imaritalstatus);
			if(this.doc.getElementById("dmaritalstatus")){				
				var dnode=this.doc.getElementById("dmaritalstatus");
				dnode.setAttribute("value",imaritalstatus);
				this.doc.thisData.updateField(dnode); // dw: update field count
			}
		}
	}
}

/* sets other section values based on name & address section values */
function setDefaultDriver(doc,customer,tnode){
	/* default relationship to insured */
	
	if(tnode.getAttribute("id")=="ifirstname"){
		var fname=tnode.getAttribute("value");
		if(fname){
			customer.setFieldValue("dfirstname",fname);
			if(doc.getElementById("dfirstname")){				
				var dnode=doc.getElementById("dfirstname");
				dnode.setAttribute("value",fname);
				doc.thisData.updateField(dnode); // dw: update field count
			}
		}
		return true;
	}else if(tnode.getAttribute("id")=="ilastname"){
		var lname=tnode.getAttribute("value");
		if(lname){
			customer.setFieldValue("dlastname",lname);
			if(doc.getElementById("dlastname")){				
				var dnode=doc.getElementById("dlastname");
				dnode.setAttribute("value",lname);
				doc.thisData.updateField(dnode); // dw: update field count
			}
		}
		return true;
	}else if(tnode.getAttribute("id")=="imaritalstatus"){
		defaultDriverMarital.doc = doc;
		defaultDriverMarital.customer = customer;
		defaultDriverMarital.tnode = tnode;
		setTimeout('defaultDriverMarital.execute()', 500);
		return true;
	}else if(tnode.getAttribute("id")=="zip"){
		var zip=tnode.getAttribute("value");
		if(zip){
			/* set each vehicle's zip code */
			var vehicles=customer.node.selectNodes('.//vehicle');
			for(var d=0;d<vehicles.length;d++){
				var currvehicle=vehicles[d];
				var vzipcode=currvehicle.selectNodes('.//garagezipcode');
				vzipcode.item(0).text=zip;
			}
			if(doc.getElementById("garagezipcode1")){				
				var dnode=doc.getElementById("garagezipcode1");
				dnode.setAttribute("value",zip);
				doc.thisData.updateField(dnode); // dw: update field count
			}
			if(doc.getElementById("garagezipcode2")){	
				dnode=doc.getElementById("garagezipcode2");
				dnode.setAttribute("value",zip);
				doc.thisData.updateField(dnode); // dw: update field count
			}
		}
		return true;	
	}
	return false;
}

/*
	setDefaultDisplay()
	sets default display when quote/policy is first opened
*/
function setDefaultDisplay(winname,document,customer){

	var datefield=document.getElementById("createdBar");
	
	// set policy status	
	var statusattr=customer.getAttributeValue("policy","status");
	var status=customer.getFieldValue("status");
	/*
	var statusnode=document.getElementById("quotepolicystatus");
	if(statusnode.childNodes.length>1)
	{
		thisTxt = document.createTextNode("Status: " + status);
		statusnode.replaceChild(thisTxt,statusnode.childNodes[1]);
	}
	else
	{
		thisTxt = document.createTextNode("Status: " + status);
		statusnode.appendChild(thisTxt);
	}
	*/
	//new quote 
	if(statusattr!=null && statusattr.length>0){
		/* set the timestamp */
		var thisDte=document.createTextNode("Created: " + getCurrentDateTime());
		datefield.appendChild(thisDte);
		customer.setFieldValue("effectivedate",getCurrentDate());
		
		var effectivedateText=document.getElementById("effectivedate");
		if( effectivedateText != null )
		{
			effectivedateText.value = getCurrentDate();
		}
		/* remove new quote indicator */
		customer.removeAttribute("policy","status");
		
		/* Open name & address section */
		//var thisLink=document.getElementById("ADDRESSLINK");
		//toggleFields(winname,thisLink,document,customer,'personalinfo',1);
		
		/* Set focus on the 1st Name field */
		//var firstfield=document.getElementById("ifirstname");
		//firstfield.focus();
		
		// show 'driver 1' and 'vehicle 1' as links that open that section
		var namenode=document.getElementById("drivername");
		var thisTxt = document.createTextNode("Driver 1");
		namenode.appendChild(thisTxt, namenode.childNodes[0]);
				
		namenode=document.getElementById("vehiclename1");
		thisTxt = document.createTextNode("Vehicle 1");
		namenode.appendChild(thisTxt, namenode.childNodes[0]);
		
		/* hide vehicle 2 */
		namenode=document.getElementById("vehiclename2");
		var pnode=namenode.parentNode;
		while(pnode.nodeName.toLowerCase()!="dt"){pnode=pnode.parentNode}
		if (!hasClassName(pnode, 'hidden')) {
			addClassName(pnode, 'hidden');
		}		
		
	//existing quote or policy
	}else{
	
		/* policy */
		if(status==ISSUEDPOLICY){
			displayPolicyHeader(document,customer);			
		}
		
		/* set the effective date */
		var effectiveDate=customer.getFieldValue("effectivedate");
		var thisDte=document.createTextNode(effectiveDate);
		datefield.appendChild(thisDte);
		
		/* set driver section name */
		var firstnamenodes=customer.findNode("dfirstname");
		var lastnamenodes=customer.findNode("dlastname");
		var drivername="Driver 1";		
		if(firstnamenodes && lastnamenodes){
			var fname=firstnamenodes.item(0).text;
			var lname=lastnamenodes.item(0).text;
			if(fname && lname){
				drivername=fname + " " + lname;
			}
		}		
		
		var namenode=document.getElementById("drivername");
		var thisTxt = document.createTextNode(drivername);
		namenode.appendChild(thisTxt, namenode.childNodes[0]);
		
		/* set vehicle section name */
		var vehiclenodes=customer.findNode("vehicle");
		for(var b=1;b<=vehiclenodes.length;b++){
			var vehiclenode=vehiclenodes[b-1];
			var vname="vehiclename"+b;
			namenode=document.getElementById(vname);
			var oldTxtNode=namenode.childNodes[0];		
						
			var vehicleyear=vehiclenode.selectNodes(".//modelyear");
			var vehiclemake=vehiclenode.selectNodes(".//make");
			var vehiclemodel=vehiclenode.selectNodes(".//model");
			var vehiclesectioname=vehicleyear.item(0).text + " " + vehiclemake.item(0).text + " " + vehiclemodel.item(0).text;
			
			if(!vehicleyear || vehicleyear[0].text.length<1 ||
			!vehiclemake || vehiclemake[0].text.length<1 ||
			!vehiclemodel || vehiclemodel[0].text.length < 1){
				var vehiclesectioname="Vehicle " + b;
			}
			thisTxt = document.createTextNode(vehiclesectioname);
			namenode.appendChild(thisTxt);
		
		}
		/* hide vehicle 2 */
		if(vehiclenodes.length<2){		
			namenode=document.getElementById("vehiclename2");
			var pnode=namenode.parentNode;
			while(pnode.nodeName.toLowerCase()!="dt"){pnode=pnode.parentNode}
			if (!hasClassName(pnode, 'hidden')) {
				addClassName(pnode, 'hidden');
			}
		}		
	}
	if(status!=ISSUEDPOLICY){
		/* hide the billing section */
		hideSection(document,"billinginfolink");
		
		if(status!=ENDORSEMENT & status!=ENDORSEMENTCOMPLETE){
			displayPremiumHeader(document,"Premium Overview and Billing");
		}
	}
}
function issuePolicy(document,customer){
	/* are you sure message */
	document.confirmWindow.showMsg('You are about to issue this policy.  Are you sure you want to proceed?<p><a href="#" onclick="confirmWindow.hide();opener.displayIssuePolicyConfirmation(this.document,document.customer);">' + yesEndorsementButton + '</a>&nbsp;&nbsp;<a href="#" onclick="confirmWindow.hide();return(false);">' + noEndorsementButton + '</a>');
}
function displayIssuePolicyConfirmation(document,customer){	
	var polNum=customer.getAttributeValue("policy","pid");
	
	/* alert display */
	document.confirmWindow.showMsg('You have succesfully issued a policy for:<p>'+ customer.getFieldValue("ifirstname") +' ' + customer.getFieldValue("ilastname") + '<p><a href="#" onclick="opener.QuotePolicyController.closeItem(' + polNum + ')">' + closePolicyButton + '</a>&nbsp;&nbsp;<a href="#" onclick="confirmWindow.hide();return(false);">' + backToPolicyButton + '</a>');
	
	/* change customer status */
	var issuedPolicyTxt=ISSUEDPOLICY;
	customer.setFieldValue("status",issuedPolicyTxt);
	
	/* save data */
	save(document,customer);
	
	/* delay */
	
	/* remove all so sections can reload in read mode */
	reloadPolicy(document);
	
	/* set to read mode */
	setDisplayMode(customer,"disabled");

	/* set status of item*/
	var quotepolicyitem=QuotePolicyController.findItem(polNum);
	quotepolicyitem.setStatus(issuedPolicyTxt);
	
	/* display the policy header */
	displayPolicyHeader(document,customer);

	/* display Open for Endorsements Message */
	var windowMsg=document.getElementById("windowStatusMessage");
	if(hasClassName(windowMsg,'hidden')){
		removeClassName(windowMsg,'hidden');
	}
	windowMsg.innerHTML=confirmationCheckMark+ " You have successfully issued this policy."
	
	/* reset the Premium Header */
	displayPremiumHeader(document,"Premium Details");
}

function reloadPolicy (document) {
	var ddnodes=document.getElementsByTagName("DD");
	for(var a=0;a<ddnodes.length;a++){
		var thisDD=ddnodes[a];		
		if (hasClassName(thisDD, 'visible')){
			removeClassName(thisDD, 'visible');
		}
		if(thisDD.hasChildNodes()){
			thisDD.removeChild(thisDD.childNodes[0]);
		}
		var thisDT=thisDD.parentNode;
		var arrow = findChildElements(thisDT, function (e) { return hasClassName(e, 'arrow') });
		for(var i=0;i<arrow.length;i++){
			thisArrow=arrow[i];
			/* special case for vehicles since they share the same parent dt */
			if (thisArrow.innerText == 6)
				thisArrow.innerText = 4;
		}
	}
}

function performEndorsement(customer,document){
	/* display Open for Endorsements Message */
	var windowMsg=document.getElementById("windowStatusMessage");
	if(!hasClassName(windowMsg,'hidden')){
		addClassName(windowMsg,'hidden');
	}
	
	/* display popup to capture effective date */
	document.confirmWindow.showMsg('Indicate an effective date for this endorsement:<p><input type=\"text\" id=\"endEffectiveDate\" maxsize=\"10\"><p><a href="#" onclick="confirmWindow.hide();return(false);">' + cancelEndorsementButton + '</a>&nbsp;&nbsp;<a href="#" onclick="confirmWindow.hide();opener.startEndorsement(this.document,document.customer)">' + startEndorsementButton + '</a>');
	var effDate=document.getElementById('endEffectiveDate');
	effDate.focus();
}

function startEndorsement(document,customer){

	/* remove existing readonly nodes from policy */
	reloadPolicy (document);	
	
	/* delay? */
	
	/* change to edit mode */
	setDisplayMode(customer,"enabled");
	
	/* replace perform endorsment button with issue endorsement button */
	var polNum=customer.getAttributeValue("policy","pid");
	var quotepolicyitem=QuotePolicyController.findItem(polNum);
	quotepolicyitem.status=ENDORSEMENT;
	quotepolicyitem.updateState();

	/* display Open for Endorsements Message */
	var windowMsg=document.getElementById("windowStatusMessage");
	if(hasClassName(windowMsg,'hidden')){
		removeClassName(windowMsg,'hidden');
	}
	
	/* hide billing section */
	hideSection(document,BILLINGINFO);
	hideSection(document,"billinginfolink");
	
	windowMsg.innerHTML="Policy:  Open for Endorsements";
	
	updateEffectiveDate(document,customer);
	
}
/*
	issueEndorsement()
	issues an endorsement
*/
function issueEndorsement(customer,document){

	/* are you sure message */
	document.confirmWindow.showMsg('You are about to make changes to this policy.  Are you sure you want to proceed?<p><a href="#" onclick="confirmWindow.hide();opener.displayEndorsementConfirmation(this.document,document.customer);">' + yesEndorsementButton + '</a>&nbsp;&nbsp;<a href="#" onclick="confirmWindow.hide();return(false);">' + noEndorsementButton + '</a>');
}
function displayEndorsementConfirmation(document,customer){
	var polNum=customer.getAttributeValue("policy","pid");
	
	/* save data */
	save(document,customer);

	/* display sections collapsed in read only mode */
	setDisplayMode(customer,"disabled");
	
	/* collapse sections */
	reloadPolicy (document);

	var quotepolicyitem=QuotePolicyController.findItem(polNum);
	quotepolicyitem.status=ISSUEDPOLICY;
	quotepolicyitem.updateState();
	document.confirmWindow.showMsg('You have succesfully changed the address and added a vehicle:<p>2003 Chevrolet Malibu<p><p><a href="#" onclick="opener.QuotePolicyController.closeItem(' + polNum + ')">' + closePolicyButton + '</a><a href="#" onclick="confirmWindow.hide();return(false);">' + backToPolicyButton + '</a>');

	/* Remove Open for Endorsements Message */
	/* display Open for Endorsements Message */
	var windowMsg=document.getElementById("windowStatusMessage");
	if(hasClassName(windowMsg,'hidden')){
		removeClassName(windowMsg,'hidden');
	}	
	windowMsg.innerHTML=confirmationCheckMark+" Policy:  You have successfully issued this endorsement.";
	
	/* unhide billing section */
	unhideSection(document,"billinginfolink");
	unhideSection(document,BILLINGINFO);
}

function payBill(customer,document){
	var polNum=customer.getAttributeValue("policy","pid");		
	
	/* save */
	save(document,customer);
	
	/* delay */
	
	/* display confirmation */
	document.confirmWindow.showMsg('You have succesfully made a payment for:<p>$444.20<p><p><a href="#" onclick="opener.QuotePolicyController.closeItem(' + polNum + ')">' + closePolicyButton + '</a>&nbsp;&nbsp;<a href="#" onclick="confirmWindow.hide();return(false);">' + backToPolicyButton + '</a>');	
	
	/* collapse sections */
	reloadPolicy (document);

	/* display Open for Endorsements Message */
	var windowMsg=document.getElementById("windowStatusMessage");
	if(hasClassName(windowMsg,'hidden')){
		removeClassName(windowMsg,'hidden');
	}	
	windowMsg.innerHTML=confirmationCheckMark+" You have successfully made a payment.";
}

/*
	loadBundle(document,customer)
	loads the coverages associated with a bundle
*/
function loadBundle(document,customer,node){	
	
	var coverageArray=new Array('bodilyinjury','propertydamage','medicalexpensebenefit','uninsuredmotorist','uninsuredmotoristpropertydamage','collision','comprehensive','rentalreimbursement','towinglabor','soundsystemcoverage');
	/* determine what coverage was selected */
	var index=parseId(node.getAttribute("id"))[1];
	var selection=node.options[node.selectedIndex].text;

	/* get the list of coverage bundles */
	var str='.//coveragebundledesc[text()=\'' + selection +'\']';
	var selectedoption=optionsxmlDoc.selectNodes(str);
	
	/* match selection up with coverage id */
	var bundleid=selectedoption[0].getAttribute("id");	
	
	for(var a=0;a<coverageArray.length;a++){
		str='.//' + coverageArray[a] + '/*[@' + bundleid +']';
		var selectedoption=optionsxmlDoc.selectNodes(str);
		
		/* get the select box on the form */
		var selectbox=document.getElementById(coverageArray[a]+index);
		
		/* loop through each option until you find the one to set */
		for(var b=0;b<selectbox.options.length;b++){
			opt=selectbox.options[b];
			if(opt.text==selectedoption[0].text){
				opt.setAttribute("selected","selected");
				break;
			}
		}
		document.thisData.updateField(selectbox);
	}
	
}
/* updates section headers and main header based */
function checkUpdateSectionHead(viewname,document,customer){
	var fname,lname;
	/* update policy first name and lastname */
	if(viewname==PERSONALINFO){
		var h1 = document.getElementById('fullname');
		fname=document.getElementById('ifirstname').getAttribute("value");
		lname=document.getElementById('ilastname').getAttribute("value");
		if(fname.length>0 || lname.length>0){
			h1.innerText = fname + " " + lname;
			/* update driver section head */
			var driver = document.getElementById('drivername');
			var txtNode=document.createTextNode(fname + " " + lname);
			driver.replaceChild(txtNode,driver.childNodes[0]);
		}		
	/* update vehicle section head */	
	}else if(viewname==VEHICLE1 || viewname==VEHICLE2){
		var index=parseId(viewname)[1];
		var makeModelYearTxt=getMakeModelYear(document,customer,index);
		
		var vehicle = document.getElementById("vehiclename"+index);
		var txtNode=document.createTextNode(makeModelYearTxt);
		vehicle.replaceChild(txtNode,vehicle.childNodes[0]);
	}

}
function hideShowPremium(customer){
	var polNum=customer.getAttributeValue("policy","pid");
	var quotepolicyitem=QuotePolicyController.findItem(polNum);
	var policystatus=quotepolicyitem.status;
	if(policystatus=="Quote Complete" || policystatus==ISSUEDPOLICY || policystatus==ENDORSEMENTCOMPLETE){
		quotepolicyitem.showHidePremium('visible');
	}else{
		quotepolicyitem.showHidePremium('hidden');
	}
}
function hideShowCoverages(customer){
	var polNum=customer.getAttributeValue("policy","pid");
	var quotepolicyitem=QuotePolicyController.findItem(polNum);
	var policystatus=quotepolicyitem.status;
	if(policystatus=="Quote Complete" || policystatus==ISSUEDPOLICY || policystatus==ENDORSEMENTCOMPLETE){
		quotepolicyitem.showHideCoverages('visible');
	}else{
		quotepolicyitem.showHideCoverages('hidden');
	}
}
function setDate(node){
	var dateString=node.getAttribute("value");
	var dateString=formatDate(dateString);
	node.setAttribute("value",dateString);

}

/*****************************/
/* helper functions		*/
/*****************************/
/*
	isNum(valueToCheck)
	returns true of valueToCheck is a number, false if not
*/
function isNum(valueToCheck){
	for(var i=0;i<valueToCheck.length;i++){
		var chartocheck=valueToCheck.charAt(i);
		var code=chartocheck.charCodeAt(0);
		if(code < 48 || code > 57){
			return false;
		}
	}
	return true;
}

/*
	generateId()
	returns a random 9 digit number
*/
function generateId(){
	var id=Math.floor(Math.random()*1000000001);
	return id;
}
function parseId(id){
	var idArray=new Array();
	var index=id.length;
	idArray[0]=id.slice(0,index-1);//nodename
	idArray[1]=id.slice(-1);//index
	return idArray;
}
function getViewNameId(viewname){
	var id=null;
	if(viewname==VEHICLE1|| viewname==VEHICLE2){
		id="vehicleid";
		isMulti=true;
	}
	return id;
}

function isMultiNode(viewname){
	var id=null;
	if(viewname==VEHICLE1  || viewname==VEHICLE2 
	|| viewname==COVERAGE || viewname=="coverage1" 
	|| viewname=="coverage2"){
		return true;
	}
	return false;
}
function findSibling(currentnode,siblingid){

	var i = 0;
	var header = currentnode.parentNode;
	var siblings = header.childNodes;
	while (siblings[i].tagName.toLowerCase() != siblingid) {i++; }	
	return(siblings[i]); 
}
function checkViewName(currentnode){
	while(currentnode.tagName.toLowerCase()!='dd'){currentnode=currentnode.parentNode}
	return currentnode.getAttribute("id");
}
function getCurrentDate(){
	var now=new Date();
	return ((now.getMonth()+1) + "/" + now.getDate()+ "/" + now.getYear());
}
function getCurrentDateTime()
{
	var now=new Date();
	var hours=now.getHours();
	var seconds=now.getSeconds();
	var minutes=now.getMinutes();
	var ampm=" AM";
	if(hours>12)
	{
		hours=hours-12;
		ampm=" PM";
	}
	if(minutes<10)
	{
		minutes='0'+minutes;
	}
	return ((now.getMonth()+1) + "/" + now.getDate()+ "/" + now.getYear().toString().substring( 2, 4 ) + " " + hours +":" + minutes+ampm);
}
function setDisplayMode(customer,mode){
	var pid=customer.getAttributeValue("policy","pid");
	var quotepolicyitem=QuotePolicyController.findItem(pid);
	quotepolicyitem.displayMode=mode;
}
function getMakeModelYear(document,customer,index){
	var maketext,modeltext,modelyeartext;
	
	var defaultVehicleName="Vehicle " + index;
	var make=document.getElementById('make' + index);			
	var model=document.getElementById('model'+index);
	var modelyear=document.getElementById('modelyear'+index);
	
	if(!make || !model || !modelyear){
		/* no field values on doc so check customer */
		var vehicle=customer.node.selectNodes('.//vehicle[@vehicleid='+index+']');
		var veh=vehicle[0];
		
		make=veh.selectNodes('.//make');		
		model=veh.selectNodes('.//model');		
		modelyear=veh.selectNodes('.//modelyear');
		
		maketext=make[0].text;
		modeltext=model[0].text
		modelyeartext=modelyear[0].text;
	}else{
		modelyeartext=modelyear.getAttribute("value");
		maketext = make.value;
		modeltext = model.value;
	}			
	
	if(modelyeartext.length>0 || maketext.length>0 || modeltext.length>0){
		txtNode=modelyeartext + " " + maketext + " "+ modeltext;
		return txtNode;
	}
	return defaultVehicleName;
}
function displayPolicyHeader(document,customer){
	/* display policy header */
	var header=document.getElementById("mainBar");
	if (!hasClassName(header, 'hidden')) {
		addClassName(header, 'hidden');
	}
	
	var issuePolicyButton2 = document.getElementById('issuePolicyButton2');
	if(issuePolicyButton2){
		addDisplayStyle( issuePolicyButton2, "none" );
	}
	
	header=document.getElementById("mainBarPolicy");
	if (hasClassName(header, 'hidden')) {
		removeClassName(header, 'hidden');
	}
	
	/* display policy number, effective date, current premium */
	var fullname=document.getElementById("fullNamePolicy");
	var effectiveDate=document.getElementById("effectiveDateData");
	var policyNum=document.getElementById("policyNumberData");	
	var totalPremium=document.getElementById("currentPremiumData");
	var statusMsg=document.getElementById("windowStatusMessage");
	
	var name=customer.getFieldValue("ifirstname") + " " + customer.getFieldValue("ilastname");
	var effDate=customer.getFieldValue("effectivedate");
	var polNum=customer.getAttributeValue("policy","pid");
	var totPolPrem=customer.getFieldValue("totalpolicypremium");
	
	fullname.innerHTML= name;
	effectiveDate.innerHTML= effDate;
	policyNum.innerHTML= polNum;
	totalPremium.innerHTML= totPolPrem;	
	
//	var polEffectiveDate=document.getElementById("policyEffectiveDate");
//	addDisplayStyle( polEffectiveDate, "none");

	/* replace perform endorsment button with issue endorsement button */
	var polNum=customer.getAttributeValue("policy","pid");
	var quotepolicyitem=QuotePolicyController.findItem(polNum);
	quotepolicyitem.status=ISSUEDPOLICY;
	quotepolicyitem.updateState();
	
	var reqFields=getElementsByStyleClass(document,'requiredFieldsTally');
	for(var a=0;a<reqFields.length;a++){
		reqField=reqFields[a];
		if (!hasClassName(reqField, 'hidden')) {
			addClassName(reqField, 'hidden');
		}
	}

}
/* 	
	updates endorsement effective date based on
	the date supplied in the pop-up box
*/
function updateEffectiveDate(document,customer){
	var effDate=document.getElementById('endEffectiveDate');
	var effectiveDateEndorsement=document.getElementById('effectiveDateEndorsement');
	var formattedDate=formatDate(effDate.getAttribute("value"));
	effectiveDateEndorsement.innerHTML="Effective Date: " + formattedDate;
	var endEffectiveDate=document.getElementById('endEffectiveDate');
	
	/* remove the floating text box field so it's not included in save */
	var pnode=endEffectiveDate.parentNode;
	pnode.removeChild(endEffectiveDate);
}
/*

*/
function findQuotePolicyItem(customer){
	var polNum=customer.getAttributeValue("policy","pid");
	var quotepolicyitem=QuotePolicyController.findItem(polNum);
	return quotepolicyitem;
}
/*

	formatDate(dateString)
*/
function formatDate(dateString){
	if(!dateString || dateString.length<4){return dateString;}
	var re = /(\d+)[\.\-\/\s]+(\d+)[\.\-\/\s]+(\d+)/;
	var re1=/^(\d{2})(\d{2})(\d{2})$/; // 01/01/04 (6);
	var re2=/^(\d{2})(\d{2})(\d{4})$/; // 01/01/2004 (8);
	var re3=/^(\d{1})(\d{1})(\d{2})$/; // 1/1/04 (4);
	
	var part1,part2,part3,formattedString;
	
	if(dateString.match(re1)){
		//alert('matching re1');
		part1 = RegExp.$1;
		part2 = RegExp.$2;
		part3 = RegExp.$3;
		if (part3 < 100) part3 = parseInt(part3, 10) + 2000;
		formattedString=part1 + "/" + part2 + "/" + part3;
	}else if(dateString.match(re2)){
		//alert('matching re2');
		part1 = RegExp.$1;
		part2 = RegExp.$2;
		part3 = RegExp.$3;
		formattedString=part1 + "/" + part2 + "/" + part3;
	}else if (dateString.match(re)){
		part1 = RegExp.$1;
		part2 = RegExp.$2;
		part3 = RegExp.$3;
		if (part3 < 100) part3 = parseInt(part3, 10) + 2000;
		formattedString=part1 + "/" + part2 + "/" + part3;		
	}else if(dateString.match(re3)){
		part1 = RegExp.$1;
		part2 = RegExp.$2;
		part3 = RegExp.$3;
		if (part3 < 100) part3 = parseInt(part3, 10) + 2000;
		formattedString=part1 + "/" + part2 + "/" + part3;
	}else {
		formattedString = dateString;
	} 
	//alert("Extracted date as " + formattedString);
	return formattedString;
}
/*
	returns the vehicles for a customer
*/
function getCustomerVehicles(customer){
	return(vehicles=customer.node.selectNodes('.//vehicle'));
}
/*
	returns the number of vehicles for a customer
*/
function getCustomerVehicleCount(customer){
	return getCustomerVehicles(customer).length;	
}
function hideSection(document,sectionName){
	var section=document.getElementById(sectionName);
	if(!section){return;}
	if (!hasClassName(section, 'hidden')) {
		addClassName(section, 'hidden');
	}
}
function unhideSection(document,sectionName){
	var section=document.getElementById(sectionName);
	if(!section){return;}
	if (hasClassName(section, 'hidden')) {
		removeClassName(section, 'hidden');		
	}
}
function displayPremiumHeader(document,headerText){
	var premium=document.getElementById("premiumheader");
	if(!premium){return;}
	premium.innerText=headerText;
}
function checkHideUnhide(document,inputfield,sectionname,mode){
	if(inputfield.type.toLowerCase() =='text'){
		if(inputfield.value & inputfield.value.length>0){
			mode="show";
		}else{
			mode="hide";
		}
	}
	if(mode=="show"){
		unhideSection(document,sectionname);
	}else{
		hideSection(document,sectionname);
	}
}
