

/*****************************/
/* functions		     */
/*****************************/

/*
	findChildElements (e, f)
	find all the children of e (inclusive) that satisfy function f
*/
function findChildElements (e, f) {
	var r = new Array();
	for (var c=0; c<e.childNodes.length; c++)
		r = r.concat(findChildElements(e.childNodes[c], f));
	if (f(e))
		r.push(e);
	return r;
}


/*
	findFirstParent (e, f)
	find the first parent of e (inclusive that satisfies function f
*/
function findFirstParent (e, f) {
	while (!f(e))
		e = e.parentNode;
	return e;
}

/*
	getElementsByClassName (c)
	returns an array of all elements with class c
*/
document.getElementsByClassName = function (c) {
	return findChildElements(document, function (e) { return hasClassName(e, c) });
}


/*
	hasClassName (el, c)
	returns true if element el has class c
*/
function hasClassName (el, c) {
	if (el.className) {
		var cArr = el.className.split(/\s+/);
		for (var i=0; i<cArr.length; i++)
			for (var i in cArr)
				if (cArr[i] == c) return true;
		return false;
	} else {
		return false;
	}
}


/*
	addClassName (el, c)
	adds class c to element el unless el already has c
*/
function addClassName (el, c) {
	if (!hasClassName(el, c))
		el.className = (el.className == "") ? c : el.className + " " + c;
}


/*
	removeClassName (el, c)
	removes class c from element el
*/
function removeClassName (el, c) {
	var cArr = el.className.split(/\s+/);
	for (var i in cArr)
		if (cArr[i] == c)
			cArr.splice(i, 1);
	el.className = cArr.join(' ');
}

/*
	hasDisplayStyle (el, ds)
	returns true if element el has style.display ds
*/
function hasDisplayStyle (el, ds) 
{
	if (el.style.display) 
	{
		var sArr = el.style.display.split(/\s+/);
		for (var i=0; i<sArr.length; i++)
			for (var i in sArr)
				if (sArr[i] == ds) return true;
		return false;
	} 
	else 
	{
		return false;
	}
}

/*
	addDisplayStyle (el, ds)
	adds style.display ds to element el unless el already has ds
*/
function addDisplayStyle (el, ds) 
{
	if (!hasDisplayStyle(el, ds))
		el.style.display = (el.style.display == "") ? ds : el.style.display + " " + ds;
  	
}


/*
	removeDisplayStyle (el, ds)
	removes style.display ds from element el
*/
function removeDisplayStyle (el, ds) {
	var sArr = el.style.display.split(/\s+/);
	for (var i in sArr)
		if (sArr[i] == ds)
			sArr.splice(i, 1);
	el.style.display = sArr.join(' ');
}


/*
	inArray (testArray, item)
	returns true if item is in testArray; otherwise, returns false
*/
function inArray (testArray, item) {
	for (var k in testArray)
		if (testArray[k] == item)
			return true;
	return false;
}


/*
	addEvent (elm, evType, fn)
	attach function fn to the event evType of element elm
		cross-browser method to attach functions to events
		it can handle adding multiple functions to a single event
		even in mac ie!
*/
function addEvent (elm, evType, fn) {
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, false);
		return true;
	} else if (elm.attachEvent) {
		return elm.attachEvent('on' + evType, fn);
	} else {
		if (!elm['_'+evType]) {
			elm['_'+evType] = new Array(fn);
			elm['on' + evType] = function () {
				for (var i in elm['_'+evType])
					elm['_'+evType][i]();
			};
		} else {
			elm['_'+evType][elm['_'+evType].length] = fn;
		}
	}
}


/*
	removeEvent (elm, evType, fn)
	remove function fn from event evType of element elm
*/
function removeEvent (elm, evType, fn) {
	if (elm.removeEventListener) {
		elm.removeEventListener(evType, fn, false);
		return true;
	} else if (elm.detachEvent) {
		return elm.detachEvent('on' + evType, fn);
	} else {
		if (elm['_'+evType]) {
			for (var i in elm['_'+evType]) {
				var thisEv = elm['_'+evType][i];
				if (thisEv == fn)
					elm['_'+evType].splice(i, 1);
			}
		}
	}
}


/*
	searchClear (field, focus)
	handles the search field on blur and focus
*/
function searchClear (field, focus) {
	var defaultString = "enter name or policy #";
	if ((field.value == defaultString) && focus) {
		field.value = "";
		addClassName(field, 'on');
	} else if ((field.value == "") && !focus) {
		field.value = defaultString;
		removeClassName(field, 'on');
	}
}


/*
	Floating Window class
	handles all functions with floating windows
	build it by passing the id of the floating window
*/
function FloatingWindow (doc, id, greybg) {
	if (doc != undefined)
		this.win = doc.getElementById(id);
	if (this.win) {
		this.x = this.win.offsetLeft;
		this.y = this.win.offsetTop;
	}
	this.greybg = greybg;
	if (greybg)
		this.bg = doc.getElementById('greyBG');
};
var FWP = FloatingWindow.prototype;
FWP.moveTo = function (x,y) {
	this.win.style.left = x + 'px';
	this.win.style.top = y + 'px';
};
FWP.floatBelow = function (item) {
	var o = getOffset(item);
	var x = o[0];
	var y = o[1]+item.offsetHeight;
	this.moveTo(x,y);
	this.show();
};
FWP.floatToRightOf = function (item) {
	var o = getOffset(item);
	var x = o[0]+item.offsetWidth;
	var y = o[1];
	this.moveTo(x,y);
	this.show();
}
FWP.hide = function () {
	addClassName(this.win, 'hidden');
	if (this.greybg)
		addClassName(this.bg, 'hidden');
}
FWP.show = function () {
	removeClassName(this.win, 'hidden');
	if (this.greybg)
		removeClassName(this.bg, 'hidden');
}
FWP = null;


/*
	getOffset (item)
	calculates the top and left offset of the given element
	necessary because browsers calculate this differently
	returns an array [left, top]
*/
function getOffset (item) {
	var left = item.offsetLeft;
	var top = item.offsetTop;
	while (item.offsetParent) {
		item = item.offsetParent;
		left += item.offsetLeft;
		top += item.offsetTop;
	}
	return([left, top]);
}


/*
	QPInfoWindow extends FloatingWindow
*/
function QPInfoWindow (doc, id) {
	FloatingWindow.call(this, doc, id, false);
//	this.contentNode = doc.getElementById('infoWindowMiddle');
	var tmpNode = doc.getElementById('infoWindowMiddle');
	this.contentNode = findChildElements(tmpNode, function (e) { return (hasClassName(e, 'windowContent')) } )[0];
}
QPInfoWindow.prototype = new FloatingWindow();
QPInfoWindow.prototype.showMsg = function (el, msg) {
	this.contentNode.innerHTML = msg;
	
	var elo = getOffset(el);
	var elpo = getOffset(el.parentNode);
	var x = elpo[0]-50;
	var y = elo[1]+el.offsetHeight;
	this.moveTo(x,y);

	this.show();
}

/*
	QPConfirmWindow extends FloatingWindow
*/
function QPConfirmWindow (doc, id) {
	FloatingWindow.call(this, doc, id, true);
	var tmpNode = doc.getElementById('confirmWindowMiddle');
	this.contentNode = findChildElements(tmpNode, function (e) { return (hasClassName(e, 'windowContent')) } )[0];
}
QPConfirmWindow.prototype = new FloatingWindow();
QPConfirmWindow.prototype.showMsg = function (msg) {
	this.contentNode.innerHTML = msg;
	this.show();
}

/*
	newsWindow extends FloatingWindow
*/
function newsWindow (doc, id) {
	FloatingWindow.call(this, doc, id, false);
	this.contentNode = document.getElementById('newsWindowMiddle');
}
newsWindow.prototype = new FloatingWindow ();
newsWindow.prototype.displayNews = function (elm) {
	for (var i=0; i<elm.childNodes.length; i++) {
		if (hasClassName(elm.childNodes[i], 'newsBody')) {
			newsBody = elm.childNodes[i].cloneNode(true);
		}
	}
	removeClassName(newsBody, 'hidden');
	var i=0;
	while (!hasClassName(this.contentNode.childNodes[i], 'newsBody'))
		i++;
	this.contentNode.replaceChild(newsBody, this.contentNode.childNodes[i]);

	this.show();

	var elo = getOffset(elm);
	var x = elo[0]+elm.parentNode.offsetWidth-this.win.offsetWidth+50;
//	alert(elo[0]+', '+elm.offsetWidth+', '+this.win.offsetWidth);
	var y = elo[1]+elm.offsetHeight;
	this.moveTo(x,y);

};


