function selectState(selectedState) {
	var stateOptions = document.getElementById('sState_Province');
	for (var i=0; i< stateOptions.options.length; i++) {
		if (stateOptions.options[i].value == selectedState) {
			stateOptions.options[i].selected = true;
		}
		else {
			stateOptions.options[i].selected = false;
		}
	}
}

YAHOO.util.Event.onDOMReady(function(){
	var pc = YAHOO.util.Dom.get('purchaserContract');
	if (pc != null && pc.checked) {
		toggleContent(pc, 'contractOwnerInfo', true);
	}
});

var sAttr, sAnim;

function getObjHeight(objId) {
	var region = YAHOO.util.Dom.getRegion(objId);
	return (region.bottom - region.top);
}

function showContent(el, objId) {
	var origHeight = YAHOO.util.Dom.get(objId).origHeight;
	var isExpanded = false;
	
	if (origHeight == undefined) {
		origHeight = getObjHeight(objId);
		YAHOO.util.Dom.get(objId).origHeight = origHeight;
		YAHOO.util.Dom.addClass(objId, "visible0");
		YAHOO.util.Dom.removeClass(objId, "hideFromScreen");
	}
	else {
		var currHeight = parseInt(YAHOO.util.Dom.getStyle(objId, "height"));
		isExpanded = currHeight > 0;
	}
	
	processAnim(objId, isExpanded ? origHeight : 0, isExpanded ? 0 : origHeight);
	YAHOO.util.Dom.replaceClass(el, isExpanded ? "btnPrimGreyRightExpanded" : "btnPrimGreyRightCollapsed", isExpanded ? "btnPrimGreyRightCollapsed" : "btnPrimGreyRightExpanded");
}

function toggleContent(el, objId) {
	var cHeight;
	
	if (YAHOO.util.Dom.get(objId).origHeight == undefined) {
		YAHOO.util.Dom.get(objId).origHeight = getObjHeight(objId);
		cHeight = YAHOO.util.Dom.get(objId).origHeight;
	}
	else {
		cHeight = parseInt(YAHOO.util.Dom.getStyle(objId, "height"));	
	}
	
	if (cHeight > 0 && el.checked == true) {
		fillForm();
		if (arguments[2] == true) { 
			YAHOO.util.Dom.setStyle(objId, "height", "0px");		
		}
		else {
			processAnim(objId, YAHOO.util.Dom.get(objId).origHeight, 0);
		}
	}
	else {
		blankForm();
		processAnim(objId, 0, YAHOO.util.Dom.get(objId).origHeight);
	}
}

function processAnim(objId, sfrom, sto) {
	sAttr = { height: { from: sfrom, to: sto } };
	sAnim = new YAHOO.util.Anim(objId, sAttr);
    sAnim.duration = 1.2;
    sAnim.method = YAHOO.util.Easing.easeOut;
	sAnim.animate();
}

function fillForm() {
	document.getElementById("sFirstName").value = contractInfo.Ownerfirstname;
	document.getElementById("sMiddleInitial").value = contractInfo.Ownermiddleinitial;
	document.getElementById("sLastName").value = contractInfo.Ownerlastname;
	document.getElementById("sAddress1").value = contractInfo.Owneraddress;
	document.getElementById("sAddress2").value = contractInfo.Owneraddress2;
	document.getElementById("sCity").value = contractInfo.Ownercity;
	selectState(contractInfo.Ownerstate);
	document.getElementById("sPostalCode").value = contractInfo.Ownerzipcode;
}

function blankForm() {
	document.getElementById("sFirstName").value = "";
	document.getElementById("sMiddleInitial").value = "";
	document.getElementById("sLastName").value = "";
	document.getElementById("sAddress1").value = "";
	document.getElementById("sAddress2").value = "";
	document.getElementById("sCity").value = "";
	selectState("");
	document.getElementById("sPostalCode").value = "";
}

var PricingOptions = {};

PricingOptions.Constants = {
	DEDUCTIBLE_OPTIONS: [0, 50, 100, 200],
	DEDUCTIBLE_FIELD_ID: 'deductibleValue',
	DEDUCTIBLE_SELECT_ID: 'deductible-slider-units',
	DEDUCTIBLE_WIDGET_ID: 'deductible-select-widget',
	
	SCHEDULE_OPTIONS: [0, 6, 12, 18],
	SCHEDULE_FIELD_ID: 'paymentValue',
	SCHEDULE_SELECT_ID: 'payment-slider-units',
	SCHEDULE_WIDGET_ID: 'payment-select-widget',
	
	GENERIC_CLASSFLAG: 'pricing-option', 
	DEDUCTIBLE_CLASSFLAG: 'pricing-option-deductible',
	SCHEDULE_CLASSFLAG: 'pricing-option-schedule',
	MONTHLY_CLASSFLAG: 'pricing-option-monthly',
	DOWNPAYMENT_CLASSFLAG: 'pricing-option-downpayment',
	SUBTOTAL_CLASSFLAG: 'pricing-option-subtotal',
	TOTAL_CLASSFLAG: 'pricing-option-total'
};

PricingOptions.Manager = function(quoteOptions) { this.init(quoteOptions); }

