ASC.apply(Page,{
 
	//common parameters
	estimatedPayment:null,
	ccode: null,
    llp:null,
    paymentEstimator:null,
    isModelsPage:false,
    isSummaryPage:false,
    alreadyZipCode:true,
    initPaymentEstimator: function(  ){
    	
    	var pmtCookie = ASC.Chrysler.Cookies.getBmoPaymentEstimator();	  
    	
	    if( pmtCookie.monthlyPmt ){     	 
	    	var pmtParams={
	    		monthlyPayment: pmtCookie.monthlyPmt,
	    		term: pmtCookie.pmtTerm,
	    		apr: pmtCookie.pmtAPR
	    	};   
			this.estimatedPayment = new ASC.Chrysler.BMO.EstimatedPayment( pmtParams, {renderTo:"estimated_payment"} );
		}else{
			this.estimatedPayment = new ASC.Chrysler.BMO.EstimatedPayment( null, {renderTo:"estimated_payment"} );
		}
    },

	hideWindow: function(windowToHide)
	{
		if(windowToHide==='compare'){
			Page.allTrims.destroyWindow();
		}else if(windowToHide==='features'){
			Page.viewAllMakeTrims.hide();
		}
	},
    
    toggleWhyEnterZip: function () {
    	var whyEl = ASC.getEl('whyenterzip_explination');
    	if (!whyEl || !whyEl.dom) { return; }
    	
    	if(whyEl.dom.style.display == 'none'){
    		ASC.Chrysler.trackLinkMetrics('info_content','info_zip');
    	}
    	
    	whyEl.setVisibilityMode(Ext.Element.DISPLAY);
    	whyEl.toggle();    	
    },
  
	showAllMakeTrims: function()
	{
		this.viewAllMakeTrims.show(this.modelYearCode);
	},

	viewIncentives: function( hasIncentives )
	{
		if( hasIncentives ){
			document.getElementById("incentives_list").style.display = "block";
			document.getElementById("combined").innerHTML='<td class="left_item"><span class = "combinedIncentives">' + ASC.message("bmo_combined")+ '</span><a href="javascript:Page.closeIncentives('+ hasIncentives +');"><img src="' + ASC.cfg.getImgLocalePath() + '/bmo/bodycontainer_icon_09.gif" /></a><a href="javascript:Page.closeIncentives('+ hasIncentives +');" class="closeIncentives"> Close</a></td>';
		}
		return;
	},
	
	closeIncentives: function( hasIncentives ){
		document.getElementById("incentives_list").style.display = "none";
		document.getElementById("combined").innerHTML='<td class="left_item"><span class = "combinedIncentives">' + ASC.message("bmo_combined")+ '</span><a href="javascript:Page.viewIncentives('+ hasIncentives +');" name="&lpos=info_content&lid=info_incentives"><img src="' + ASC.cfg.getImgLocalePath() + '/bmo/bodycontainer_icon_09.gif" /></a></td>';
	},
	
	zipEntered: function()
	{
		ASC.getEl('zipCodeNotEntered').dom.style.display="none";
		ASC.getEl('currentZipCode').dom.innerHTML = ASC.Chrysler.Cookies.getZipCode();
		ASC.getEl('zipCodeEntered').dom.style.display="block";	
	},
	
	editZipCode: function()
	{
		ASC.getEl('zipCodeNotEntered').dom.style.display="block";
		ASC.getEl('zipCodeEntered').dom.style.display="none";			
	},
	calculateEmployeePricing:function()
	{
		var zipCode = ASC.Chrysler.Cookies.getZipCode();
		if(zipCode)
		{
			var url = window.location.href;
			url = this.parseUrl(url);
			if(Page.alreadyZipCode)
			{
				window.location.href = ASC.cfg.getContextPath() +"/bmo/models.do?redirectUrl="+url+"&isCalculate=true"
			}
			else
			{
				window.location.href = ASC.cfg.getContextPath() +"/bmo/models.do?redirectUrl="+url+"&isCalculate=true&zipCode="+zipCode;
			}
		}
	},
	parseUrl:function(url)
	{
		var endIndex = url.lastIndexOf("/");
		var interrogationIndex = url.indexOf("?");
		var subUrl = '';
		if(interrogationIndex>endIndex)
		{
			subUrl = url.substring(endIndex+1,interrogationIndex);
		}
		else
		{
			subUrl = url.substring(endIndex+1);
		}
		return subUrl;
	}
	,
	updateIncentives: function( response ){
		var incentives = response.data;
		Page.incentives.update(incentives, this.incentivesCategory);
		//summary page
		if( Page.incentivesList ){
			Page.incentivesList.update(incentives, this.incentivesCategory);
		}
		var incentivesTotal = 0;
		for( i=0; i<incentives.length;i++ ){
			if( incentives[i].incentiveType != 'SCB' ){
				incentivesTotal += parseFloat(incentives[i].programCashValue);
			}
		}	
		this.incentivesTotal = -1 * incentivesTotal;
		Page.netTotal = Page.configMSRP + this.incentivesTotal + this.employeeDiscount;	
	
		document.getElementById("total_msrp").innerHTML = ASC.util.formatCurrency(Page.netTotal, 0);
		
		if( Page.incentivesList ){
			document.getElementById("netprice_item").innerHTML = ASC.util.formatCurrency(Page.netTotal, 0);
		}
	},
	
	getAQuote:function(ccode, llp, stateString)
	{
		var bmo = ASC.apply(ASC.Chrysler.Cookies.getBmo(), {
		    cCode: ASC.getEl('ccode').getValue(),
		    llpCode: ASC.getEl('llp').getValue(),
		    stateString: ASC.getEl('configStateString').getValue()
		});

		var zipCode = ASC.Chrysler.Cookies.getZipCode();
		if(zipCode==null){
			zipCode='';
		}
		ASC.Chrysler.Cookies.setBmo(bmo);
				
		var modelDesc = Page.modelDesc.replace(/ /g,'_').replace(/&/g,'').toLowerCase().replace('__','_');
		if (Page.integrVeh) {
			modelDesc = Page.integrVeh.model; 
		}
		window.location.href = Page.bridgeUrl + '?target=gaq&vehicle=' + modelDesc + '&year=' + Page.yearDesc + '&zipcode=' + zipCode;
	},
	
	applyForCredit:function()
	{
		var zipCode = ASC.Chrysler.Cookies.getZipCode();
		var dealerCode = ASC.Chrysler.Cookies.getPreferredDealer();
		var ccode = Page.ccode != null ? Page.ccode : '';
		var llp = Page.llp != null ? Page.llp : '';
			
		if(zipCode==null){
			zipCode = '';
		}
		
		if(dealerCode==null){
			dealerCode=='';
		}
		
		var url = ASC.cfg.getCFCreditAppUrl() + '?cobrand='+Page.brand.toLowerCase()+'&ccode='+ccode+'&llp='+llp+'&dealerId='+dealerCode+'&vehicleType=N&zipCode='+zipCode;
		window.open(url, 'chryslerFinancialWindow');						
	},
	
	displayPayment: function(){	
		if(!this.paymentEstimator){			
			this.paymentEstimator = new ASC.Chrysler.BMO.PaymentEstimator();			
			this.paymentEstimator.on({
				beforehide: {
					fn: Page.updateEstimatedPayment,
					scope: Page
				}
			});
			
			this.paymentEstimator.on({
				beforeShow: {
					fn: Page.setPaymentEstParams,
					scope: Page
				}
			});
						
		}else{
			this.paymentEstimator.updateParams(this.setPaymentEstParams);
		}			
		this.paymentEstimator.show();
		
		//Make sure the Payment Estimator does not open on top of the Vehicle tally
		//it should also be completely visble when the view port is large enough to accomodate the component
		this.paymentEstimator.center();
		var pos = this.paymentEstimator.getPosition();
		this.paymentEstimator.setPagePosition(pos[0] - 35, pos[1]);
		
	},

	getPayment: function () {
		if (!this.paymentEstimator) {
			return;
		}
		
		var payment = this.paymentEstimator.getPayment();
		
		
		return payment;
	},
	
	setPaymentEstParams: function () {
		if (!this.paymentEstimator) {
			return;
		}
		
		var pmtCookie = ASC.Chrysler.Cookies.getBmoPaymentEstimator();

		var params = {
			msrp: this.configMSRP,
			zipCode: ASC.getEl("zip_code_text").getValue(),
			cCode: this.ccode,
			lowerLevelPackageCode: this.llp,
			apr: pmtCookie.pmtAPR,
			term: pmtCookie.pmtTerm,
			employeeDiscount: this.employeeDiscount
		};
		return params;
	},
	
	
	setZipCode: function( vehicle, year  ){
		var zipCode = ASC.getEl("zip_code_text").getValue();
		//validate zip code
		
		if( Ext.isEmpty( zipCode, false ) ){
			return;
		}
		
		if( !ASC.util.isZip( zipCode ) ){
			document.getElementById("zip_code_error").style.display = 'block';
			return;
		}
		
		//if no change in zip then no need to validate
		if (zipCode==ASC.Chrysler.Cookies.getZipCode()) {
			Page.zipEntered();
			return;
		}
		
		Page.validateZip('zip_code_text', vehicle, year);
	},
	
	validateZip:function(zipCodeElementId, vehicle, year){
		var zipCode=ASC.getEl(zipCodeElementId).getValue();
		this.ajax.sendRequest('validateZipCode', {
		params: {
    			zipCode:zipCode,  
    			elementId:zipCodeElementId,
    			vehicle:vehicle,
    			year:year,
    			updatePromo:'true'
			}
		});
	},
	
	
	
	gridDisplayInfo: function( index ){
		document.getElementById("extended_desc_icon_"+index).href="javascript:Page.gridCloseInfo('"+index+"')";
		document.getElementById("extended_desc_close_"+index).className = "extdesc_closebtn_display a-xgrid3-extOptionClose";
		document.getElementById("extended_desc_text_"+index).style.display = "block";
	},

	gridCloseInfo: function( index ){
		document.getElementById("extended_desc_icon_"+index).href="javascript:Page.gridDisplayInfo('"+index+"')";
		document.getElementById("extended_desc_close_"+index).className = "extdesc_closebtn_hide";
		document.getElementById("extended_desc_text_"+index).style.display = "none";
	},
	
	updateSelectedOptions: function( configResponse )
	{	
		document.getElementById("view_my_selections").innerHTML = '<a class="right_package_underline" href="javascript:Page.closeMySelections();ASC.Chrysler.trackLinkMetrics(\'info_content\',\'close_show_me\');">Close</a>';
		document.getElementById("my_selected_options").style.display="block";
		if(this.selectedOptions == null){
			this.selectedOptions = new ASC.Chrysler.BMO.SelectedOptions({renderTo:"my_selected_options"});
		}
		this.selectedOptions.update(configResponse.options);
	},
	
	viewMySelections: function ()
	{
		this.ajax.sendRequest('SELECTED_OPTIONS', {
			params: {
			}
		});
		
		this.viewSelections = true;
		
	},
	
	closeMySelections: function()
	{
		document.getElementById("my_selected_options").style.display="none";
		document.getElementById("view_my_selections").innerHTML = '<a class="right_package_underline" href="javascript:Page.viewMySelections();">Show me</a>';
		this.viewSelections = false;
	},
	
	
	showDisclaimer: function ()
	{
		var disclaimer = new ASC.Chrysler.BMO.Disclaimer(ASC.cfg.getContextPath());
		disclaimer.show();
	},
	
	showImage: function (imgName, width, height) {
		var imageName = imgName == '' ? 'blank.jpg' : imgName;
		this.expandImage.show(imageName, width, height);
	},
	
	updateEstimatedPayment: function () {
		
		var pmtCookie = ASC.Chrysler.Cookies.getBmoPaymentEstimator();
		var payment = null;
		
		try {
			payment = this.getPayment();
		} catch (ex) {
			//Most likely cause of this error is user does not have flash installed
			pmtCookie.monthlyPmt = -1;
		}
		
		
		if (payment != null && payment.monthlyPayment > 0) {
			
			pmtCookie.monthlyPmt = payment.monthlyPayment;
			pmtCookie.pmtTerm = payment.term;
			pmtCookie.pmtAPR = payment.apr;
			ASC.Chrysler.Cookies.setBmoPaymentEstimatorState( pmtCookie );	
			this.estimatedPayment.update(payment);
			if (payment.zipCode != ASC.Chrysler.Cookies.getZipCode()) {
				this.ajax.sendRequest('validateZipCode', {
					params: {
		    			zipCode:payment.zipCode,  
		    			elementId:'zip_code_text',
		    			vehicle:this.integrVehModel,
		    			year:this.integrVehYear,
		    			updatePromo:'true'
					}
				});
			}
		}
		this.paymentEstimator.destroy();
		this.paymentEstimator=null;
	},
	
	resetPaymentEstimations: function(  ){
		Page.estimatedPayment.update(null);
		var pmtCookie = ASC.Chrysler.Cookies.getBmoPaymentEstimator();
		pmtCookie.monthlyPmt = null;
		pmtCookie.pmtTerm = null;
		pmtCookie.pmtAPR = null;
		ASC.Chrysler.Cookies.setBmoPaymentEstimatorState( pmtCookie );
		if (Page.paymentEstimator) {
			Page.paymentEstimator.destroy();
		}
		Page.paymentEstimator=null;
	},
	
	changeVehicle: function(year) {
		var app="bmo";
		var target="selector";
		var params="?target=" + target + "&app="+app + "&year=" + year;
		var fullUrl=ASC.cfg.getBridgeUrl() + params;
		window.location.href=fullUrl;
	},
	
	postInitAjaxEngine:function() {
		var ae=this.ajax;
		var contextPath = ASC.cfg.getContextPath();

		ae.registerRequest('SELECTED_OPTIONS', contextPath + '/bmo/selectedOptions.ajax');
		ae.registerAjaxObject('selectedOptions', {
				ajaxUpdateJSON: function (response, ioArgs) {
						Page.updateSelectedOptions(response.data);						
				}
		});
		
		ae.registerRequest('ZIPCODE_UPDATE_DATA', contextPath + '/bmo/combinedIncentives.ajax');
		ae.registerAjaxObject('updateIncentivesZip', {
				ajaxUpdateJSON: function (response, ioArgs) {
					if(ASC.Chrysler.Cookies.getZipCode() !== null){
						Page.zipEntered();
					}
					Page.updateIncentives(response);				
				}
		});
	
		ae.registerAjaxObject('promoUpdate', {
			ajaxUpdateJSON: function (response, ioArgs) {
				var el=Ext.get('promo_content_div');				
				el.update(response.data,null,null);
			}
		});
		
		ae.registerRequest('UPDATE_VEHICLE_TALLY', contextPath + '/bmo/updateVehicleTally.ajax');
		ae.registerAjaxObject('updateVehicleTally',{
			ajaxUpdateJSON: function( response, ioArgs ){
				if(ASC.Chrysler.Cookies.getZipCode() !== null){
					Page.zipEntered();
				}
				if(response.data.isTrimSelector){
					var selComb = response.data.tallyData;
					Page.updateVehicleTallyFromTrimSelector(selComb);
				}else{
					var pricingSummary = response.data.configResponse.pricingSummary;
					Page.updateVehicleTally(pricingSummary);
				}
				//update model list if on models page
				if( Page.isModelsPage ){
					Page.combinations = response.data.combinations;
					var modelList = Page.getModelList();
					Page.currentModelList = modelList;
					var selModelIndex = 1;
					for( i=0; i<modelList.length;i++ ){
						if( modelList[i].CCode == Page.ccode && modelList[i].lowerLevelPackageCode == Page.llp ){
							selModelIndex = i+1;
						}
					} 
					Page.modelList.update(modelList, selModelIndex);
				}
			}
		});
		
		this.zipCodeValidator = new ASC.Chrysler.ZipValidator({ajax:this.ajax});
		ASC.apply(this.zipCodeValidator,{
			handleZipValidation: function (response, ioArgs)
			{			
				var isValidZipCode=(response.data!='false');
				if (isValidZipCode) {				
					document.getElementById("zip_code_error").style.display = 'none';
					var zipCode=ioArgs.options.params.zipCode;
					if( ASC.getEl("zip_code_text").getValue() != zipCode ){
						ASC.getEl("zip_code_text").setValue(zipCode);
					}
					ASC.Chrysler.Cookies.setZipCode(zipCode);
					Page.alreadyZipCode = false;
					this.ajax.sendRequest('UPDATE_VEHICLE_TALLY',{
						params:{}
					});
				} else {
					document.getElementById("zip_code_error").style.display = 'block';
				}
			},
			handleOrigZipValidation: function (response, ioArgs)
			{
				document.getElementById("zip_code_error").style.display = 'none';
				var zipCode=ioArgs.options.params.zipCode;
				ASC.Chrysler.Cookies.setZipCode(zipCode);
				this.ajax.sendRequest('ZIPCODE_UPDATE_DATA', {
					params:{
						incentivesCategory: Page.incentivesCategory
					}
				});
			}
		});	
	},
	
	/**common function to colors, powertrain and options page
	updates the tally when an option is selected*/
	updateVehicleTally: function( pricingSummary ){

		var employeeDiscount = '';
		var employeeDiscountDesc = '';
		var employeeDiscountValue = 0;
						
		if (typeof pricingSummary.employeeDiscount != "undefined" && typeof pricingSummary.employeeDiscount.msrp != "undefined") {
			employeeDiscountValue = pricingSummary.employeeDiscount.msrp;
			employeeDiscount = ASC.util.formatCurrency(pricingSummary.employeeDiscount.msrp, 0);
			employeeDiscountDesc = pricingSummary.employeeDiscount.name + ' *****';
			//alert(employeeDiscountDesc + ' ' + employeeDiscountValue);
		}
		this.employeeDiscount = employeeDiscountValue;
		//this.netTotal = pricingSummary.total.msrp + this.incentivesTotal + employeeDiscountValue;
		this.configMSRP = pricingSummary.total.msrp;
		
		ASC.getEl("base_msrp").setValue(ASC.util.formatCurrency(pricingSummary.base.msrp, 0));
		ASC.getEl("selected_opt").setValue(ASC.util.formatCurrency(pricingSummary.selectedOptions.msrp,0));
		ASC.getEl("destination").setValue(ASC.util.formatCurrency(pricingSummary.destination,0));
		ASC.getEl("configMSRP").setValue(ASC.util.formatCurrency(this.configMSRP, 0));
		
		ASC.getEl("employee_discount_desc").dom.innerHTML = employeeDiscountDesc;
		ASC.getEl("employee_discount").dom.innerHTML = employeeDiscount;

		if(Page.isSummaryPage){
			ASC.getEl('summary_destCharge').setValue(ASC.util.formatCurrency(pricingSummary.destination,0));
			var employeePricingObj = ASC.getEl('summary_employeePricing');
			if( typeof pricingSummary.employeeDiscount != "undefined" && typeof pricingSummary.employeeDiscount.msrp != "undefined"){
				employeePricingObj.dom.innerHTML = employeeDiscount;
				ASC.getEl("summary_employeePricingDesc").dom.innerHTML = employeeDiscountDesc;
				ASC.getEl('summary_employeePricing_div').setDisplayed('block');
			}else{
				ASC.getEl('summary_employeePricing_div').setDisplayed('none');
			}
		}
		//update incentives based on the selection - due to incentives restrictions
		this.ajax.sendRequest('ZIPCODE_UPDATE_DATA', {
			params:{
				incentivesCategory: this.incentivesCategory
			}
		});
	},
	
	updateVehicleTallyFromTrimSelector: function( pricingSummary ){


		var employeeDiscount = '';
		var employeeDiscountDesc = '';
		var employeeDiscountValue = 0;
		
		this.configMSRP = pricingSummary.msrpAsConfigured;
		
		ASC.getEl("base_msrp").setValue(ASC.util.formatCurrency(pricingSummary.MSRP, 0));
		ASC.getEl("selected_opt").setValue(ASC.util.formatCurrency(pricingSummary.forcedOptionsValue,0));
		ASC.getEl("destination").setValue(ASC.util.formatCurrency(pricingSummary.destination,0));
		ASC.getEl("configMSRP").setValue(ASC.util.formatCurrency(this.configMSRP, 0));
		//ASC.getEl("total_msrp").setValue(ASC.util.formatCurrency(this.netTotal, 0));

		if(typeof pricingSummary.employeeDiscount != "undefined" && typeof pricingSummary.employeeDiscount.msrp != "undefined"){
			ASC.getEl("employee_discount").dom.innerHTML = ASC.util.formatCurrency(pricingSummary.employeeDiscount.msrp,0);
			ASC.getEl("employee_discount_desc").dom.innerHTML = pricingSummary.employeeDiscount.name;
			this.employeeDiscount = pricingSummary.employeeDiscount.msrp;
		}else{
			ASC.getEl("employee_discount").dom.innerHTML = "";
			ASC.getEl("employee_discount_desc").dom.innerHTML = "";
			this.employeeDiscount = 0;
		}
		
		//update incentives based on the selection - due to incentives restrictions
		this.ajax.sendRequest('ZIPCODE_UPDATE_DATA', {
			params:{
				incentivesCategory: this.incentivesCategory
			}
		});
	},
	
	selectIncentiveCategory: function( incentivesCategory ){
		this.incentivesCategory = incentivesCategory;
		this.ajax.sendRequest('ZIPCODE_UPDATE_DATA', {
			params:{
				incentivesCategory: this.incentivesCategory
			}
		});
		if(this.incentivesCategory == 'L'){
			ASC.Chrysler.trackLinkMetrics('content', 'lease_offer');
			document.getElementById('estimated_payment').style.display='none';
		}else{
			ASC.Chrysler.trackLinkMetrics('content', 'purchase_offer');
			document.getElementById('estimated_payment').style.display='block';
		}
	},
	
	findVehicleInInventory: function(modelYearId){
		ASC.Chrysler.trackLinkMetrics("content","Search_Inventory");
		window.location = ASC.cfg.getContextPath() + '/sni/inventorySearch.do?modelYearCode='+ modelYearId +'&ccode='+ this.ccode +'&lowLevelPackageCode='+ this.llp +'&driveTypeId='+ this.dindex +'&cabTypeId='+ this.cindex +'&vehTypeId=' + this.tindex + '&cabBoxTypeId='+this.cbindex;
	}
});