/*
	DismissFloater extends FloatingWindow
*/
function DismissFloater (id) {
	FloatingWindow.call(this, document, id, false);
	this.nameNode = document.getElementById('dismissFloaterName');
	this.timeout;
}
DismissFloater.prototype = new FloatingWindow ();
DismissFloater.prototype.dismiss = function (rowItem) {
	var thisRow = findFirstParent(rowItem, function (e) { return (e.tagName.toLowerCase() == 'tr') });
	var thisNameTD = findChildElements(thisRow, function (e) { return hasClassName(e, 'name'); })[0];
	var thisName = findChildElements(thisNameTD, function (e) { return e.nodeType == 3; })[0];
	this.nameNode.replaceChild(thisName, this.nameNode.childNodes[0]);
	this.floatToRightOf(rowItem);
	clearTimeout(this.timeout);
	this.timeout = setTimeout('DismissFloater.hide()',1500);
	thisRow.parentNode.removeChild(thisRow);
	updateAllTables(document.getElementsByClassName('quotes'));
};


/*
	AlertWindow
*/
function AlertWindow (d) {
	this.win = d.getElementById('alertWindow');
	this.bg = d.getElementById('greyBG');
	var tmp = d.getElementById('alertMiddle');
	this.msgArea = findChildElements(tmp, function (e) { return e.className == 'windowContent' })[0];
}
var AWP = AlertWindow.prototype;
AWP.showMsg = function (m) {
	removeClassName(this.win, 'hidden');
	removeClassName(this.bg, 'hidden');
	this.msgArea.innerHTML = m;
}
AWP.hide = function () {
	addClassName(this.win, 'hidden');
	addClassName(this.bg, 'hidden');
}
AWP = null;


/*
	updateTable (t)
	
	Updates the display of table t
	* hides empty tables, shows tables with data
*/
function updateTable (t) {
	var container = findFirstParent(t, function (e) { return (e.tagName.toLowerCase() == 'dl') });
	if (t.tBodies[0].rows.length > 0) {
		if (container.id == 'openPolicies') {
			removeClassName(container, 'hidden');
		}
	} else if (container.id == 'openPolicies') {
		addClassName(container, 'hidden');
	}
}


/*
	updateAllTables (tArr)
	
	calls updateTable on all tables in tArr
*/
function updateAllTables (tArr) {
	for (t in tArr)
		updateTable(tArr[t]);
}


function showFind () {
	// get search results array
	var searchVal = document.getElementById('findCustomerInput').value;
	searchVal = (searchVal == "enter name or policy #") ? "" : searchVal;
	displaySearchResults(searchVal,5000);
	loadPage('searchResults');
	var progress = document.getElementById('searchProgress');
	removeClassName(progress, 'hidden');
}


function displaySearchResults(criteria,time){

	var searchCaller = {
	    update: function (o) {
	    	results=o.resultsArray;
			var t = document.getElementById('searchResultsTable');
			var tBody = t.tBodies[0];
			var newTBody = document.createElement('tbody');
		
			newTBody.innerHTML = "";
			var thisResult, thisTR, thisTD;
			if (results != null && results.length > 0) {
				for (var r in results) {
					thisResult = results[r];
					thisTR = document.createElement('tr');
		
					thisTD = document.createElement('td');
					thisTD.className = 'name';
					thisTD.innerHTML = '<a href="#" onclick="QuotePolicyController.openItem('
									+ thisResult.getAttributeValue('policy','pid') + ')">' 
									+ thisResult.getFieldValue('ifirstname') + ' '
									+ thisResult.getFieldValue('ilastname') + '</a>';
					thisTR.appendChild(thisTD);
					
					thisTD = document.createElement('td');
					thisTxt = document.createTextNode(thisResult.getAttributeValue('policy','pid'));
					thisTD.appendChild(thisTxt);
					thisTR.appendChild(thisTD);
					
					thisTD = document.createElement('td');
					thisTxt = document.createTextNode(thisResult.getFieldValue('status'));
					thisTD.appendChild(thisTxt);
					thisTR.appendChild(thisTD);
		
					newTBody.appendChild(thisTR);
				}
			} else {
				thisTR = document.createElement('tr');
				thisTD = document.createElement('td');
				thisTxt = document.createTextNode('No results');
				thisTD.appendChild(thisTxt);
				thisTR.appendChild(thisTD);
				newTBody.appendChild(thisTR);
			}
			tBody.parentNode.replaceChild(newTBody, tBody);
			updateAllTables(document.getElementsByClassName('quotes'));
			var progress = document.getElementById('searchProgress');
			addClassName(progress, 'hidden');
	    }
	}
	var sr = new SearchResult(criteria,time,searchCaller);
}


/*
	QuotePolicyItem
*/
function QuotePolicyItem (id) {
	this.id = id;
	this.win;
	this.viewname;
	this.needsToBeSaved;
	this.displayMode;
	this.secondVehicleAdded = false;
	
	var custarray=findCustomer(id);
	if(custarray==null || custarray.length<1){
		this.name = 'Unknown Name';
		this.status = 'Unknown Status';
	} else {
		this.customer = findCustomer(id)[0];
		if (!(this.customer.getFieldValue('ilastname') == ''))
			this.name = this.customer.getFieldValue('ifirstname') + ' ' + this.customer.getFieldValue('ilastname');
		else
			this.name = 'New Policy '+QuotePolicyController.newQuoteNum++;
		this.status = this.customer.getFieldValue('status');
		if(this.status=="Issued Policy"){
			this.displayMode="disabled";
		}else{
			this.displayMode="enabled";
		}
	}
}
var QPIP = QuotePolicyItem.prototype;
QPIP.open = function() {
//	this.win = window.open('quotepolicy.html', this.id, 'left=100,top=100,width=820,height=550,menubar=no,location=no,resizable=yes,scrollbars=yes,status=no');
	this.win = window.open('quotepolicy.html', this.id, 'width='+(window.screen.availWidth-10)+',height='+(window.screen.availHeight-35)+',left=0,top=0,directories=no,location=no,menubar=no,resizable=yes,scrollbars=no,status=no,titlebar=no,toolbar=no');
}
QPIP.registerWindow = function (win) {
//	var h1 = win.document.getElementById('fullname');
//	h1.innerText = this.name;
	this.win = win;
	win.document.customer = this.customer;
	win.document.alertWindow = new AlertWindow(win.document);
	win.document.infoWindow = new QPInfoWindow(win.document, 'infoWindow');
	win.document.confirmWindow = new QPConfirmWindow(win.document, 'confirmWindow');
	win.document.thisData = this;
	win.document.displayMode = this.displayMode;
	win.document.visibleSelect = this.visibleSelect;
	
	this.SmartPickController = new SmartPickController(win);
	win.document.SmartPickController = this.SmartPickController;

	win.document.notImplemented = function () {
		win.document.alertWindow.showMsg('Not implemented');
	}

	// set up required number updating
	this.ddArr = new Array();
	this.rfqTotalText = win.document.getElementById('rfqTotal');
	this.rfiTotalText = win.document.getElementById('rfiTotal');

	var ddEls = win.document.getElementsByTagName('dd');
	for (var e in ddEls) {
		if (ddEls[e].tagName) {
			var ddObj = new Object();
			ddObj.dd = ddEls[e];
			var prevDT = 0;
			while (ddEls[e].parentNode.childNodes[prevDT] != ddEls[e])
				prevDT++;
			while (ddEls[e].parentNode.childNodes[prevDT].tagName != 'DT')
				prevDT--;
			var dt = ddEls[e].parentNode.childNodes[prevDT];
			ddObj.arrow = findChildElements(dt, function (e) { return hasClassName(e, 'arrow') })[0];
			ddObj.rfq = findChildElements(dt, function (e) { return hasClassName(e, 'rfq') })[0];
			ddObj.rfi = findChildElements(dt, function (e) { return hasClassName(e, 'rfi') })[0];
			if (ddObj.rfq != undefined) {
				ddObj.rfqText = ddObj.rfq.innerText;
				ddObj.rfiText = ddObj.rfi.innerText;
//				ddObj.rfq = Number(ddObj.rfqText);
//				ddObj.rfiText = Number(ddObj.rfiText);
				this.ddArr.push(ddObj);
			}
		}
	}

	// set up state info
	this.quoteOutOfDate = true;
//	this.recalcButton = win.document.getElementById('premiumCalcButton');
	this.rateButtons = findChildElements(win.document, function (e) { return hasClassName(e, 'rate') || hasClassName(e, 'ratewithmvr') });
	this.issuePolicyButton1 = win.document.getElementById('issuePolicyButton1');
	this.issuePolicyButton2 = win.document.getElementById('issuePolicyButton2');
	this.calcText = win.document.getElementById('premiumTotalCalc');
	this.nocalcText = win.document.getElementById('premiumTotalNoCalc');
	this.statusText = win.document.getElementById('quotepolicystatus');
	this.smallFunctions = win.document.getElementById('smallFunctions');
	this.statusText = win.document.getElementById('fullName');
	this.performEndorsementButton = win.document.getElementById('performEndorsementButton');
	this.issueEndorsementButton = win.document.getElementById('issueEndorsementButton');
	this.endorsementHeader = win.document.getElementById('endorsementHeader');
	this.cancelEndorsementButton=win.document.getElementById('cancelEndorsementButton');
	this.estimatedPremiumEndorsement=win.document.getElementById('estimatedPremiumEndorsement');
	this.effectiveDateEndorsement=win.document.getElementById('effectiveDateEndorsement');
	this.endorsementSmallLink=win.document.getElementById('endorsementSmallLink');
	this.endorsementRecalcButton=win.document.getElementById('endorsementRecalcButton');
	this.premiumDollarsEndorsement=win.document.getElementById('premiumDollarsEndorsement');
	this.premiumCentsEndorsement=win.document.getElementById('premiumCentsEndorsement');
	this.saveQuote=win.document.getElementById('saveQuote');
	this.saveIndicator=win.document.getElementById('saveIndicator');
	this.calcIndicator=win.document.getElementById('calcIndicator');
	this.lastUpdated=win.document.getElementById('lastUpdated');
	this.premiumTotalCalcEndorsement=win.document.getElementById('premiumTotalCalcEndorsement');
	this.issueEndorsementButtonBilling=win.document.getElementById('issueEndorsementButtonBilling');
	this.billingSectionLink=win.document.getElementById('billinginfolink');
	this.billingInfoRequiredFieldsTally=win.document.getElementById('billingInfoRequiredFieldsTally');
	
	/* add the save onclick event */
	this.attachSaveEvent();

	this.updateState();
}