PricingOptions.Manager.prototype = {
	_c: PricingOptions.Constants,
	
	_deductible: null,
	_deductibleField: null,
	_deductibleSelect: null,
	_deductibleWidget: null,
	
	_schedule: null,
	_scheduleField: null,
	_scheduleSelect: null,
	_scheduleWidget: null,
	
	_quoteOptions: null,
	_firstLoad: true,
		
	'init': function(quoteOptions) {
		this._quoteOptions = quoteOptions;

		this.initDeductible();
		this.initSchedule();

		YAHOO.util.Event.addListener(YAHOO.util.Dom.getElementsByClassName('quote-engine-get-price', 'A', 'main-box'), 'click', function() {
			this.onPricingOptionsChanged();
		}, this, true);
		
		this.onPricingOptionsChanged();
	},

	'initDeductible': function() {
		this._deductibleField = YAHOO.util.Dom.get(this._c.DEDUCTIBLE_FIELD_ID);
		this._deductibleSelect = YAHOO.util.Dom.get(this._c.DEDUCTIBLE_SELECT_ID);
		this._deductibleWidget = YAHOO.util.Dom.get(this._c.DEDUCTIBLE_WIDGET_ID);

		if (this._deductibleSelect.options.length <= 1) {
			YAHOO.util.Dom.setStyle("deductible-cont", "display", "none");
			YAHOO.util.Dom.addClass("payment-cont", "deductibleSNA");			
		}

		this._deductible = this.getSelectWidget(this._deductibleField, this._deductibleSelect, this._deductibleWidget, 'onDeductibleChangeEvent');
	},
	
	'initSchedule': function() {
		this._scheduleField = YAHOO.util.Dom.get(this._c.SCHEDULE_FIELD_ID);
		this._scheduleSelect = YAHOO.util.Dom.get(this._c.SCHEDULE_SELECT_ID);
		this._scheduleWidget = YAHOO.util.Dom.get(this._c.SCHEDULE_WIDGET_ID);

		if (this._scheduleSelect.options.length <= 1) {
			YAHOO.util.Dom.setStyle("payment-cont", "display", "none");
			YAHOO.util.Dom.addClass("deductible-cont", "paymentSNA");
		}		
		
		this._schedule = this.getSelectWidget(this._scheduleField, this._scheduleSelect, this._scheduleWidget, 'onScheduleChangeEvent');		
	},
	
	'getSelectWidget': function(fld, sel, widg, fn) {
		if (fld.value) {
			for (var i = 0, j = sel.options.length; i < j; i ++) {
				sel.options[i].selected = sel.options[i].value == fld.value ? true : false;
			}
		}

		if (!sel.selectedIndex || sel.selectedIndex < 0) {
			sel.selectedIndex = 0;
		}

		YAHOO.util.Dom.batch(YAHOO.util.Dom.getElementsByClassName('widget-select-display', null, widg), function(wd, val) { 
			wd.innerHTML = val;
		}, sel.options[sel.selectedIndex].text);

		var selectMenu = new YAHOO.widget.Menu(sel, { 
			'position': 'dynamic', 
			'keepopen': false, 
			'clicktohide': true, 
			'classname': 'widget-select-menu', 
			'hidedelay': 500, 
			'constraintoviewport': false, 
			
			'effect': {
				'effect': ESP.widget.ContainerEffect.SLIDEY,
				'duration': 0.2
			},
			
			'context': [widg.id, "tl", "tl"],
			'shadow': false 
		});

		selectMenu.getItem(sel.selectedIndex).cfg.setProperty("checked", true);
		
		selectMenu.subscribe('click', function(type, e, args) {
			if (this.activeItem) {
				args[0][args[1]](this.srcElement, args[2], this.activeItem);
			}
		}, [this, fn, widg]);
		
		selectMenu.setHeader('<br/>');
		selectMenu.setFooter('<br/>');
		
		YAHOO.util.Dom.addClass(sel.parentNode, 'widget-use-widget');

    		selectMenu.render('current-plan-tab-cascade');

		YAHOO.util.Event.addListener(widg, "click", function() { this.show(); }, null, selectMenu);

		return selectMenu;
	},
	
	'onDeductibleChangeEvent': function(sel, el, oMenuItem) {
		var oldValue = this._deductibleSelect.selectedIndex;
		
		this.onSelectChangedEvent(sel, el, oMenuItem);
		
		if (oldValue != this._deductibleSelect.selectedIndex) {
			
		}
		
		this.onWidgetsChangedEvent();
	},
	
	'onScheduleChangeEvent': function(sel, el, oMenuItem) {
		var oldValue = this._scheduleSelect.selectedIndex;
		
		this.onSelectChangedEvent(sel, el, oMenuItem);
		
		if (oldValue != this._scheduleSelect.selectedIndex) {
			
		}
		
		this.onWidgetsChangedEvent();
	},	
	
	'onSelectChangedEvent': function(sel, el, oMenuItem) {
		if (oMenuItem.index != sel.selectedIndex) {
			if (sel.selectedIndex > -1) {
				oMenuItem.parent.getItem(sel.selectedIndex).cfg.setProperty("checked", false);
			}

			sel.selectedIndex = oMenuItem.index;
		}

		if (!oMenuItem.cfg.getProperty("checked")) {
			oMenuItem.cfg.setProperty("checked", true);
		}

		YAHOO.util.Dom.batch(YAHOO.util.Dom.getElementsByClassName('widget-select-display', null, el), function(w, v) { 
			w.innerHTML = v; 
		}, sel.options[sel.selectedIndex].text);		
	},
	
	'onWidgetsChangedEvent': function() {
		YAHOO.util.Dom.batch(YAHOO.util.Dom.getElementsByClassName('quote-engine-get-price', 'A', 'main-box'), function(el) {
			YAHOO.util.Dom.removeClass(el, 'disabled');
		});
	},
	
	'onPricingOptionsChanged': function() {
		this._deductibleField.value = this._deductibleSelect.options[this._deductibleSelect.selectedIndex].value;
		this._scheduleField.value = this._scheduleSelect.options[this._scheduleSelect.selectedIndex].value;
		
		var deductible = parseInt(this._deductibleField.value);
		var schedule = parseInt(this._scheduleField.value);
		
		var downpayment = this._quoteOptions[deductible][schedule].dp;
		var monthly = this._quoteOptions[deductible][schedule].mp;
		var total = this._quoteOptions[deductible][schedule].total;
		
		var els = YAHOO.util.Dom.getElementsByClassName(this._c.GENERIC_CLASSFLAG);

		for (var i = 0; i < els.length; i ++) {
			var el = els[i];

			if (YAHOO.util.Dom.hasClass(el, this._c.DEDUCTIBLE_CLASSFLAG)) {
				el.innerHTML = formatNumber(deductible.toFixed(2));
			}
			else if (YAHOO.util.Dom.hasClass(el, this._c.SCHEDULE_CLASSFLAG)) {
				if ((schedule - 1) < 0) {
					el.innerHTML = 0;
				}
				else {
					el.innerHTML = schedule - 1;
				}
			}
			else if (YAHOO.util.Dom.hasClass(el, this._c.DOWNPAYMENT_CLASSFLAG)) {
				el.innerHTML = formatNumber(downpayment.toFixed(2));
			}
			else if (YAHOO.util.Dom.hasClass(el, this._c.MONTHLY_CLASSFLAG)) {
				el.innerHTML = formatNumber(monthly.toFixed(2));
			}
			else if (YAHOO.util.Dom.hasClass(el, this._c.TOTAL_CLASSFLAG)) {
				el.innerHTML = formatNumber(total.toFixed(2));
			}
		}
		
		YAHOO.util.Dom.batch(YAHOO.util.Dom.getElementsByClassName('quote-engine-get-price', 'A', 'main-box'), function(el) {
			YAHOO.util.Dom.addClass(el, 'disabled');
		});		
		
		if (this._firstLoad) {
			YAHOO.util.Dom.removeClass('pricingOptions', 'visibilityHidden');
			this._firstLoad = false;
		}
	}
};

var ESPToolTips = {};

ESPToolTips.Constants = {
	DEFAULT_TOOL_TIP_ID: 'vin-tool-tips',
	TOOLTIP_TRIGGER_CLASSFLAG: 'tool-tips-trigger',
	MILE_PER_YEAR_TIGGER_CLASSFLAG: 'miles-per-year-tigger',
	TOOLTIP_PANEL_CLASSFLAG: 'tool-tips'
}

ESPToolTips.Manager = function() { this.init(); }

ESPToolTips.Manager.prototype = {
	_c: ESPToolTips.Constants,

	_triggers: null,
	_panels: null,

	init: function() {
		var triggers = YAHOO.util.Dom.getElementsByClassName(this._c.TOOLTIP_TRIGGER_CLASSFLAG);

		YAHOO.util.Event.addListener(triggers, "focus", function() { 
			YAHOO.util.Dom.removeClass(YAHOO.util.Dom.getElementsByClassName(ESPToolTips.Constants.TOOLTIP_PANEL_CLASSFLAG, 'div'), 'current-tip'); 
			YAHOO.util.Dom.addClass((this.id + '-tool-tips'), 'current-tip');
		});
	}	
}

var ESPFlash = {};

ESPFlash.Constants = {
	SWF_PATH: '/Storage/Owner2/assets/swf/esp.swf',
	CONTAINER_ID: 'swfHolder',
	NOFLASH_ID: 'noflash',
	FLASH_VERSION: '9.0.45',
	
	WIDTH_MAX: 728,
	WIDTH_MIN: 728,
	HEIGHT_MAX: 1220, /*662,*/
	HEIGHT_MIN: 389,
	SHORT_HEIGHT_MIN: 227,

	ANIM_DURATION: .05
};

ESPFlash.Manager = function(planname, args) { this.init(planname, args); }

ESPFlash.Manager.prototype = {
	_c: ESPFlash.Constants,

	_swf: null,
	_container: null,
	_height: ESPFlash.Constants.HEIGHT_MIN,
	_success: false,

	init: function(planname, args) {
		this._container = YAHOO.util.Dom.get(this._c.CONTAINER_ID);
		YAHOO.util.Dom.setStyle(this._container, "overflow", "hidden");
		
		if ( planname != null && planname != '' ) { 
			this._height = this._c.SHORT_HEIGHT_MIN; 
		}
			
		this.doResize();
		
		var width = args && args.width ? args.width : this._c.WIDTH_MAX;
		var height = args && args.height ? args.height : this._c.HEIGHT_MAX;
		var version = args && args.version ? args.version : this._c.FLASH_VERSION;
		var planXMLpath = args && args.planXMLpath ? args.planXMLpath : 'xml/plans.xml';
		
		this._swf = new SWFObject(this._c.SWF_PATH, "esp_wizard", width, height, version);
		this._swf.addParam("wmode", "transparent");
		this._swf.addParam("quality", "high");
		this._swf.addParam("menu", "false");

		this._swf.addVariable("plan", planname);
		this._swf.addVariable("planXMLpath", planXMLpath);
		this._success = this._swf.write(this._c.CONTAINER_ID);

		if (!this._success) {
			YAHOO.util.Dom.setStyle(this._c.CONTAINER_ID, "display", "none");
			YAHOO.util.Dom.setStyle(this._c.NOFLASH_ID, "display", "block");
		}
	},

	handleResize: function(newVal, isAddition) {
		var currentHeight = this._height;
		var newHeight = newVal + (isAddition ? currentHeight : 0);
		
		this._height = newHeight;
		//this.doResize({ height: { from: currentHeight, to: newHeight } }); // Flash is handling all tweening on its own
		this.doResize(null);
	},

	doResize: function(animConfig) {
		if (YAHOO.lang.isObject(animConfig)) {
			var anim = new YAHOO.util.Anim(this._container, animConfig);
		    anim.duration = this._c.ANIM_DURATION;
		    anim.method = YAHOO.util.Easing.easeOut;
			anim.animate();
		}
		else {
			YAHOO.util.Dom.setStyle(this._container, "height", ('' + this._height + 'px'));
		}
	}
};