QPIP.addSecondVehicle = function () {
	if (!this.secondVehicleAdded) {
		var v2 = this.win.document.getElementById('vehicle2requiredFields');
		var v2q = Number(findChildElements(v2, function (e) { return hasClassName(e, 'rfq') } )[0].innerText);
		var v2i = Number(findChildElements(v2, function (e) { return hasClassName(e, 'rfi') } )[0].innerText);
		
		this.rfqTotalText.innerText = v2q + Number(this.rfqTotalText.innerText);
		this.rfiTotalText.innerText = v2i + Number(this.rfiTotalText.innerText);

		this.secondVehicleAdded = true;
	}
}

QPIP.updateState = function () {

	var rfqt = Number(this.rfqTotalText.innerText);
	var rfit = Number(this.rfiTotalText.innerText);

//alert('update state...\nrfit: '+rfit+'\nrfqt: '+rfqt+'\nrfqtotal: '+this.rfqTotalText);
	if(this.status=="Issued Policy"){
		if (hasClassName(this.performEndorsementButton, 'hidden')) {
			removeClassName(this.performEndorsementButton, 'hidden');
		}		
		if (!hasClassName(this.issueEndorsementButton, 'hidden')) {
			addClassName(this.issueEndorsementButton, 'hidden');
		}	
		if (!hasClassName(this.issueEndorsementButtonBilling, 'hidden')) {
			addClassName(this.issueEndorsementButtonBilling, 'hidden');
		}
		if (!hasClassName(this.cancelEndorsementButton, 'hidden')) {
			addClassName(this.cancelEndorsementButton, 'hidden');
		}	
		if (!hasClassName(this.effectiveDateEndorsement, 'hidden')) {
			addClassName(this.effectiveDateEndorsement, 'hidden');
		}
		if (!hasClassName(this.estimatedPremiumEndorsement, 'hidden')) {
			addClassName(this.estimatedPremiumEndorsement, 'hidden');
		}
		if (!hasClassName(this.endorsementHeader, 'hidden')) {
			addClassName(this.endorsementHeader, 'hidden');
		}
		if (!hasClassName(this.endorsementSmallLink, 'hidden')) {
			addClassName(this.endorsementSmallLink, 'hidden');
		}
		this.performEndorsementButtonWorks(true);
		makeBillingSectionVisible(this.billingSectionLink, this.billingInfoRequiredFieldsTally, this.rfiTotalText, this.win);

	}else if(this.status=="Endorsement" || this.status=="Endorsement Complete"){
		if (!hasClassName(this.performEndorsementButton, 'hidden')) {
			addClassName(this.performEndorsementButton, 'hidden');
		}
		if (hasClassName(this.issueEndorsementButton, 'hidden')) {
			removeClassName(this.issueEndorsementButton, 'hidden');
		}		
		if (hasClassName(this.issueEndorsementButtonBilling, 'hidden')) {
			removeClassName(this.issueEndorsementButtonBilling, 'hidden');
		}
		if (hasClassName(this.cancelEndorsementButton, 'hidden')) {
			removeClassName(this.cancelEndorsementButton, 'hidden');
		}	
		if (hasClassName(this.effectiveDateEndorsement, 'hidden')) {
			removeClassName(this.effectiveDateEndorsement, 'hidden');
		}
		if (hasClassName(this.estimatedPremiumEndorsement, 'hidden')) {
			removeClassName(this.estimatedPremiumEndorsement, 'hidden');
		}
		if (hasClassName(this.endorsementHeader, 'hidden')) {
			removeClassName(this.endorsementHeader, 'hidden');
		}
		if (hasClassName(this.endorsementSmallLink, 'hidden')) {
			removeClassName(this.endorsementSmallLink, 'hidden');
		}
		if(this.status=="Endorsement"){
			this.issueEndorsementButtonWorks(false);
		}else{
			this.issueEndorsementButtonWorks(true);
		}	
		makeBillingSectionVisible(this.billingSectionLink, this.billingInfoRequiredFieldsTally, this.rfiTotalText, this.win);
			
	}else{
		if (rfqt == 0)
		 {
			// required for quote = 0
			if (this.quoteOutOfDate)
				this.recalcButtonWorks(true);
			else
				this.recalcButtonWorks(false);
			this.setStatus('Ready to Quote');
			//if(!hasClassName(this.calcText,'hidden'))
			//{
				//makeBillingSectionVisible(this.billingSectionLink, this.billingInfoRequiredFieldsTally, this.rfiTotalText, this.win);
			//}
		} 
		else 
		{
			// required for quote > 0
			this.recalcButtonWorks(false);
			this.setStatus('Incomplete');
		}
		
		if (rfit == 0 ) {
			// required for issue/policy = 0
			this.smallFunctions.style.visibility = 'visible';
			if (this.quoteOutOfDate) {
				this.issuePolicyButtonWorks(false);
			} else {
				this.issuePolicyButtonWorks(true);
				this.setStatus('Ready to Issue');
			}			
		} else {
			// required for issue/policy > 0
			this.smallFunctions.style.visibility = 'hidden';
			this.issuePolicyButtonWorks(false);			
		}
	}
	
	this.updateName();
}

QPIP.setStatus = function (str) {
	var statusText = this.win.document.getElementById('quotepolicystatus');
	var activeStatusText = document.getElementById('activeQuotesStatus'+this.id);
	activeStatusText.innerText = str;
	statusText.innerText = str;
}

QPIP.updateName = function () {
	var nameStr = '';
	var lastName = this.win.document.getElementById('ilastname');
	if (lastName && (lastName.value.length > 0)) {
//		alert('yes: '+lastName.value);
		var firstName = this.win.document.getElementById('ifirstname');
		if (firstName && (firstName.value.length > 0)) {
			nameStr = firstName.value + ' ';
		}
		nameStr += lastName.value;
		this.name = nameStr;

		var openNameText = document.getElementById('openPolicies'+this.id);
		openNameText.innerText = nameStr;
		var activeNameText = document.getElementById('activeQuotes'+this.id);
		activeNameText.innerText = nameStr;
		this.statusText.innerText = nameStr;
		this.win.document.title = nameStr;
	}
}

QPIP.issuePolicyButtonWorks = function (isTrue) 
{
	if (isTrue) 
	{
		if (hasClassName(this.issuePolicyButton1, 'issuePolicyButtonOff')) 
		{
			removeClassName(this.issuePolicyButton1, 'issuePolicyButtonOff');	
			addClassName(this.issuePolicyButton1, 'issuePolicyButtonOn');
		}
		this.issuePolicyButton1.onclick = function () {
			issuePolicy(this.document,this.document.customer);
		}

		/* try to get it again in case the premium/billing section wasn't loaded yet */
		if(!this.issuePolicyButton2){
			this.issuePolicyButton2 = this.win.document.getElementById('issuePolicyButton2');
		}
		if(this.issuePolicyButton2){
			if (hasClassName(this.issuePolicyButton2, 'issuePolicyButtonOff')) 
			{
				removeClassName(this.issuePolicyButton2, 'issuePolicyButtonOff');			
				addClassName(this.issuePolicyButton2, 'issuePolicyButtonOn');
			}
			this.issuePolicyButton2.onclick = function () {
				issuePolicy(this.document,this.document.customer);
			}
		}
	}
	else 
	{
		if (hasClassName(this.issuePolicyButton1, 'issuePolicyButtonOn')) 
		{	
			removeClassName(this.issuePolicyButton1, 'issuePolicyButtonOn');
			addClassName(this.issuePolicyButton1, 'issuePolicyButtonOff');		
		}
		this.issuePolicyButton1.onclick = function () { return false };
		/* try to get it again in case the premium/billing section wasn't loaded yet */
		if(!this.issuePolicyButton2){
			this.issuePolicyButton2 = this.win.document.getElementById('issuePolicyButton2');
		}
		if(this.issuePolicyButton2){
			if (hasClassName(this.issuePolicyButton2, 'issuePolicyButtonOn')) 
			{			
				removeClassName(this.issuePolicyButton2, 'issuePolicyButtonOn');
				addClassName(this.issuePolicyButton2, 'issuePolicyButtonOff');	
			}			
			this.issuePolicyButton2.onclick = function () { return false };	
		}
	}
}

QPIP.showQuote = function () {
	this.quoteOutOfDate = false;
	addClassName(this.nocalcText, 'hidden');
	removeClassName(this.calcText, 'outOfDate');
	removeClassName(this.calcText, 'hidden');

	if(!hasClassName(this.calcIndicator,'hidden')){
	addClassName(this.calcIndicator,'hidden');
	}
	
	this.setStatus('Quote Complete');
	this.status='Quote Complete';
//	this.issuePolicyButtonWorks(true);
this.updateState();
	this.showHideCoverages('visible');
	this.showHidePremium('visible');
}
QPIP.showHidePremium = function (mode) {
	var prem1=this.win.document.getElementById("premiumamt1");
	if(!prem1){return;}
	
	var prem2=this.win.document.getElementById("premiumamt2");						
	var totvehprem=this.win.document.getElementById("totalVehiclePremium");
	var tottax=this.win.document.getElementById("totaltax");
	var stsurcharge=this.win.document.getElementById("statesurcharge");
	var hwyfundfee=this.win.document.getElementById("highwayfundfee");
	var sr22fee=this.win.document.getElementById("sr22fee");
	var polfee=this.win.document.getElementById("policyfee");
	var totfees=this.win.document.getElementById("totalfeesandsurcharges");
	var totpolprem=this.win.document.getElementById("totalpolicypremium");
	var writprem=this.win.document.getElementById("writtenPremium");
	var paymentsum=this.win.document.getElementById("paymentsummary");
	
	/* display premium based on displaymode */	
	prem1.style.visibility=mode;
	prem2.style.visibility=mode;
	totvehprem.style.visibility=mode;
	tottax.style.visibility=mode;
	stsurcharge.style.visibility=mode;
	hwyfundfee.style.visibility=mode;
	sr22fee.style.visibility=mode;
	polfee.style.visibility=mode;
	totfees.style.visibility=mode;
	totpolprem.style.visibility=mode;
	/* due to different billing fields on quote and policy */
	if(writprem){writprem.style.visibility=mode;}
	if(paymentsum){paymentsum.style.visibility=mode;}
}
QPIP.showHideCoverages = function (mode) {
	var prem1=this.win.document.getElementById("premiumAmount11");
	if(!prem1){return;}
	
	var count=this.customer.node.selectNodes('.//vehicle').length;
	var index=1;	
	
	for(var i=0;i<count;i++){						
		var prem1=this.win.document.getElementById("premiumAmount1" + index);
		var prem2=this.win.document.getElementById("premiumAmount2" + index);						
		var covprem=this.win.document.getElementById("coveragepremium" + index);
		
		/* display premium if section has been expanded */
		prem1.style.visibility=mode;
		prem2.style.visibility=mode;
		covprem.style.visibility=mode;
		
		index++;
	}
}

QPIP.recalcButtonClick = function () {
	this.updateState();
//	this.recalcButton.className = 'recalcOff';
//	this.recalcButton.id = 'premiumRecalcButton';
	this.recalcButtonWorks(false);
	var waitTxt = this.win.document.getElementById('premiumTotalNoCalc');
	waitTxt.innerText = 'Calculating';
	
	if(hasClassName(this.calcIndicator,'hidden')){
		removeClassName(this.calcIndicator,'hidden');
	}
	if(!hasClassName(this.calcIndicator,'rightHeader')){
		addClassName(this.calcIndicator,'rightHeader');	
	}
	this.calcIndicator.style.visibility='visible';
	
	removeClassName(this.nocalcText, 'hidden');
	addClassName(this.calcText, 'hidden');
	this.win.setTimeout('this.document.thisData.showQuote()', 5000);
}
QPIP.recalcButtonWorks = function (isTrue) {
	if (isTrue) {
		for (var b in this.rateButtons) {
			var button = this.rateButtons[b];
			if (hasClassName(button, 'rate'))
				addClassName(button, 'rateon');
			else if (hasClassName(button, 'ratewithmvr'))
				addClassName(button, 'ratewithmvron');
			button.onclick = function () {
				this.document.thisData.recalcButtonClick();
			}
		}
	} else {
		for (var b in this.rateButtons) {
			var button = this.rateButtons[b];
			removeClassName(button, 'rateon');
			removeClassName(button, 'ratewithmvron');
			button.onclick = function () { return false; };
		}
	}
}