function resize(newVal, isAddition) { _efm.handleResize(newVal, isAddition); }

function setOdometerReading() {
	var $D = YAHOO.util.Dom; 
	var odometerReading = $D.get('odometer-reading'); 
	stopNaNChar(odometerReading);
}


var ESPPlanTabs = {};

ESPPlanTabs.Constants = {
	TAB_CLASSFLAG: 'plan-tab',
	
	IS_ACTIVE: function(el, planKey) {
		return planKey && YAHOO.util.Dom.hasClass(el, (planKey + 'Plan'));
	},
	
	SET_INACTIVE: function(el) {
		//YAHOO.util.Dom.addClass(YAHOO.util.Dom.getFirstChild(el), "page-plan-tab-inactive");
	},
	
	SET_ACTIVE: function(el) {
		//YAHOO.util.Dom.removeClass(YAHOO.util.Dom.getFirstChild(el), "page-plan-tab-inactive");
	}
};

ESPPlanTabs.Manager = function(planKey, clickFunction, doBgSwap) { this.init(planKey, clickFunction, doBgSwap); }

ESPPlanTabs.Manager.prototype = {
	_c: ESPPlanTabs.Constants,
	
	_init: false,
	_plan: null,
	_tabs: null,
	
	_doBgSwap: false,
	
	init: function(planKey, clickFunction, doBgSwap) {
		this._plan = planKey;
		this._tabs = YAHOO.util.Dom.getElementsByClassName(this._c.TAB_CLASSFLAG, null, null);
		
		if (doBgSwap && doBgSwap === true) {
			this._doBgSwap = true;
		}
		
		this.update(clickFunction);
		this._init = true;
	},
	
	update: function(clickFunction) {
		for (var i = 0; i < this._tabs.length; i ++) {
			var el = this._tabs[i];
			
			if (!this._c.IS_ACTIVE(el, this._plan)) { 
				if (!this._doBgSwap) {
					this._c.SET_INACTIVE(el);
				}
				else {
				}
			}
			
			if (clickFunction) {
				var a = el.tagName && el.tagName == "A" ? el : YAHOO.util.Dom.getFirstChildBy(el, function(c) { return c.tagName && c.tagName == "A"; });
				
				if (a && (!this._init || YAHOO.util.Event.removeListener(a, "click", clickFunction))) {
					YAHOO.util.Event.addListener(a, "click", clickFunction);
				}				
			}
		}
	}
}

function setInterceptRedirect(el)
{
	if ( document.espEditForm ) {
		//document.espEditForm.action = el.href;
		var url = unescape(el.href);
		var pos = el.href.indexOf('pagename=');
		if (pos > -1) {
			url = url.substring((pos + 9), url.length);
		}
		document.espEditForm.pagename.value = url;
		showModal('esp-edit-intercept-module');
	}
	return false;
}

YAHOO.namespace ("compare");

var rows;
YAHOO.compare.init = function() {
	rows = YAHOO.util.Selector.query("#compare-plan-page .compare-plan-row");
	yDOM.removeClass(rows, "expandList");
	for (var i=0; i<rows.length; i++) {
		if (i % 2 == 0) {
			yEvent.addListener(rows[i], "mouseover", function() {
				yDOM.removeClass(rows, "featureHeaderHover");
				yDOM.removeClass(rows, "featureHeaderExpandHover");
				
				yDOM.addClass(this, "featureHeaderHover");
				
				if (yDOM.hasClass(this, "expandList")) {
					yDOM.addClass(this, "featureHeaderExpandHover");
				}

			});
			yEvent.addListener(rows[i], "mouseout", function() {
				yDOM.removeClass(this, "featureHeaderHover");
				yDOM.removeClass(this, "featureHeaderExpandHover");
			});			
			yEvent.addListener(rows[i], "click", function() {
				YAHOO.compare.toggleRows(yDOM.getNextSibling(this));
				yDOM.addClass(this, "featureHeaderExpandHover");
			});
		}
		else {
			yDOM.setStyle(rows[i], "display", "none");
			yEvent.addListener(rows[i], "click", function() {
				YAHOO.compare.toggleRows(this);
			});
		}
	}
}

YAHOO.compare.toggleRows = function(obj) {
	if (yDOM.hasClass(obj, "currentList")) {
		yDOM.removeClass(obj, "currentList");
		yDOM.removeClass(yDOM.getPreviousSibling(obj), "expandList");
	}
	else {
		yDOM.removeClass(rows, "currentList");
		yDOM.removeClass(rows, "expandList");
		yDOM.addClass(yDOM.getPreviousSibling(obj), "expandList");
		yDOM.addClass(obj, "currentList");
	}
}

yEvent.onDOMReady(YAHOO.compare.init); 

function formatNumber(p) {	
	if ( !isNaN(p) ){
		var tp = p + '';
		
		var cPos = 3;
		
		if (tp.indexOf('.') > -1) { cPos = 6; }
				
		if (tp.length > cPos ) {
			return (tp.substring(0, tp.length-cPos) + ',' + tp.substring(tp.length-cPos));	
		}
		else {
			return tp;	
		}
	}
	else {
		return p;
	}
}

var QuoteCalculator = {};

QuoteCalculator.Constants = {
	MESSAGE_PLAN_UNAVAILABLE: 'We\'re sorry, but this plan is not available for your vehicle.',
	MESSAGE_PLAN_RECOMMENDATION: 'This plan is unavailable for the currently selected coverage terms. Click the tab for recommended coverage under this plan.',
	
	PLAN_FIELD_ID: 'plan-textbox',
	PLAN_TYPE_FIELD_ID: 'plan-type-textbox',	
	VIN_FIELD_ID: 'vin-textbox',
	STATE_FIELD_ID: 'state-textbox',
	WARRANTYSTART_FIELD_ID: 'warranty-start-textbox',
	POWERTRAINPLAN_FIELD_ID: 'pt-plan-textbox',
	SNOWPLOW_FIELD_ID: 'snowplow-textbox',
	
	YEARS_OPTIONS: [3, 4, 5, 6, 7], /* 0, 1, 2, */
	YEARS_FIELD_ID: 'years-textbox',
	YEARS_SELECT_ID: 'years-select',
	YEARS_WIDGET_ID: 'years-select-widget',
	
	MILES_OPTIONS: [36000, 48000, 60000, 75000, 100000],
	MILES_FIELD_ID: 'miles-textbox', 
	MILES_SELECT_ID: 'miles-select',
	MILES_WIDGET_ID: 'miles-select-widget',
	
	YEARS_MILES_MAP: { 
		'3': { '75000': '75,000', '100000': '100,000' }, 
		'4': { '75000': '75,000', '100000': '100,000' }, 
		'5': { '36000': '36,000', '48000': '48,000', '60000': '60,000', '75000': '75,000', '100000': '100,000' }, 
		'6': { '36000': '36,000', '48000': '48,000', '60000': '60,000', '75000': '75,000', '100000': '100,000' }, 
		'7': { '36000': '36,000', '48000': '48,000', '60000': '60,000', '75000': '75,000', '100000': '100,000' } 
	},

	DEDUCTIBLE_DEFAULT: 100,
	DEDUCTIBLE_DEFAULT_CODE: 'HD',
	SCHEDULE_DEFAULT: 17,
	MONTH_OPTIONS: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	
	GENERIC_CLASSFLAG: 'quote-calculator',
	DURATION_YEARS_CLASSFLAG: 'quote-calculator-years',
	DURATION_ENDDATE_CLASSFLAG: 'quote-calculator-enddate',
	DURATION_MILES_CLASSFLAG: 'quote-calculator-miles',
	DOWNPAYMENT_CLASSFLAG: 'quote-calculator-downpayment',
	DEDUCTIBLE_CLASSFLAG: 'quote-calculator-deductible',
	SCHEDULE_CLASSFLAG: 'quote-calculator-schedule',
	SUBTOTAL_CLASSFLAG: 'quote-calculator-subtotal', 
	MONTHLY_CLASSFLAG: 'quote-calculator-monthly',
	TOTAL_CLASSFLAG: 'quote-calculator-total',
	CONTINUE_CLASSFLAG: 'quote-calculator-continue',
	GET_PRICE_CLASSFLAG: 'quote-calculator-get-price',
	
	REQUEST_VALID_CLASSFLAG: 'quote-calculator-request-valid',
	REQUEST_INVALID_CLASSFLAG: 'quote-calculator-request-invalid',
	REQUEST_PROCESSING_CLASSFLAG: 'quote-calculator-request-processing',
	
	REQUEST_SHIM_CLASSFLAG: 'quote-calculator-shim',
	REQUEST_INVALID_SHIM_CLASSFLAG: 'quote-calculator-request-invalid-shim',
	REQUEST_PROCESSING_SHIM_CLASSFLAG: 'quote-calculator-request-processing-shim',
	
	REQUEST_PLAN_TYPE: 'core',
	REQUEST_BASE_URL: '/servlet/ContentServer?pagename=Owner/ESP/GetQuote&',
	REQUEST_URL_FORMAT: '{url}state={state}&deductible={deductible}&payments={payments}&vin={vin}&planCode={planCode}&planMileage={miles}&planMonths={months}&warrantyStartDate={warrantyStart}&powertrainPlanCode={ptPlanCode}&snowplow={snowplow}&planType={planType}',
	
	UNAVAILABLE_MESSAGE: '-',
	
	PLAN_CODES: { 'prem': 'PREM', 'ex': 'EX', 'base': 'BASE', 'ptrn': 'PTRN' },	
	PLAN_BASE: 650,
	PLAN_OFFSET: { 'premium': 1, 'extra': .9, 'base': .8, 'powertrain': .7 } /* for prototyping only */
};

QuoteCalculator.Manager = function(planData, quoteData, startDate, planCodeData, recommendationData) { this.init(planData, quoteData, startDate, planCodeData, recommendationData); };

QuoteCalculator.Manager.prototype = {
	_init: false,
	
	_planField: null,
	_plan: null,
	
	_planTypeField: null,
	_planType: null,

	_stateField: null,
	_state: null,

	_startDate: null,	
	
	_yearsIncrement: 58,
	_yearsField: null,
	_yearsSelect: null,
	_yearsWidget: null,
	_years: null,
	
	_milesIncrement: 35,
	_milesField: null,
	_milesSelect: null,
	_milesWidget: null,
	_miles: null,
	
	_messagers: null,
	
	_requestUrlFormat: null,
	_planData: null,
	_quoteData: null,
	_planCodeData: null,
	_recommendationData: null,
	_planName: null,
	_planSelected : false,	
	_tooltips: {},
		
	'init': function(planData, quoteData, startDate, planCodeData, recommendationData) {
		this._c = QuoteCalculator.Constants;

		this._planTypeField = YAHOO.util.Dom.get(this._c.PLAN_TYPE_FIELD_ID);
		this._planType = this._planTypeField.value;	
	
		this._planField = YAHOO.util.Dom.get(this._c.PLAN_FIELD_ID);
		this._plan = this._planField.value;
		//this._plan = planCodeData[this._planType]['code']; /* #### TODO: PROTOYPE ONLY */

		this._stateField = YAHOO.util.Dom.get(this._c.STATE_FIELD_ID);
		this._state = this._stateField.value;

		this._startDate = new Date(startDate);

		this._planData = planData; 
		this._quoteData = quoteData;
		this._planCodeData = planCodeData;
		this._recommendationData = recommendationData;		
		
		this._planName = this._planCodeData[this._planType]['name'];		
		
		this._messagers = YAHOO.util.Dom.getElementsByClassName(this._c.GENERIC_CLASSFLAG);

		// ### TODO PROTOTYPING ONLY???
		//(YAHOO.util.Dom.get(this._c.YEARS_FIELD_ID)).value = (this._quoteData[this._planType]['planMonths'] / 12);
		//(YAHOO.util.Dom.get(this._c.MILES_FIELD_ID)).value = this._quoteData[this._planType]['planMileage'];		
		
		this.initYears();
		this.initMiles();
		
		this.updateYearsOptions();
		this.updateMilesOptions();

		// ### TODO PROTOTYPING ONLY???
		//this._yearsField.value = this._yearsSelect.options[this._yearsSelect.selectedIndex].value; /* ### PROTOTYPING ONLY?? */
		//this._milesField.value = this._milesSelect.options[this._milesSelect.selectedIndex].value; /* ### PROTOTYPING ONLY?? */
		
		YAHOO.util.Dom.batch(YAHOO.util.Dom.getElementsByClassName('page-plan-tab', null, 'main-box'), function(el) {
			YAHOO.util.Event.addListener(el, 'click', function(e, lnk) { 
				this.onTabClick(lnk, e);
			}, el, this);

			var planTypeName = ((el.className.match(/quote-calculator-tab-(prem|ex|base|ptrn)/))[1]);

			this._tooltips[planTypeName] = new ESP.widget.Tooltip(planTypeName + '-tab-tooltip', { 'context': [el.id, 'tl', 'bl'], 'text': '', 'tail': 'tm', 'contextCentered': true });
			
			this._tooltips[planTypeName].subscribe('contextMouseOver', function(type, e, args) {
				if (YAHOO.util.Dom.hasClass(e[0], 'quote-calculator-tab-unavailable') || YAHOO.util.Dom.hasClass(e[0], 'quote-calculator-tab-recommendation')) {
					this.cfg.setProperty('text', YAHOO.util.Dom.hasClass(e[0], 'quote-calculator-tab-unavailable') ? QuoteCalculator.Constants.MESSAGE_PLAN_UNAVAILABLE : QuoteCalculator.Constants.MESSAGE_PLAN_RECOMMENDATION, true);
					
					return true;
				}
				else {
					return false;
				}
			}, [this]);
		}, this, true);		

		this.onQuoteCalculatorChanged();

		this._requestUrlFormat = YAHOO.lang.substitute(this._c.REQUEST_URL_FORMAT, {
			'url': this._c.REQUEST_BASE_URL,
			'state': this._state,
			'deductible': this._c.DEDUCTIBLE_DEFAULT_CODE,
			'payments': this._c.SCHEDULE_DEFAULT, 
			'vin': YAHOO.util.Dom.get(this._c.VIN_FIELD_ID).value,
			'warrantyStart': YAHOO.util.Dom.get(this._c.WARRANTYSTART_FIELD_ID).value,
			'ptPlanCode': YAHOO.util.Dom.get(this._c.POWERTRAINPLAN_FIELD_ID).value,
			'snowplow': (YAHOO.util.Dom.get(this._c.SNOWPLOW_FIELD_ID).value == 'true' ? 'true' : 'false'),
			'planType': this._c.REQUEST_PLAN_TYPE
		});

		YAHOO.util.Dom.batch(YAHOO.util.Dom.getElementsByClassName(this._c.GET_PRICE_CLASSFLAG, null, 'main-box'), function(el) {
			YAHOO.util.Dom.addClass(el, 'disabled');
			
			YAHOO.util.Event.addListener(el, 'click', function(e, lnk) { 
				YAHOO.util.Event.stopEvent(e); 

				if (!YAHOO.util.Dom.hasClass(lnk, 'disabled')) {
					this.requestQuoteWrapper(false);
				}
			}, el, this);
		}, this, true);
		
		// doublecheck active tab matches plantype - can mismatch from browser back button [eg firefox]
		if (!YAHOO.util.Dom.hasClass('current-plan-tab-cascade', (this._planType + 'Plan'))) {
			YAHOO.lang.later(500, this, function() { 
				this.onTabClick(arguments[0], null);
			}, YAHOO.util.Dom.getElementsByClassName(('quote-calculator-tab-' + this._planType), 'A', 'main-box'));
		}

		YAHOO.util.Dom.setStyle(YAHOO.util.Dom.getElementsByClassName('esp3-grid-current-container', 'DIV', 'esp3-grid-current-wrapper-block'), 'opacity', .85);
		
		this._init = true;
	},
	
	'initYears': function() {
		this._yearsField = YAHOO.util.Dom.get(this._c.YEARS_FIELD_ID);
		this._yearsSelect = YAHOO.util.Dom.get(this._c.YEARS_SELECT_ID);
		this._yearsWidget = YAHOO.util.Dom.get(this._c.YEARS_WIDGET_ID);
		
		this._years = this.getSelectWidget(this._yearsField, this._yearsSelect, this._yearsWidget, 'onYearsChangedEvent');
	},

	'initMiles': function() {
		this._milesField = YAHOO.util.Dom.get(this._c.MILES_FIELD_ID);
		this._milesSelect = YAHOO.util.Dom.get(this._c.MILES_SELECT_ID);
		this._milesWidget = YAHOO.util.Dom.get(this._c.MILES_WIDGET_ID);
		
		this._miles = this.getSelectWidget(this._milesField, this._milesSelect, this._milesWidget, 'onMilesChangedEvent');
	},	
	
	'getSelectWidget': function(fld, sel, widg, fn) {
		if (fld.value) {
			for (var i = 0, j = sel.options.length; i < j; i ++) {
				sel.options[i].selected = sel.options[i].value == fld.value ? true : false;
			}
		}
		
		if (!sel.selectedIndex || sel.selectedIndex < 0) {
			sel.selectedIndex = 0;
		}

		YAHOO.util.Dom.batch(YAHOO.util.Dom.getElementsByClassName('widget-select-display', null, widg), function(wd, val) { wd.innerHTML = val; }, sel.options[sel.selectedIndex].text);

		var selectMenu = new YAHOO.widget.Menu(sel, { 
			'position': 'dynamic', 
			'keepopen': false, 
			'clicktohide': true, 
			'classname': 'widget-select-menu', 
			'hidedelay': 500, 
			'constraintoviewport': false, 
			
			'effect': {
				'effect': ESP.widget.ContainerEffect.SLIDEY,
				'duration': 0.2
			},
			
			'context': [widg.id, "tl", "tl"],
			'shadow': false 
		});

		if (sel.selectedIndex > 0) selectMenu.getItem(sel.selectedIndex).cfg.setProperty("checked", true);
		
		selectMenu.subscribe('click', function(type, e, args) {
			if (this.activeItem) {
				args[0][args[1]](this.srcElement, args[2], this.activeItem);
			}
			else {
				//alert('nothing active');
			}
		}, [this, fn, widg]);
		
		selectMenu.setHeader('<br/>');
		selectMenu.setFooter('<br/>');
		
		YAHOO.util.Dom.addClass(sel.parentNode, 'widget-use-widget');

    		selectMenu.render('current-plan-tab-cascade');

		YAHOO.util.Event.addListener(widg, "click", function() { this.show(); }, null, selectMenu);
		
		return selectMenu;
	},
	
	'onFirstInteractionEvent': function() {
		
	},	
	
	'onYearsChangedEvent': function(sel, el, oMenuItem) {
		var oldValue = this._yearsSelect.selectedIndex;
		
		this.onSelectChangedEvent(sel, el, oMenuItem);
		
		if (oldValue != this._yearsSelect.selectedIndex) {
			this.updateMilesOptions();
		}
		
		this.onWidgetsChangedEvent();
	},
	
	'onMilesChangedEvent': function(sel, el, oMenuItem) {
		var oldValue = this._milesSelect.selectedIndex;
		
		this.onSelectChangedEvent(sel, el, oMenuItem);
		
		if (oldValue != this._milesSelect.selectedIndex) {
			
		}
		
		this.onWidgetsChangedEvent();
	},	
	
	'onSelectChangedEvent': function(sel, el, oMenuItem) {
		if (oMenuItem.index != sel.selectedIndex) {
			if (sel.selectedIndex > -1) {
				oMenuItem.parent.getItem(sel.selectedIndex).cfg.setProperty("checked", false);
			}

			sel.selectedIndex = oMenuItem.index;
		}

		if (!oMenuItem.cfg.getProperty("checked")) {
			oMenuItem.cfg.setProperty("checked", true);
		}

		YAHOO.util.Dom.batch(YAHOO.util.Dom.getElementsByClassName('widget-select-display', null, el), function(w, v) { 
			w.innerHTML = v; 
		}, sel.options[sel.selectedIndex].text);		
	},
	
	'onWidgetsChangedEvent': function() {
		this.updateRequestState();
	},
	
	'updateYearsOptions': function() {
		this._c.YEARS_MILES_MAP = this._planData[this._planType];

		// build array of actually available year options
		var planYears = [];
		for (var yr in this._c.YEARS_MILES_MAP) {
			planYears[planYears.length] = parseInt(yr); 
		}

		this._c.YEARS_OPTIONS = planYears;

		for (var i = 1, j = this._yearsSelect.options.length; i < j; i ++) {
			var disabled = (this._yearsSelect.options[i].value in this._c.YEARS_MILES_MAP) ? false : true;

			this._yearsSelect.options[i].disabled = disabled;
			this._years.getItem(i).cfg.setProperty("disabled", disabled);
			
			if (disabled && this._years.getItem(i).cfg.getProperty("checked")) {
				this._years.getItem(i).cfg.setProperty("checked", false);
			}
		}
		
		if (this._yearsSelect.options[this._yearsSelect.selectedIndex].disabled) {
			var index = 0;
			
			if ((this._planType in this._recommendationData) && YAHOO.lang.isObject(this._recommendationData[this._planType]) && ('duration' in this._recommendationData[this._planType])) {
				var duration = parseInt(this._recommendationData[this._planType]['duration']);
				
				if (!isNaN(duration)) {
					var years = '' + (duration / 12);
					
					for (var i = 1, j = this._yearsSelect.options.length; i < j; i ++) {
						if (this._yearsSelect.options[i].value == years) {
							index = i;
							break;
						}
					}
				}
			}
			
			this._yearsSelect.selectedIndex = index;
			this._years.getItem(this._yearsSelect.selectedIndex).cfg.setProperty('checked', true);
			
			YAHOO.util.Dom.batch(YAHOO.util.Dom.getElementsByClassName('widget-select-display', null, this._yearsWidget), function(el, val) { el.innerHTML = val; }, this._yearsSelect.options[this._yearsSelect.selectedIndex].text);
		}
	},
	
	'updateMilesOptions': function(preserve) {
		var year = this._yearsSelect.options[this._yearsSelect.selectedIndex].value;
		var milesOptions = (year in this._c.YEARS_MILES_MAP) ? this._c.YEARS_MILES_MAP[year] : {};

		for (var i = 1, j = this._milesSelect.options.length; i < j; i ++) {
			var disabled = milesOptions && (this._milesSelect.options[i].value in milesOptions) ? false : true;

			this._milesSelect.options[i].disabled = disabled;
			this._miles.getItem(i).cfg.setProperty("disabled", disabled);
		}

		if (this._milesSelect.options[this._milesSelect.selectedIndex].disabled) {
			var index = 0;

			if ((this._planType in this._recommendationData) && YAHOO.lang.isObject(this._recommendationData[this._planType]) && this._recommendationData[this._planType]['duration'] == ('' + (parseInt(year) * 12)) && ('mileage' in this._recommendationData[this._planType])) {
				var miles = this._recommendationData[this._planType]['mileage'];
				alert(miles);
				for (var i = 1, j = this._milesSelect.options.length; i < j; i ++) {
					if (this._milesSelect.options[i].value == miles) {
						index = i;
						break;
					}
				}
			}

			this._milesSelect.selectedIndex = index;
			this._miles.getItem(this._milesSelect.selectedIndex).cfg.setProperty('checked', true);

			YAHOO.util.Dom.batch(YAHOO.util.Dom.getElementsByClassName('widget-select-display', null, this._milesWidget), function(el, val) { el.innerHTML = val; }, this._milesSelect.options[this._milesSelect.selectedIndex].text);
		}
	},
	
	'updateRequestState': function(disabled) {
		if (!disabled && disabled !== false) {
			disabled = this._yearsSelect.selectedIndex < 1 || this._milesSelect.selectedIndex < 1 ? true : false;
		}
		
		YAHOO.util.Dom.batch(YAHOO.util.Dom.getElementsByClassName(this._c.GET_PRICE_CLASSFLAG, null, 'main-box'), function(el, disabled) {
			if (disabled) {
				YAHOO.util.Dom.addClass(el, 'disabled');
			}
			else {
				YAHOO.util.Dom.removeClass(el, 'disabled');
			}
		}, disabled);		
	},
	
	'onTabClick': function(tabClicked, e) {
		if (YAHOO.util.Dom.hasClass(tabClicked, 'quote-calculator-tab-unavailable') || YAHOO.util.Dom.hasClass(tabClicked, 'page-plan-tab-active') || YAHOO.util.Dom.hasClass(tabClicked, 'page-plan-tab-processing')) {
			if (e) YAHOO.util.Event.stopEvent(e);
			return;
		}
		
		this._doLock = true;

		if (e) YAHOO.util.Event.stopEvent(e);
		
		this.requestQuoteWrapper(((tabClicked.className.match(/quote-calculator-tab-(prem|ex|base|ptrn)/))[1]), YAHOO.util.Dom.hasClass(tabClicked, 'quote-calculator-tab-recommendation'));

		var _metricsName = s.pageName.replace(/:[^:]+$/, '');
		var _s = YAHOO.lang.merge(s_gi(s_account), s, { 'pageName': (_metricsName + ': ' + this._planName.toLowerCase()), 'eVar11': _metricsName, 'prop11': _metricsName, 'events': '', 'eVar48': '', 'prop48': '', 'eVar49': '', 'prop49': '' });
		_s.t();			
	},
	
	'requestQuoteWrapper': function(tabClicked, isRecommendation) {
		// show processing animation then defer call to onchange handler
		for (var j = 0; j < this._messagers.length; j ++) {
			var el = this._messagers[j];
			
			if (YAHOO.util.Dom.hasClass(el, this._c.REQUEST_VALID_CLASSFLAG)) {
				YAHOO.util.Dom.setStyle(el, "visibility", "hidden");
			}
			else if (YAHOO.util.Dom.hasClass(el, this._c.REQUEST_INVALID_CLASSFLAG)) {
				YAHOO.util.Dom.setStyle(el, "visibility", "hidden");
			}
			else if (YAHOO.util.Dom.hasClass(el, this._c.REQUEST_PROCESSING_CLASSFLAG)) {
				YAHOO.util.Dom.setStyle(el, "visibility", "visible");
			}
			else if (YAHOO.util.Dom.hasClass(el, this._c.REQUEST_SHIM_CLASSFLAG)) {
				YAHOO.util.Dom.setStyle(el, "display", "block");
			}
		}		

		YAHOO.util.Dom.batch(YAHOO.util.Dom.getElementsByClassName('page-plan-tab', 'A'), function(el) { 
			YAHOO.util.Dom.addClass(el, 'page-plan-tab-processing');
		});

		// ### PROTOTYPING ONLY -- build in delay		
		this.requestQuote(tabClicked, isRecommendation); //YAHOO.lang.later(2000, this, 'requestQuote', [tabClicked, isRecommendation]);
	},
	
	'requestQuote': function(tabClicked, isRecommendation) {
		var plan = tabClicked && tabClicked !== false ? this._planCodeData[tabClicked]['code'] : this._plan;
		var miles = isRecommendation ? this._recommendationData[tabClicked]['mileage'] : this._milesField.value;
		var months = isRecommendation ? this._recommendationData[tabClicked]['duration'] : (parseInt(this._yearsField.value) * 12);

		var quoteUrl = YAHOO.lang.substitute(this._requestUrlFormat, {
			'planCode': plan.toUpperCase(),
			'miles': miles,
			'months': months
		});

		YAHOO.util.Connect.asyncRequest('GET', quoteUrl, {
			'success': this['onSuccessQuoteRequest'],
			'failure': this['onFailureQuoteRequest'],
			'timeout': 10000, 
			'scope': this, 
			'argument': [tabClicked, isRecommendation]			
		});
	},

	'onSuccessQuoteRequest': function(o) {
		var quoteData = false;
		
		if (o && o.status == '200' && o.responseText && YAHOO.lang.trim(o.responseText) != '') {
			try { quoteData = eval("(" + YAHOO.lang.trim(o.responseText) + ")"); } catch(e) { }
		}

		if (quoteData) {
			var tabClicked = o.argument && o.argument[0] && o.argument[0] !== false ? o.argument[0] : false;		
			
			if (tabClicked) { /* this is for tabClicked param */
				this._planSelected = true;

				var oldPlanType = this._planType;
				var isRecommendation = o.argument[1];
				
				// first store new plan info
				this._plan = this._planCodeData[tabClicked]['code'];
				this._planField.value = this._plan;
				this._planType = tabClicked;
				this._planTypeField.value = this._planType; 
				this._planName = this._planCodeData[tabClicked]['name'];

				if (tabClicked != oldPlanType) {
					YAHOO.util.Dom.removeClass('current-plan-tab-cascade', oldPlanType + 'Plan');
				}
				else {
					for (var p in this._planCodeData) {
						if (p != tabClicked) YAHOO.util.Dom.removeClass('current-plan-tab-cascade', p + 'Plan');
					}
				}

				YAHOO.util.Dom.addClass('current-plan-tab-cascade', tabClicked + 'Plan');

				// then set up tab classes
				YAHOO.util.Dom.batch(YAHOO.util.Dom.getElementsByClassName('page-plan-tab', 'A'), function(el, arg) {
					if (YAHOO.util.Dom.hasClass(el, 'quote-calculator-tab-' + arg)) {
						YAHOO.util.Dom.removeClass(el, 'page-plan-tab-inactive');
						YAHOO.util.Dom.addClass(el, 'page-plan-tab-active');
					}
					else {
						YAHOO.util.Dom.removeClass(el, 'page-plan-tab-active');
						YAHOO.util.Dom.addClass(el, 'page-plan-tab-inactive');
					}
				}, tabClicked);

				this._c.YEARS_MILES_MAP = this._planData[tabClicked];

				if (isRecommendation) {
					this._yearsField.value = (quoteData.planMonths / 12);
					this._milesField.value = quoteData.planMileage;
				}

				this.updateYearsOptions();
				this.updateMilesOptions(!isRecommendation); // TODO >> !(YAHOO.util.Dom.hasClass(tabClicked, 'quote-calculator-tab-recommendation')));
			}
			else {
				this._yearsField.value = this._yearsSelect.options[this._yearsSelect.selectedIndex].value;
				this._milesField.value = this._milesSelect.options[this._milesSelect.selectedIndex].value;
			}

			for (var p in this._c.PLAN_CODES) {
				if (this._planCodeData[p]['code'] == quoteData.planCode) {
					this._quoteData[p] = quoteData;
				}
			}		
			
			this.updateRequestState(true);
			this.onQuoteCalculatorChanged();			
		}
		else {
			this.onFailureQuoteRequest(o);
		}
	},

	'onFailureQuoteRequest': function(o) {
		// roll back selections visible in years/miles widgets ??
		alert("There was a system error attempting to retrieve the quote you requested. Please refresh the page and try again.");
	},	
	
	'onQuoteCalculatorChanged': function() {
		this._doLock = false;

		var milesText = this._milesField.value;
		
		var years = parseInt(this._yearsField.value);
		var miles = parseInt(milesText);

		var milesIndex = 0;
		for (var i = 1, j = this._milesSelect.options.length; i < j; i ++) {
			if (this._milesSelect.options[i].value == milesText) {
				milesIndex = i;
				break;
			}
		}

		var endDate = new Date(this._startDate);
		endDate.setFullYear((endDate.getFullYear()) + years);

		// TODO: ### CHECK ON WHAT THE END DATE REPRESENTS ... IS IT "THROUGH" OR "UNTIL"????
		// IF THROUGH THEN NEED TO ADD TO END DATE AS PER BELOW
		//var displayEndDate = new Date();
		//displayEndDate.setTime(endDate.getTime());
		//if (displayEndDate.getMonth() == 11) {
		//	displayEndDate.setMonth(0);
		//	displayEndDate.setFullYear(displayEndDate.getFullYear() + 1);
		//}
		
		var deductible = this._c.DEDUCTIBLE_DEFAULT;
		var schedule = this._c.SCHEDULE_DEFAULT;

		var total = this._quoteData[this._planType]['totalCost'];
		var downpayment = this._quoteData[this._planType]['downPayment'];
		var monthly = this._quoteData[this._planType]['monthCost'];		
		
		var validYears = !(isNaN(years));
		var validMiles = !(isNaN(miles));
		var validRequest = !validYears || !validMiles ? false : true;

		var grid = YAHOO.util.Dom.get('quote-calculator-grid-buy-coverage'); /* 58px per x-tick, max is 406px; 35px per y-tick, max is 175px */
		YAHOO.util.Dom.setStyle(grid, 'width', '' + (years * 58) + 'px');
		YAHOO.util.Dom.setStyle(grid, 'height', '' + (milesIndex * 35) + 'px');

		var l1 = YAHOO.util.Dom.get('esp3-grid-buy-label');
		var b1 = YAHOO.util.Dom.get('quote-calculator-grid-buy-coverage');
		var b2 = YAHOO.util.Dom.get('esp3-grid-current-wrapper-block');
		if (b2) b2 = YAHOO.util.Dom.getFirstChild(b2);
		var b3 = YAHOO.util.Dom.get('esp3-grid-canvas');

		if (YAHOO.env.ua.ie > 0) {
			if (YAHOO.env.ua.ie < 7) {
				var ie6offset = 406 - (years * 58);
				YAHOO.util.Dom.setStyle(grid.parentNode.parentNode, 'marginLeft', '-' + ie6offset + 'px');
				YAHOO.util.Dom.setX(l1, YAHOO.util.Dom.getX(grid) + ie6offset);
			}
			else if (YAHOO.env.ua.ie < 8) {
				YAHOO.util.Dom.setStyle(grid.parentNode.parentNode, 'width', '' + ((years * 58) + 10) + 'px');
				//YAHOO.util.Dom.setStyle(grid.parentNode, 'left', '-' + (406 - (years * 58) + 5) + 'px');				
			}
		}
		
		if (b2) {
			var r1 = YAHOO.util.Dom.getRegion(l1);
			var labelHeight = r1.bottom - r1.top;
			var r2 = YAHOO.util.Dom.getRegion(b2);			
			var r3 = YAHOO.util.Dom.getRegion(grid);
			
			if (r2.top - r3.top <= labelHeight) {
				// too little room, move above colored grid hatching and make dark font color
				YAHOO.util.Dom.setY(l1, r3.top - (labelHeight + 5));
				YAHOO.util.Dom.setStyle(l1, 'color', '#333');
			}
			else {
				// center in non-overlapping colored grid hatching, make sure font is white
				YAHOO.util.Dom.setY(l1, r3.top + Math.floor((r2.top - r3.top - labelHeight) / 2));
				YAHOO.util.Dom.setStyle(l1, 'color', '#FFF');
			}

		}

		var ind = YAHOO.util.Dom.get('quote-calculator-buy-indicator');
		YAHOO.util.Dom.setStyle(ind, 'margin', '-' + ((milesIndex * 35) + 28) + 'px 0 0 ' + ((years * 58) - 11) + 'px');

		for (var i = 0; i < this._messagers.length; i ++) {
			var el = this._messagers[i];

			if (YAHOO.util.Dom.hasClass(el, this._c.DURATION_YEARS_CLASSFLAG)) {
				el.innerHTML = validYears ? years : this._c.UNAVAILABLE_MESSAGE;
			}
			else if (YAHOO.util.Dom.hasClass(el, this._c.DURATION_ENDDATE_CLASSFLAG)) {
				el.innerHTML = validYears ? this._c.MONTH_OPTIONS[endDate.getMonth()].substring(0, 3) + " " + endDate.getFullYear() : this._c.UNAVAILABLE_MESSAGE;
			}
			else if (YAHOO.util.Dom.hasClass(el, 'quote-calculator-plan-name')) {
				el.innerHTML = this._planName;
			}			
			else if (YAHOO.util.Dom.hasClass(el, this._c.DURATION_MILES_CLASSFLAG)) {
				el.innerHTML = validMiles ? miles.toLocaleString().replace(/\.\S*$/, '') : this._c.UNAVAILABLE_MESSAGE;
			}	
			else if (YAHOO.util.Dom.hasClass(el, this._c.DOWNPAYMENT_CLASSFLAG)) {
				el.innerHTML = validRequest ? formatNumber(downpayment.toFixed(2)) : this._c.UNAVAILABLE_MESSAGE;
			}			
			else if (YAHOO.util.Dom.hasClass(el, this._c.DEDUCTIBLE_CLASSFLAG)) {
				el.innerHTML = deductible;
			}
			else if (YAHOO.util.Dom.hasClass(el, this._c.SCHEDULE_CLASSFLAG)) {
				el.innerHTML = schedule - 1;
			}			
			else if (YAHOO.util.Dom.hasClass(el, this._c.SUBTOTAL_CLASSFLAG)) {
				
			}
			else if (YAHOO.util.Dom.hasClass(el, this._c.TOTAL_CLASSFLAG)) {
				el.innerHTML = validRequest ? formatNumber(total.toFixed(2)) : this._c.UNAVAILABLE_MESSAGE;
			}
			else if (YAHOO.util.Dom.hasClass(el, this._c.MONTHLY_CLASSFLAG)) {
				el.innerHTML = validRequest ? formatNumber(monthly.toFixed(2)) : this._c.UNAVAILABLE_MESSAGE;
			}
			else if (YAHOO.util.Dom.hasClass(el, this._c.REQUEST_VALID_CLASSFLAG)) {
				YAHOO.util.Dom.setStyle(el, "visibility", validRequest ? "visible" : "hidden");
			}
			else if (YAHOO.util.Dom.hasClass(el, this._c.REQUEST_INVALID_CLASSFLAG)) {
				YAHOO.util.Dom.setStyle(el, "visibility", validRequest ? "hidden" : "visible");
			}
			else if (YAHOO.util.Dom.hasClass(el, this._c.REQUEST_PROCESSING_CLASSFLAG)) {
				if (validRequest) {
					YAHOO.util.Dom.setStyle(el, "visibility", "hidden");
				}
			}
			else if (YAHOO.util.Dom.hasClass(el, this._c.CONTINUE_CLASSFLAG)) {
				if (validRequest) {
					YAHOO.util.Dom.removeClass(el, 'disabled');
				}
				else {
					YAHOO.util.Dom.addClass(el, 'disabled');
				}
			}
			else if (YAHOO.util.Dom.hasClass(el, "quote-calculator-tab")) {
				if (!YAHOO.util.Dom.hasClass(el, "quote-calculator-tab-" + this._planType)) {
					var tabPlan = (el.className.match(/quote-calculator-tab-(prem|ex|base|ptrn)/))[1];

					var tabAvailable = (tabPlan in this._planData) && YAHOO.lang.isObject(this._planData[tabPlan]) && (this._yearsField.value in this._planData[tabPlan]) && (this._milesField.value in this._planData[tabPlan][this._yearsField.value]) ? true : false;

					if (tabAvailable || YAHOO.lang.isValue(this._recommendationData[tabPlan])) {
						YAHOO.util.Dom.removeClass(el, "quote-calculator-tab-unavailable");

						if (tabAvailable) {
							YAHOO.util.Dom.removeClass(el, "quote-calculator-tab-recommendation");
						}
						else {
							YAHOO.util.Dom.addClass(el, "quote-calculator-tab-recommendation");
						}
					}
					else {
						YAHOO.util.Dom.addClass(el, "quote-calculator-tab-unavailable");
					}
				}
				else {
					YAHOO.util.Dom.removeClass(el, 'quote-calculator-tab-unavailable');
					YAHOO.util.Dom.removeClass(el, "quote-calculator-tab-recommendation");
				}
			}
			else if (YAHOO.util.Dom.hasClass(el, this._c.REQUEST_SHIM_CLASSFLAG)) {
				var anchor = YAHOO.util.Dom.get(el.id.replace(/-shim$/, ''));

				if (anchor && YAHOO.util.Dom.getStyle(el, "width") == "0px") {
					// first set up initial styles if not yet done
					var region = YAHOO.util.Dom.getRegion(anchor);
					
					YAHOO.util.Dom.setStyle(el, "width", '' + (region.right - region.left) + 'px');
					YAHOO.util.Dom.setStyle(el, "height", '' + (region.bottom - region.top + 20) + 'px');
					YAHOO.util.Dom.setX(el, YAHOO.util.Dom.getX(anchor));
					YAHOO.util.Dom.setY(el, YAHOO.util.Dom.getY(anchor) - 10);
				}
				
				if (YAHOO.util.Dom.hasClass(el, this._c.REQUEST_INVALID_SHIM_CLASSFLAG)) {
					YAHOO.util.Dom.setStyle(el, "display", validRequest ? "none" : "block");
				}
				else if (YAHOO.util.Dom.hasClass(el, this._c.REQUEST_PROCESSING_SHIM_CLASSFLAG)) {
					if (validRequest) {
						YAHOO.util.Dom.setStyle(el, "display", "none");
					}
				}
			}
		}
		
		YAHOO.util.Dom.batch(YAHOO.util.Dom.getElementsByClassName('page-plan-tab', 'A', 'main-box'), function(el) { YAHOO.util.Dom.removeClass(el, 'page-plan-tab-processing'); });
	}
};