QPIP.performEndorsementButtonWorks = function (isTrue){
	if (isTrue) {
		if (hasClassName(this.performEndorsementButton, 'on')
			|| hasClassName(this.performEndorsementButton, 'off')) {
			this.performEndorsementButton.className = 'on';
		}
		this.performEndorsementButton.onclick = function () {
			performEndorsement(this.document.customer,this.document);}
	} else {
		if (hasClassName(this.performEndorsementButton, 'on')
			|| hasClassName(this.performEndorsementButton, 'off')) {
			this.performEndorsementButton.className = 'off';
		}
		this.performEndorsementButton.onclick = function () { return false; };
	}
}
QPIP.issueEndorsementButtonWorks = function (isTrue){
	if (isTrue) {		
		if (this.issueEndorsementButton.className=='off') {
			this.issueEndorsementButton.className='issueEndorsementButton';
		}
		this.issueEndorsementButton.onclick = function () {
			issueEndorsement(this.document.customer,this.document);}
		if (this.issueEndorsementButtonBilling.className=='off') {
			this.issueEndorsementButtonBilling.className='issueEndorsementButton';
		}
		this.issueEndorsementButtonBilling.onclick = function () {
			issueEndorsement(this.document.customer,this.document);}
		this.showHideCoverages('visible');
		this.showHidePremium('visible');
	} else {
		if (!hasClassName(this.issueEndorsementButton.className, 'off')) {
			this.issueEndorsementButton.className = 'off';
		}
		this.issueEndorsementButton.onclick = function () { return false; };
		if (!hasClassName(this.issueEndorsementButtonBilling.className, 'off')) {
			this.issueEndorsementButtonBilling.className = 'off';
		}
		this.issueEndorsementButtonBilling.onclick = function () { return false; };
		this.showHideCoverages('hidden');
		this.showHidePremium('hidden');	
		if(!hasClassName(this.premiumDollarsEndorsement,'hidden')){
			addClassName(this.premiumDollarsEndorsement,'hidden');
		}
		if(!hasClassName(this.premiumCentsEndorsement,'hidden')){
			addClassName(this.premiumCentsEndorsement,'hidden');
		}
		if(!hasClassName(this.premiumTotalCalcEndorsement,'hidden')){
			addClassName(this.premiumTotalCalcEndorsement,'hidden');
		}
	}
}
QPIP.endorsementRecalcButtonWorks = function (isTrue){
	if (isTrue) {
		this.endorsementRecalcButton.className = 'recalcOn';
		this.endorsementRecalcButton.onclick = function () {
			this.document.thisData.endorsementRecalcButtonClick();
		}
		this.issueEndorsementButtonWorks(false);
	} else {
		this.endorsementRecalcButton.className = 'recalcOff';
		this.endorsementRecalcButton.onclick = function () { return false; };
		this.issueEndorsementButtonWorks(true);
	}
}
QPIP.endorsementRecalcButtonClick = function(){
	if(hasClassName(this.premiumDollarsEndorsement,'hidden')){
		removeClassName(this.premiumDollarsEndorsement,'hidden');
	}
	if(hasClassName(this.premiumCentsEndorsement,'hidden')){
		removeClassName(this.premiumCentsEndorsement,'hidden');
	}
	if(hasClassName(this.premiumTotalCalcEndorsement,'hidden')){
		removeClassName(this.premiumTotalCalcEndorsement,'hidden');
	}
	this.endorsementRecalcButtonWorks(false);
	this.status="Endorsement Complete";
}
QPIP.attachSaveEvent=function(){
	this.saveQuote.onclick = function () {
		this.document.thisData.saveQuoteButtonClick();
	}
}
QPIP.saveQuoteButtonClick=function(){
	/* display wait indicator */
	if(hasClassName(this.saveIndicator,'hidden')){
		removeClassName(this.saveIndicator,'hidden');
	}
	if(!hasClassName(this.saveIndicator,'rightHeader')){
		addClassName(this.saveIndicator,'rightHeader');	
	}
	if(!hasClassName(this.lastUpdated,'hidden')){
		addClassName(this.lastUpdated,'hidden');
	}
	save(this.win.document,this.win.document.customer);
	this.saveIndicator.style.visibility='visible';
	
	/* set timestamp */
	this.win.setTimeout('this.document.thisData.displayTimeStamp()',5000);	
}
QPIP.displayTimeStamp=function(){
	if(!hasClassName(this.saveIndicator,'hidden')){
		addClassName(this.saveIndicator,'hidden');
	}
	if(hasClassName(this.lastUpdated,'hidden')){
		removeClassName(this.lastUpdated,'hidden');
	}
	if(!hasClassName(this.lastUpdated,'rightHeader')){
		addClassName(this.lastUpdated,'rightHeader');	
	}
	this.lastUpdated.style.visibility='visible';	
	this.lastUpdated.innerText="Saved: " + getCurrentDateTime();

}

QPIP.focus = function () {
	this.win.focus();
}
QPIP.close = function () {
	this.win.close();
}
QPIP.updateFieldArr = function (fArr) {
	var returnArr = fArr;
//	alert(returnArr);
	for (var f=0; f<returnArr.length; f++) {
		// check against the first input field found...
		var theInputArr =  findChildElements(returnArr[f], function (e) { if (e.tagName) { return e.tagName.toLowerCase() == 'input';  } else { return false } });
		var theSelectArr = findChildElements(returnArr[f], function (e) { if (e.tagName) { return e.tagName.toLowerCase() == 'select'; } else { return false } });
		var theInput;
		var valueExists = false;
		if (theInputArr.length > 0) {
			theInput = theInputArr[0];
			valueExists = (theInput.value.length > 0);
		} else {
			theInput = theSelectArr[0];
			valueExists = (theInput.selectedIndex > 0);
		}
		if (valueExists) {
			if (QuotePolicyController.isValid(returnArr[f])) {
				addClassName(returnArr[f], 'valid');
//				alert(f+' 1: '+returnArr[f].value);
				returnArr.splice(f--, 1);
//				alert(f+' 2: '+returnArr[f].value);
			} else {
				addClassName(returnArr[f], 'error');
			}
		}
	}
//	alert(returnArr);
	return returnArr;
}
QPIP.updateStatus = function () {
	var thisField = this.win.event.srcElement;
	this.updateField(thisField);
}

QPIP.updateFields = function (thisDT, thisDD) {
	var fields = findChildElements(thisDD, function (e) { return ((e.tagName == 'INPUT') || (e.tagName == 'SELECT')) });
	for (var f in fields) {
		if (hasClassName(fields[f].parentNode, 'requiredForQuote')
			|| hasClassName(fields[f].parentNode, 'requiredForPolicy')) {
			this.updateField(fields[f]);
		}
		if (hasClassName(fields[f], 'disabled')) {
			var win = this.win;
			addEvent(fields[f], 'focus', function () {win.event.srcElement.blur();});
		}
	}
	this.rateButtons = this.rateButtons.concat(findChildElements(thisDD, function (e) { return hasClassName(e, 'rate') || hasClassName(e, 'ratewithmvr') }));
	this.updateState();
}

QPIP.updateCount = function (fieldContainer, amount) {
	var node = findFirstParent(fieldContainer, function (e) { return e.tagName.toLowerCase() == 'dd'; });
	var siblings = node.parentNode.childNodes;
	for (var i = siblings.length; siblings[i] != node; i--);
	while (siblings[i].tagName != "DT") i--;
	var dt = node.parentNode.childNodes[i];
	var rfqText = findChildElements(dt, function (e) { return hasClassName(e, 'rfq'); })[0];
	var rfiText = findChildElements(dt, function (e) { return hasClassName(e, 'rfi'); })[0];
	if (hasClassName(fieldContainer, 'requiredForPolicy')
		|| hasClassName(fieldContainer, 'requiredForQuote')) {
		var rfi = Number(rfiText.innerText);
		rfi += amount;
		if (rfi < 0) rfi=0;
		rfiText.innerText = rfi;
		var rfit = Number(this.rfiTotalText.innerText);
		rfit += amount;
		if (rfit < 0) rfit=0;
		this.rfiTotalText.innerText = rfit;
		if (hasClassName(fieldContainer, 'requiredForQuote')) {
			var rfq = Number(rfqText.innerText);
			rfq += amount;
			if (rfq < 0) rfq=0;
			rfqText.innerText = rfq;
			var rfqt = Number(this.rfqTotalText.innerText);
			rfqt += amount;
			if (rfqt < 0) rfqt=0;
			this.rfqTotalText.innerText = rfqt;
		}
	}
}

QPIP.updateField = function (thisField) {
	var fieldContainer = thisField.parentNode;
//	alert('field: '+thisField.className+'\nvalue: '+thisField.value+'\nlength: '+thisField.value.length+'\nchecked: '+thisField.checked);
//	alert('before: '+fieldContainer.className);
	if (((thisField.tagName == 'INPUT') && ((thisField.value.length == 0) || 
		 (!thisField.checked && ((thisField.type == 'checkbox') || (thisField.type == 'radio'))))) ||
		((thisField.tagName == 'SELECT') && (thisField.selectedIndex == 0))) {
		// field is empty
		if (hasClassName(fieldContainer, 'valid')) {
			if (hasClassName(fieldContainer, 'requiredForPolicy') 
				|| hasClassName(fieldContainer, 'requiredForQuote')) {
				this.updateCount(fieldContainer, 1);
			}
			removeClassName(fieldContainer, 'valid');
		}
		removeClassName(fieldContainer, 'error');
	} else if (!QuotePolicyController.isValid(thisField)) {
		// field has an error
		if (hasClassName(fieldContainer, 'valid')) {
			if (hasClassName(fieldContainer, 'requiredForPolicy') 
				|| hasClassName(fieldContainer, 'requiredForQuote')) {
				this.updateCount(fieldContainer, 1);
			}
			removeClassName(fieldContainer, 'valid');
		}
		addClassName(fieldContainer, 'error');
	} else if (!hasClassName(fieldContainer, 'valid')) {
		// field has valid data
		removeClassName(fieldContainer, 'error');
		addClassName(fieldContainer, 'valid');

//alert('hello: '+fieldContainer.className);

		// update totals
		this.updateCount(fieldContainer, -1);
	}
//	alert('after: '+fieldContainer.className);
	// update the status
	this.quoteOutOfDate = true;
	this.updateState();
}
QPIP.smartPickInputExecute = function (f) {
	this.SmartPickController.inputExecute(f);
}
QPIP.smartPickLIExecute = function (f) {
	this.SmartPickController.liExecute(f);
}
QPIP.nextDD = function () {
	var e = this.win.event.srcElement;

	var thisDD = findFirstParent(e, function (e) { return (e.tagName.toLowerCase() == 'dd') });
	
	// hack for quote premium section so hidden billing section does not display
	if(thisDD.id==PREMIUM){return;}
	
	var ddSiblings = thisDD.parentNode.childNodes;
	var i = 0;

	while (ddSiblings[i] != thisDD) i++;
	do {
		i++;
	} while ((i < ddSiblings.length) && (ddSiblings[i].tagName != 'DD'));

	var newDD = null;
	if (i < ddSiblings.length) {
		newDD = ddSiblings[i];
		// hack for second vehicle
		if ((newDD.id == 'vehicle2') && (this.customer.node.selectNodes('.//vehicle').length == 1))
			newDD = null;
	}

	if (newDD == null) {
		// go to the next dl
		var thisDL = thisDD.parentNode;
		var dlList = this.win.document.getElementsByTagName('dl');
		var i=0;
		while (dlList[i++] != thisDL) ;
		if (i < dlList.length) {
			var newDLkids = dlList[i].childNodes;
			var j=0;
			while (newDLkids[j].tagName != 'DD') j++;
			newDD = newDLkids[j];
		}
	}

	if (newDD != null) {
		var newDDsiblings = newDD.parentNode.childNodes;
		var i=newDDsiblings.length-1;
		while (newDDsiblings[i] != newDD) i--;
		while (newDDsiblings[i].tagName != 'DT') i--;
		var newDT = newDDsiblings[i];
		closeAllSections(newDD, this.win.document);
		if (!hasClassName(newDD, 'visible')) {
			toggleDD(this.id,newDD,this.win.document,this.customer,newDD.id,newDT);
			var arrow = findChildElements(newDT, function (e) { return hasClassName(e, 'arrow') })[0];
			if (arrow.innerText == 4)
				arrow.innerText = 6;
			else
				arrow.innerText = 4;
		}
	}
}
QPIP.focusField = function () {
	addClassName(this.win.event.srcElement, 'focus');
}
QPIP.unfocusField = function () {
	removeClassName(this.win.event.srcElement, 'focus');
}

QPIP = null;


/*
	QuotePolicyController
*/
function QuotePolicyController () {
	this.newQuoteNum = 1;
	this.openItems = new Array();
	this.openPoliciesTable = findChildElements(document.getElementById('openPolicies'), function (t) { return hasClassName(t, 'quotes') })[0];
	this.activeQuotesTable = findChildElements(document.getElementById('activeQuotes'), function (t) { return hasClassName(t, 'quotes') })[0];
//	this.openPoliciesTable.style.backgroundColor = "#fff";
}
var QPCP = QuotePolicyController.prototype;
QPCP.addItem = function (item) {
	this.openItems[this.openItems.length] = item;
	return item;
}
QPCP.findItem = function (id) {
	for (var i in this.openItems)
		if (this.openItems[i].id == id)
			return this.openItems[i];
	return null;
}
QPCP.updateStatus = function (id) {
//	var item = this.findItem(id);
//	item.updateStatus();
}
QPCP.deleteItem = function (id) {
	for (var i in this.openItems) {
//		alert(i+' '+this.openItems[i].id+' =? '+id);
		if (this.openItems[i].id == id) {
//			alert(true);
			this.openItems.splice(i, 1);
			return true;
		}
	}
	return false;
}
QPCP.openItem = function (id) {
	var item = this.findItem(id);
	if (item != null) {
		item.focus();
	} else {
		item = this.addItem(new QuotePolicyItem(id));
		item.open();
		this.refreshTable();
	}
}
QPCP.updateFields = function (id, thisDT, thisDD) {
	var item = this.findItem(id);
	item.updateFields(thisDT, thisDD);
}
QPCP.closeItem = function (id) {
	var item = this.findItem(id);
	item.close();
}
QPCP.removeItem = function (id) {
	this.deleteItem(id);
	this.refreshTable();
}
QPCP.registerWindow = function (win, id) {
	this.addToActiveQuotes(id);
	var item = this.findItem(id);
	item.registerWindow(win.window);
}
QPCP.addToActiveQuotes = function (id) {
	var tBody = this.activeQuotesTable.tBodies[0];
	var thisRow, thisTD, thisTxt, thisSpan;
	
	var date = new Date();
	var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
	var thisMonth = months[date.getMonth()];
	var thisDate = date.getDate();
	var thisYear = date.getYear();

	thisRow = document.createElement('tr');

	thisTD = document.createElement('td');
	thisTD.className = 'name';
	thisTD.innerHTML = '<a href="#" id="activeQuotes'
						+ id + '" onclick="QuotePolicyController.openItem('
						+ id + ');return(false);">New Policy</a>';
	thisRow.appendChild(thisTD);
	
	thisTD = document.createElement('td');
	thisTD.id = 'activeQuotesStatus'+id;
	thisTxt = document.createTextNode('Incomplete');
	thisTD.appendChild(thisTxt);
	thisRow.appendChild(thisTD);

	thisTD = document.createElement('td');
	thisTxt = document.createTextNode(thisMonth + ' ' + thisDate + ', ' + thisYear); // Oct 31, 2005
	thisTD.appendChild(thisTxt);
	thisRow.appendChild(thisTD);

	thisTD = document.createElement('td');
	thisTD.className = 'dismiss';
	thisSpan = document.createElement('span');
	thisSpan.innerHTML = '<a href="#" onclick="DismissFloater.dismiss(this);return(false);">archive</a>';
	thisTD.appendChild(thisSpan);
	thisRow.appendChild(thisTD);
	
	tBody.appendChild(thisRow);
}
QPCP.refreshTable = function () {
	var tBody = this.openPoliciesTable.tBodies[0];
	var t = this.openPoliciesTable;
	var newTBody = document.createElement('tbody');
	
	var thisRow, thisTD, thisItem, thisTxt;
	for (var i in this.openItems) {
		thisItem = this.openItems[i];
//		thisName = (thisItem.name == undefined) ? 'New Quote '+this.newQuoteNum++ : thisItem.name;
		thisName = thisItem.name;
		thisRow = document.createElement('tr');

		///<td class="name"><a href="#" onclick="QuotePolicyController.openItem(1);">Jane Smith</a></td>
		thisTD = document.createElement('td');
		thisTD.className = 'name';
		thisTD.innerHTML = '<a href="#" id="openPolicies' + thisItem.id
							+ '" onclick="QuotePolicyController.openItem('+thisItem.id+');return(false);">'
							+ thisName + '</a>';
		thisRow.appendChild(thisTD);

		//<td>Complete/Unissued</td>
		thisTD = document.createElement('td');
		thisTxt = document.createTextNode(thisItem.status);
		thisTD.appendChild(thisTxt);
		thisRow.appendChild(thisTD);
		
		//<td class="dismiss"><a href="#" onclick="closeItem(this)">close</a></td>
		thisTD = document.createElement('td');
		thisTD.className = 'dismiss';
		thisTD.innerHTML = '<span><a href="#" onclick="QuotePolicyController.closeItem('+thisItem.id+')">'
							+ 'close</a></span>';
		thisRow.appendChild(thisTD);

		newTBody.appendChild(thisRow);
	}
	tBody.parentNode.replaceChild(newTBody, tBody);
	updateAllTables(document.getElementsByClassName('quotes'));
}
QPCP.isValid = function (e) {
	if (hasClassName(e, 'validateVIN'))
		return Validate.VIN(e);
	return true;
}
QPCP.updateSectionLocation = function(pid,viewname,doc,field){
	/* perform view-specific functionality */
	var item = this.findItem(pid);
	if(item.status=="Endorsement" || item.status=="Endorsement Complete"){
		if(item.status=="Endorsement Complete"){
			item.status="Endorsement";
		}
		/* notify state handling if a field changed in endorsement */
		item.endorsementRecalcButtonWorks(true);
	}
	if(!item.viewname){
		item.viewname=viewname;
		item.needsToBeSaved=true;
	}else if(item.viewname!=viewname && item.needsToBeSaved){
		checkUpdateSectionHead(item.viewname,doc,item.customer);
		item.viewname=viewname;
		save(doc,item.customer,item.needsToBeSaved);
		item.needsToBeSaved=false;		
	}else{
		if(!item.needsToBeSaved){
			item.needsToBeSaved=true;
		}
	}
//	alert('pid: '+pid+'\nviewname: '+viewname+'\ndoc: '+doc+'\nfield: '+field+'\nfield tag: '+field.tagName);
	item.updateStatus();
}
QPCP.smartPickInputExecute = function (id, f) {
	var item = this.findItem(id);
	item.smartPickInputExecute(f);
}
QPCP.smartPickLIExecute = function (id, f) {
	var item = this.findItem(id);
	item.smartPickLIExecute(f);
}
QPCP.getWindow = function (id) {
	var item = this.findItem(id);
	return item.win;
}
QPCP.focusField = function (pid) {
	var item = this.findItem(pid);
	item.focusField();
}
QPCP.unfocusField = function (pid) {
	var item = this.findItem(pid);
	item.unfocusField();
}
QPCP = null;