var ESP = {};
ESP.widget = {};

ESP.widget.ContainerEffect = {};

ESP.widget.ContainerEffect.SLIDEY = function(D, F){
	var A = YAHOO.widget.ContainerEffect,
		B = YAHOO.util.Dom;

	var G = YAHOO.util.Easing,
		R = YAHOO.util.Dom.getRegion(D.element),
		I = { 'attributes': { 'height': { 'from': 0, 'to': (R.bottom - R.top) }}, 'duration': F, 'method': G.easeIn },
		E = { 'attributes': { 'height': { 'to': 0 }}, 'duration': F, 'method': G.easeOut },
		H = new A(D, I, E, D.element);
	
	H['handleUnderlayStart'] = function() {};
	
	H['handleUnderlayComplete'] = function() {};
	
	H['handleStartAnimateIn'] = function(K, J, L) {
		B.addClass(L.overlay.element, "hide-select");
		
		if (!L.overlay.underlay) {
			L.overlay.cfg.refireEvent("underlay");
		}
		
		L.handleUnderlayStart();
		
		B.setStyle(L.overlay.element, "height", "0px");
		B.setStyle(L.overlay.element, "visibility", "visible");
	};

	H['handleCompleteAnimateIn'] = function(K, J, L) {
		B.removeClass(L.overlay.element, "hide-select");
		
		L.handleUnderlayComplete();
		
		L.overlay.cfg.refireEvent("iframe");
		L.animateInCompleteEvent.fire();
	};
	
	H['handleStartAnimateOut'] = function(K, J, L) {
		B.addClass(L.overlay.element, "hide-select");
		L.handleUnderlayStart();
	};
	
	H['handleCompleteAnimateOut'] = function(K, J, L) {
		B.setStyle(L.overlay.element, "visibility", "hidden");
		B.setStyle(L.overlay.element, "height", "auto");
		
		L.animateOutCompleteEvent.fire();
	};
	
	H.init();
	
	return H;
};