Validate = {
	showMessage: function (msg) {
		alert(msg);
	},
	VIN: function (thisfield) {
		var vin = thisfield.value;
		var vinLength = 17;
		if ( vin.length != vinLength )
		{
			thisfield.document.alertWindow.showMsg("VIN number must be 17 characters in length. Please enter a valid VIN number.");
			return false
		}
	
		return true;
	}
}

function getElementsByStyleClass (document,className) {
  var all = document.getElementsByTagName('*');
  var elements = new Array();
  for (var e = 0; e < all.length; e++)
    if (all[e].className == className)
      elements[elements.length] = all[e];
  return elements;
}

/*
	startNewQuote()
	creates a new null customer and opens in a new window
*/
function startNewQuote(){
	var newQuote=createQuote();
	if(newQuote!=null){
		QuotePolicyController.openItem(newQuote.getAttributeValue('policy','pid'));
	}
}

/*
	toggleFields (link)
	
	Toggle the display of the dd after link
*/
function toggleFields (id,dt,document,customer,viewname,maxnodes) {	
	var i = 0;
	var thisDT = dt;
	var siblings = thisDT.parentNode.childNodes;
	while (siblings[i] != thisDT) { i++; }
	while (siblings[i].tagName.toLowerCase() != 'dd') { i++; }
	
	toggleDD(id,siblings[i],document,customer,viewname,thisDT);
	/* close all sections except this */
	//closeAllSections (siblings[i],document);
	var arrow = findChildElements(thisDT, function (e) { return hasClassName(e, 'arrow') })[0];
	if (arrow.innerText == 4)
		arrow.innerText = 6;
	else
		arrow.innerText = 4;
}

function toggleDD (id,thisDD,document,customer,viewname,maxnodes,thisDT) {	
	if (hasClassName(thisDD, 'visible')) {
		removeClassName(thisDD, 'visible');
	} else {
		var pid=customer.getAttributeValue("policy","pid");
		var quotepolicyitem=QuotePolicyController.findItem(pid);
		var displayMode=quotepolicyitem.displayMode;					
				
		/* disable billing section in Endorsement mode */
		if(viewname=="billinginfo"){
			if(quotepolicyitem.status=="Endorsement" )
			{
				displayMode="disabled";			
			}
			else
			{		
				displayMode="enabled";			
			}
		}		
								
		addClassName(thisDD, 'visible');
		var loadedNewView=loadView(document,viewname,customer,maxnodes,displayMode);
		
		if(loadedNewView){
			QuotePolicyController.updateFields(id, thisDT, thisDD);
		}

		/*			find first and last tab items
			focus on first tab item
			add event to last tab item
		*/
		
		var tabList = findChildElements(thisDD, function (e) { return ((e.tagName != undefined) && (e.getAttribute('tabIndex') != null) && ((e.tagName.toLowerCase() == 'input') || (e.tagName.toLowerCase() == 'select'))) } );

		var firstTabItem, lastTabItem, thisNode, thisTabIndex;
		var firstTabIndex = Number.MAX_VALUE;
		var lastTabIndex = 0;

		for (var i in tabList) {
			thisNode = tabList[i];
			thisTabIndex = thisNode.getAttribute('tabIndex');
			if (thisTabIndex > 0) {
				if (thisTabIndex <= firstTabIndex) {
					firstTabIndex = thisTabIndex;
					firstTabItem = thisNode;
				}
				if (thisTabIndex >= lastTabIndex) {
					lastTabIndex = thisTabIndex;
					lastTabItem = thisNode;
				}
			}
		}

//alert(firstTabItem.tagName+', '+firstTabItem.getAttribute('type')+', '+firstTabIndex+', '+firstTabItem.id+', '+lastTabItem.tagName);

		if (tabList.length > 0) {
			firstTabItem.focus();
			if (loadedNewView) {
				win = QuotePolicyController.getWindow(id);
				win.tabOut = function () { win.document.thisData.nextDD(); };
				addEvent(lastTabItem, 'blur', win.tabOut);
			}
		}
	}
}



function loadPage (pageName) {
	// hide all pages except pageName
	var pages = document.getElementsByClassName('page');
	for (var p in pages) {
		if (pages[p].id == pageName) {
			removeClassName(pages[p], 'hidden');
		} else {
			addClassName(pages[p], 'hidden');
		}
	}
	// set current nav to on, all others off
	var nav = document.getElementById(pageName+'Nav');
	var navItems = document.getElementById('topnav').childNodes;
	for (var i in navItems) {
		if (navItems[i].id != undefined) {
			if (navItems[i] == nav) {
				addClassName(navItems[i], 'on');
			} else {
				removeClassName(navItems[i], 'on');
			}
		}
	}
}

function notImplemented() {
	alertWindow.showMsg('Not implemented');
}

function addNode(id,document,customer,viewname,maxnodes){
  	var zip;
  	
	namenode=document.getElementById("vehiclename2");
	if(namenode.hasChildNodes()){
		return;
	}
	var pid=customer.getAttributeValue("policy","pid");
	var quotepolicyitem=QuotePolicyController.findItem(pid);
	if(quotepolicyitem.displayMode=="disabled"){return;}
	
	customer.addNode("vehicle");
	thisTxt = document.createTextNode("Vehicle 2");
	namenode.appendChild(thisTxt, namenode.childNodes[0]);	

	/* set the garage location */
	var zipfield=document.getElementById("zip");		
	if(!zipfield || zipfield.length<1){
		zip=customer.getFieldValue("zip");
	}else{
		zip=zipfield.getAttribute("value");
	}
	/* set vehicle two zip code */
	var vehicle2=customer.node.selectNodes('.//vehicle[@vehicleid="2"]/garagezipcode');
	vehicle2.item(0).text=zip;

	var pnode=namenode.parentNode;
	while(pnode.nodeName.toLowerCase()!="dt"){pnode=pnode.parentNode}
	if (hasClassName(pnode, 'hidden')) {
		removeClassName(pnode, 'hidden');
	}
	/* open vehicle 2 */
	namenode=document.getElementById("vehicle2link");
	toggleFields (id,namenode,document,customer,viewname,maxnodes);
}

function closeAllSections (link,document) {
	var ddnodes=document.getElementsByTagName("DD");
	for(a=0;a<ddnodes.length;a++){
		var thisDD=ddnodes[a];
		/* don't hide the link clicked on */
		if(link==thisDD){continue;}
		if (hasClassName(thisDD, 'visible')){
			removeClassName(thisDD, 'visible');
		}
		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.parentNode.getAttribute("id")!=link.getAttribute("id")+'link'){
				if (thisArrow.innerText == 6)
					thisArrow.innerText = 4;
			}
		}
	}
}

/*
	SmartPick class
*/
function SmartPick (inputField, data, win) {
	this.inputField = inputField;
	this.id = inputField.id;
	this.data = data;
	this.fieldArray = new Array();
	this.blurEvent;
	this.selectedLI = null;
	this.nonEventKeyCodes = [9, 16, 17, 18, 37, 39, 255];
	this.win = win;

	this.ul = this.buildUL();

	var winID = this.win.name;
	addEvent(this.inputField, 'click', function () { QuotePolicyController.smartPickInputExecute(winID, 'inputClick'); });
	addEvent(this.inputField, 'blur', function () { QuotePolicyController.smartPickInputExecute(winID, 'inputBlurSetup'); });
	addEvent(this.inputField, 'keyup', function () { QuotePolicyController.smartPickInputExecute(winID, 'inputKeyUp'); });
}
var SPP = SmartPick.prototype;
SPP.buildUL = function () {
	var thisUL = document.createElement('ul');
	thisUL.className = 'smartPick';
	this.hide(thisUL);
	var thisLI, thisText;
	for (var d in this.data) {
		thisLI = document.createElement('li');
		thisText = document.createTextNode(this.data[d]);
		thisLI.appendChild(thisText);
		thisUL.appendChild(thisLI);
	}

	thisUL.style.width = this.inputField.offsetWidth + 'px';
	var fieldOffset = getOffset(this.inputField);
	thisUL.style.left = (fieldOffset[0] - 14) + 'px'; // i don't know why it's 14px off
	thisUL.style.top = (fieldOffset[1] + this.inputField.offsetHeight) + 'px';

	var parent = this.inputField.parentNode;
	parent.innerHTML += thisUL.outerHTML;
	
	this.inputField = findChildElements(parent, function (e) { return (e.tagName && (e.tagName.toLowerCase() == 'input')) } )[0];
	thisUL = findChildElements(parent, function (e) { return (e.tagName && (e.tagName.toLowerCase() == 'ul')) } )[0];
	
	var lis = findChildElements(parent, function (e) { return (e.tagName && (e.tagName.toLowerCase() == 'li')) } );
	var thisLI;
	var winID = this.win.name;
	for (var key in lis) {
		thisLI = lis[key];
		addEvent(thisLI, 'click', function () { QuotePolicyController.smartPickLIExecute(winID, 'liClick'); } );
		addEvent(thisLI, 'mouseover', function () { QuotePolicyController.smartPickLIExecute(winID, 'liSelect'); } );
		this.fieldArray[thisLI.innerText] = thisLI;
	}

	return thisUL;
}
SPP.updateList = function () {
	var v = this.inputField.value;
	if ((this.selectedLI != null) && (this.selectedLI.innerText.toLowerCase().indexOf(v.toLowerCase()) != 0))
		this.liDeselect();
	for (var k in this.fieldArray) {
		if (k.toLowerCase().indexOf(v.toLowerCase()) == 0) {
			this.show(this.fieldArray[k]);
			if (this.selectedLI == null)
				this.liSelect(this.fieldArray[k]);
		}
	}
}
SPP.inputClick = function () {
	this.show(this.ul);
	this.updateList();
}
SPP.inputBlurExecute = function () {
	if ((this.selectedLI != null) && this.isVisible(this.ul))
		this.inputField.value = this.selectedLI.innerText;
	this.hide(this.ul);
	this.liDeselect();
	this.win.document.thisData.updateField(this.inputField);
}
SPP.inputBlurSetup = function () {
	// add a .1s delay before executing blur code
	// prevents blur code from being executed when user clicks on dropdown
	SmartPickController.blurEventItem = this;
	SmartPickController.blurEventFunc = function (sp) { sp.inputBlurExecute() };
 	this.blurEvent = setTimeout("SmartPickController.blurEventFunc(SmartPickController.blurEventItem)", 100);
}
SPP.inputKeyUp = function (event) 
{
	var newSelect = null;
	if (!inArray(this.nonEventKeyCodes, event.keyCode))
		this.show(this.ul);
	if (event.keyCode == 38) // arrow up
	{ 
		if (this.selectedLI == null) {
			// select last item
			for (var k in this.fieldArray)
				if (this.isVisible(this.fieldArray[k]))
					newSelect = this.fieldArray[k];
		} else {
			// select previous item
			for (var k in this.fieldArray) {
				if (this.fieldArray[k] == this.selectedLI)
					break;
				else if (this.isVisible(this.fieldArray[k]))
					newSelect = this.fieldArray[k];
			}
		}
		if (newSelect != null)
			this.liSelect(newSelect);
	}	
	else if (event.keyCode == 40) // arrow down
	 { 
		if (this.selectedLI == null) {
			// select first item
			for (var k in this.fieldArray) {
				if (this.isVisible(this.fieldArray[k])) {
					newSelect = this.fieldArray[k];
					break;
				}
			}
		} else {
			// select next item
			var foundSelected = false;
			for (var k in this.fieldArray) {
				if (foundSelected && this.isVisible(this.fieldArray[k])) {
					newSelect = this.fieldArray[k];
					break;
				} else if (this.fieldArray[k] == this.selectedLI) {
					foundSelected = true;
				}
			}
		}
		if (newSelect != null)
			this.liSelect(this.fieldArray[k]);
	}
	else if (event.keyCode == 13) // enter
	{ 
		if ((this.selectedLI != null) && this.isVisible(this.ul))
			this.inputField.value = this.selectedLI.innerText;
		this.hide(this.ul);
		this.liDeselect();
		this.win.document.thisData.updateField(this.inputField);			
	}	
	if (!inArray(this.nonEventKeyCodes, event.keyCode))
		this.updateList();
}
SPP.liClick = function (li) {
	clearTimeout(this.blurEvent);
	this.inputField.focus();
	this.inputField.value = li.innerText;
	this.updateList();
	this.hide(this.ul);
}
SPP.liDeselect = function () {
	if (this.selectedLI != null) {
		removeClassName(this.selectedLI, 'selected');
		this.selectedLI = null;
	}
}
SPP.liSelect = function (li) {
	this.liDeselect();
	addClassName(li, 'selected');
	this.selectedLI = li;
}
SPP.hide = function (el) {
	el.style.display = 'none';
	el.style.visibility = 'hidden';
}
SPP.show = function (el) {
	el.style.display = 'block';
	el.style.visibility = 'visible';

	var fieldOffset = getOffset(this.inputField);
	this.ul.style.top = (fieldOffset[1] + this.inputField.offsetHeight) + 'px';
}
SPP.isVisible = function (el) {
	return (el.style.visibility == 'visible');
}
SPP = null;

/*
	SmartPickController class
*/
function SmartPickController (win) {
	// array of all smartpicks on page, keyed by id
	this.smartPicksArray = new Array();
	this.win = win;
	this.blurEventItem;
	this.blurEventFunc;
}
var SPCP = SmartPickController.prototype;
SPCP.setupSmartPicks = function (s) {
	var newSmartPicks = findChildElements(s, function (e) { return (hasClassName(e, 'smartPick') && (e.tagName == 'INPUT') && (!hasClassName(e, 'disabled'))) } );
	var thisPick;
	for (var s in newSmartPicks) {
		this.setupSmartPick(newSmartPicks[s]);
	}
}
SPCP.setupSmartPick = function (field) {
	var options = getOptions(field.id);
	if (options.length < 1)
		options = getOptions(field.id.substring(0,field.id.length-1));
	thisPick = new SmartPick(field, options, this.win);
	this.addSmartPick(thisPick);
}
SPCP.addSmartPick = function (sp) {
	this.smartPicksArray[sp.id] = sp;
}
SPCP.inputExecute = function (f) {
	var eventObj = this.win.event.srcElement;
	var id = eventObj.id;
	var sp = this.smartPicksArray[id];
	sp[f](this.win.event);
}
SPCP.ulExecute = function (f) {
	var evUL = this.win.event.srcElement;
	var c = evUL.parentNode;
	var thisIn = findChildElements(c, function (e) { return (hasClassName(e, 'smartPick') && (e.tagName == 'INPUT')) } )[0];
	var id = thisIn.id;
	var sp = this.smartPicksArray[id];
	sp[f](evUL, this.win.event);
}
SPCP.liExecute = function (f) {
	var evLI = this.win.event.srcElement;
	var c = evLI.parentNode.parentNode;
	var thisIn = findChildElements(c, function (e) { return (hasClassName(e, 'smartPick') && (e.tagName == 'INPUT')) } )[0];
	var id = thisIn.id;
	var sp = this.smartPicksArray[id];
	sp[f](evLI, this.win.event);
}
SPCP = null;

/*
	Make the Billing section visible
*/

function makeBillingSectionVisible( billingInfoLink, billingInfoCounterSection, rfiTotalText, win )
{
	billingInfoLink.onclick = function () {
		toggleFields(win.name,billingInfoLink,win.document,win.document.customer,'billinginfo',1);}
	//removeDisplayStyle( billingInfoCounterSection,"none" );
	//rfiTotalText.innerText = 2 + Number(rfiTotalText.innerText);
}

/*
	Initialize the app.
*/
function init () {
	parent.alertWindow = new AlertWindow(document);
	parent.newsWindow = new newsWindow(document, 'newsWindow');
	parent.DismissFloater = new DismissFloater('dismissFloater');
	parent.QuotePolicyController = new QuotePolicyController();
	updateAllTables(document.getElementsByClassName('quotes'));
}

// Make sure initialization happens *after* page is loaded
addEvent(window, 'load', init);