ESP.widget.Tooltip = function(el, config) {
	ESP.widget.Tooltip.superclass.constructor.call(this, el, config);
};

if (YAHOO.widget.Tooltip) {
	YAHOO.extend(ESP.widget.Tooltip, YAHOO.widget.Tooltip);
}

ESP.widget.Tooltip.TAIL_TOP_LEFT = 'tl';

ESP.widget.Tooltip.TAIL_TOP_MIDDLE = 'tm';

ESP.widget.Tooltip.TAIL_TOP_RIGHT = 'tr';

ESP.widget.Tooltip.TAIL_BOTTOM_LEFT = 'bl';

ESP.widget.Tooltip.TAIL_BOTTOM_MIDDLE = 'bm';

ESP.widget.Tooltip.TAIL_BOTTOM_RIGHT = 'br';

ESP.widget.Tooltip.TAIL_OPTIONS = [
	ESP.widget.Tooltip.TAIL_TOP_LEFT, 
	ESP.widget.Tooltip.TAIL_TOP_MIDDLE,
	ESP.widget.Tooltip.TAIL_TOP_RIGHT,
	ESP.widget.Tooltip.TAIL_BOTTOM_LEFT,
	ESP.widget.Tooltip.TAIL_BOTTOM_MIDDLE,
	ESP.widget.Tooltip.TAIL_BOTTOM_RIGHT
];

ESP.widget.Tooltip.TOOLTIP_CSS = 'owner-tt';

ESP.widget.Tooltip.TAIL_HTML = '<div class="tooltip-tri"><img src="/Storage/Owner2/assets/img/s.gif" border="0" alt="" /></div>';

ESP.widget.Tooltip.HEADER_HTML = '<div class="box-inset box-body-white box-inset-lined box-inset-lined-white"><div class="box-cap box-cap-t"><div class="box-cap-l"><div class="box-cap-m"><div class="box-cap-r"></div></div></div></div></div>';

ESP.widget.Tooltip.FOOTER_HTML = '<div class="box-inset box-body-white box-inset-lined box-inset-lined-white"><div class="box-cap box-cap-b"><div class="box-cap-l"><div class="box-cap-m"><div class="box-cap-r"></div></div></div></div></div>';

ESP.widget.Tooltip.BODY_HTML = '<div class="box-module box-inset-lined-white"><div class="box-canvas"><div class="box-body-frame"><div class="box-body"><div class="box-body-content">{text}</div></div></div></div>';

ESP.widget.Tooltip.prototype.init = function(el, userConfig) {
	ESP.widget.Tooltip.superclass.init.call(this, el); /* defer config */

	this.beforeInitEvent.fire(ESP.widget.Tooltip);

	config = YAHOO.lang.merge( { 'autodismissdelay': 100000 }, userConfig || {});
	this.cfg.applyConfig(config, true);
	
	this.setHeader(ESP.widget.Tooltip.TAIL_HTML + ESP.widget.Tooltip.HEADER_HTML);
	this.setFooter(ESP.widget.Tooltip.FOOTER_HTML + ESP.widget.Tooltip.TAIL_HTML);
	
	YAHOO.util.Dom.addClass(this.element, ESP.widget.Tooltip.TOOLTIP_CSS);
	
	this.initEvent.fire(ESP.widget.Tooltip);
};

ESP.widget.Tooltip.prototype.initDefaultConfig = function() {
	ESP.widget.Tooltip.superclass.initDefaultConfig.call(this);
	
	this.cfg.addProperty('tail', { 'handler': this.configTail, 'value': ESP.widget.Tooltip.TAIL_TOP_LEFT, 'validator': function(val) { return ESP.widget.Tooltip.TAIL_OPTIONS.indexOf(val) > -1; }, 'suppressEvent': true });
	this.cfg.addProperty('offsetX', { 'handler': this.configOffsetX, 'validator': this.cfg.checkNumber, 'suppressEvent': true, 'supercedes': ['x'] });
	this.cfg.addProperty('offsetY', { 'handler': this.configOffsetY, 'validator': this.cfg.checkNumber, 'suppressEvent': true, 'supercedes': ['y'] });
	this.cfg.addProperty('contextCentered', { 'handler': this.configContextCentered, 'validator': this.cfg.checkBoolean, 'suppressEvent': true, 'supercedes': ['xy'] });
};

ESP.widget.Tooltip.prototype.configTail = function(type, args, obj) {
	var val = args[0];
	
	YAHOO.util.Dom.addClass(this.element, ESP.widget.Tooltip.TOOLTIP_CSS + '-' + val.substring(0, 1));
	YAHOO.util.Dom.addClass(this.element, ESP.widget.Tooltip.TOOLTIP_CSS + '-' + val.substring(1));
	YAHOO.util.Dom.addClass(this.element, ESP.widget.Tooltip.TOOLTIP_CSS + '-' + val);
};

ESP.widget.Tooltip.prototype.configOffsetX = function(type, args, obj) {	
}

ESP.widget.Tooltip.prototype.configOffsetY = function(type, args, obj) {
}

ESP.widget.Tooltip.prototype.configContextCentered = function(type, args, obj) {
}

ESP.widget.Tooltip.prototype.configText = function(type, args, obj) {
	var val = args[0] || '';

	this.setBody(YAHOO.lang.substitute(ESP.widget.Tooltip.BODY_HTML, { 'text': val }));
};

ESP.widget.Tooltip.prototype.show = function() {
	var ctxRegion = YAHOO.util.Dom.getRegion(this.cfg.getProperty('context')[0]), 
		tailDown = this.cfg.getProperty('y') < ctxRegion.top ? true : false;
	
	YAHOO.util.Dom.replaceClass(this.element, ESP.widget.Tooltip.TOOLTIP_CSS + '-' + (tailDown ? 't' : 'b'), ESP.widget.Tooltip.TOOLTIP_CSS + '-' + (tailDown ? 'b' : 't'));
	
	if (this.cfg.getProperty('contextCentered')) {
		var elRegion = YAHOO.util.Dom.getRegion(this.element),
			ctxWidth = ctxRegion.right - ctxRegion.left,
			elWidth = elRegion.right - elRegion.left;
		
		YAHOO.util.Dom.setX(this.element, ctxRegion.left + ((ctxWidth - elWidth) / 2));
		YAHOO.util.Dom.setY(this.element, tailDown ? ctxRegion.top - (elRegion.bottom - elRegion.top) + 9 : ctxRegion.bottom - 11);
	}
	else {
		if (this.cfg.getProperty('offsetX')) YAHOO.util.Dom.setX(this.element, YAHOO.util.Dom.getX(this.element) + this.cfg.getProperty('offsetX'));
		if (this.cfg.getProperty('offsetY')) YAHOO.util.Dom.setY(this.element, YAHOO.util.Dom.getY(this.element) + this.cfg.getProperty('offsetY'));
	}
	
	ESP.widget.Tooltip.superclass.show.call(this);
};

ESP.widget.Tooltip.prototype.toString = function() {
	return 'ESP Tooltip ' + this.id;
};

