/*
 * ASC.Chrysler.CPOV.VehicleList 
 * */
ASC.namespace('ASC.Chrysler.CPOV.VehicleList');
ASC.Chrysler.CPOV.VehicleList = ASC.extend(Ext.util.Observable,{
	renderTo:null,
	vehicleData:null,
	constructor: function (vehicleData,cfg)
	{
		ASC.Chrysler.CPOV.VehicleList.superclass.constructor.apply(this);
		ASC.apply(this, cfg);		
		this.addEvents({"render":true});
		this.vehicleData = vehicleData;
		this.initTemplates();
		this.initPageBar();
		this.render();
		if(this.renderToPageBar)
		{
			this.renderPageBar(this.pageIndex, this.pageSize, this.pageCount)
		}
	},
	render:function()
	{
		this.vehicleTpl.overwrite(this.renderTo, this.vehicleData);		
		this.fireEvent("render");
	},
	
	renderPageBar: function(pageIndex,pageSize,totalPageCount)
	{
		this.pageIndex = pageIndex;
		//this.pageCount = pageCount;
		//var pageCount = totalPageCount/pageSize ==0?parseInt(totalPageCount/pageSize):parseInt(totalPageCount/pageSize)+1;
		
		var pageCount = totalPageCount/pageSize ==0?parseInt(totalPageCount/pageSize):parseInt(totalPageCount/pageSize)+1;
		if (totalPageCount == pageSize)
		{
			pageCount = 1;
		}
		this.pageBarTpl.overwrite(this.renderToPageBar, {pageIndex: pageIndex,pageCount: new Array(pageCount)});
	},
	initTemplates: function ()
	{
		//alert(this.vehicleData.data.invertotyVehicles);
		this.vehicleTpl = new Ext.XTemplate(
			 '<tpl if="values.length &lt; 1">',
	            '<div class="noMatchdiv">',
				'<div class="noMatchdiv_car"><img src="{[this.getImgLocalePath()]}/cpov/brand_promo.jpg"/></div>',
				'<div class="noMatchdiv_disc">',
					'<div class="noMatchdiv_disc_top"><img src="{[this.getImgLocalePath()]}/cpov/no_match.gif"/></div>',
					'<div class="noMatchdiv_disc_text">{[this.translate("nomatchingvehicles")]}</div>',
					'<div class="noMatchdiv_disc_icon"><a href="vehicleSearch.do?zipCode={[Page.zipCode]}" name="&lpos=content&lid=change_your_search"><img src="{[this.getImgLocalePath()]}/cpov/change_search.gif"/></a></div>',
					'<div class="noMatchdiv_disc_text">{[this.translate("alternatively")]}</div>',
					'<div class="noMatchdiv_disc_icon"><a href="javascript:Page.searchEntireCertified();" name="&lpos=content&lid=locate_a_dealer"><img src="{[this.getImgLocalePath()]}/cpov/locate_dealer.gif"/></a></div>',
				'</div>',
				'</div>',
	            '</tpl>',
				'<tpl for=".">',
				'<form id="vehiclereslts_form_{[xindex]}" name="vehiclereslts_form_{[xindex]}" onsubmit="return Page.validation();" method="GET" action="vehicleDetails.do">',
				'<div class="sp2_sort_result"><table><tr><td>',				
				'<input type="hidden" id="dealerCode" name="dealerCode" value="{dealerCode}">',
				'<input type="hidden" id="yearCode" name="yearCode" value="{yearDescription}">',
				'<input type="hidden" id="inventoryStockNumber" name="inventoryStockNumber" value="{stockNumber}">',
				'<input type="hidden" id="zipDistance" name="zipDistance" value="{[this.getZipDistance(values.zipDistance)]}">',
				'<input type="hidden" id="fiveStar" name="fiveStar" value="{fiveStar}">',
				'<input type="hidden" id="modelDescription" name="modelDescription" value="{modelDescription}">',
            	'<div class="sp2_sort_result_left"><img id="img_{[xindex]}" class="xtemplateimgclass" src="{[this.getImage(values.extImage)]}" onerror="this.src=\'{[this.getImgLocalePath()]}/cpov/no_image.gif\';"/></div>',
                '</td><td><div class="sp2_sort_result_middle">',
                	'<div class="sp2_sort_result_middle1">{yearDescription} {divisionDescription} {modelDescription}</div>',
                    '<div class="sp2_sort_result_table">',
               	  	'<table>',
                        	'<tr class="sp2_sort_result_tr">',
                           	  '<td class="sp2_sort_result_th">{[this.translate("eng")]}:</td>',
                              '<td class="sp2_sort_result_td">{engineDescription} / {transmissionDescription}</td>',
                              '<td class="sp2_sort_result_th">{[this.translate("mileageII")]}:</td>',
                              '<td class="sp2_sort_result_tprice">{[ASC.util.formatNumber(values.mileage,0)]}&nbsp;{[this.translate("miles")]}</td>',
                            '</tr>',
                            '<tr class="sp2_sort_result_tr">',
                           	  '<td class="sp2_sort_result_th">{[this.translate("vin")]}:</td>',
                              '<td class="sp2_sort_result_td">{vin}</td>',
                              '<td class="sp2_sort_result_th">{[this.translate("stock")]}:</td>',
                              '<td class="sp2_sort_result_tprice">{stockNumber}</td>',
                            '</tr>',
                            '<tr class="sp2_sort_result_tr">',
                           	  '<td class="sp2_sort_result_th">{[this.translate("colors")]}:</td>',
                              '<td class="sp2_sort_result_td">Ext: {extColorDescription} / Int: {intColorDescription} </td>',
                              '<td class="sp2_sort_result_th"></td>',
                              '<td class="sp2_sort_result_tprice"></td>',
                            '</tr>',
                        '</table>',
                    '</div>',
                    '<tpl if="this.isCertified(inventoryType)">',
                    	'<div class="sp2_sort_result_icon"><a href="javascript:ASC.Chrysler.trackLinkMetrics(\'content\',\'{[this.formattolowercase(values.yearDescription)]}_{[this.formattolowercase(values.divisionDescription)]}_{[this.formattolowercase(values.modelDescription)]}_certified\');Page.openPopupWindow(\'{dealerCode}\',\'{dealerDma}\');"><img src="{[this.getImgLocalePath()]}/cpov/cpov_icon_15.gif"/></a></div>',
                    '</tpl>',                   
                    '<div class="sp2_sort_result_see"><a href="javascript:ASC.Chrysler.trackLinkMetrics(\'content\',\'{[this.formattolowercase(values.yearDescription)]}_{[this.formattolowercase(values.divisionDescription)]}_{[this.formattolowercase(values.modelDescription)]}_see_vehicle_details\');Page.submitForm({[xindex]});">{[this.translate("see")]}</a></div>',
                '</div></td><td>',
                '<div class="sp2_sort_result_right">',
                	'<div class="sp2_sort_result_right1">{[this.displayMsrpPrice(values.MSRP)]}</div>',
                	'<tpl if="dealerSitePointer == \'3\'">',
                    '<div class="sp2_sort_result_right2"><a href="javascript:Page.getAQuote(\'{stockNumber}\',\'{dealerCode}\',\'{modelDescription}\',\'{yearDescription}\'); Page.requestMetrics(\'content\',\'{[this.formattolowercase(values.yearDescription)]}_{[this.formattolowercase(values.divisionDescription)]}_{[this.formattolowercase(values.modelDescription)]}_get_a_quote\');">{[this.translate("getDealer")]}</a></div>',
                    '<div class="sp2_sort_result_right2"><a href="javascript:Page.searchNewInventory(\'{dealerCode}\',\'{[this.getModelYearCode(values.modelYearCode)]}\'); Page.requestMetrics(\'content\',\'{[this.formattolowercase(values.yearDescription)]}_{[this.formattolowercase(values.divisionDescription)]}_{[this.formattolowercase(values.modelDescription)]}_search_new_inventory\');">{[this.translate("searchnewinventory")]}</a></div>',
                    '<div class="sp2_sort_result_right2"><a href="javascript:Page.getsearchlink(\'{dealerCode}\',\'{[this.getZipDistance(values.zipDistance)]}\'); Page.requestMetrics(\'content\',\'{[this.formattolowercase(values.yearDescription)]}_{[this.formattolowercase(values.divisionDescription)]}_{[this.formattolowercase(values.modelDescription)]}_search_pre_owned_inventory\');">{[this.translate("searchpreownedinventory")]}</a></div>',
                    '<div class="sp2_sort_result_right2"><a href="javascript:Page.scheduleTestDrive(\'{stockNumber}\',\'{dealerCode}\',\'{modelDescription}\',\'{yearDescription}\'); Page.requestMetrics(\'content\',\'{[this.formattolowercase(values.yearDescription)]}_{[this.formattolowercase(values.divisionDescription)]}_{[this.formattolowercase(values.modelDescription)]}_schedule_test_drive\');">{[this.translate("schedule")]}</a></div>',
                    /*'<div class="sp2_sort_result_right2"><a href="javascript:void(0); Page.requestMetrics(\'content\',\'{[this.formattolowercase(values.yearDescription)]}_{[this.formattolowercase(values.divisionDescription)]}_{[this.formattolowercase(values.modelDescription)]}_schedule_a_service_appointment\');">{[this.translate("scheduleaserviceappointment")]}</a></div>',*/
                    '</tpl>',
                    /*
                    '<tpl if="this.shouldShowContactDealer(fiveStar,emailAddress)">',
                	'<div class="sp2_sort_result_right2"><a href="mailto:{emailAddress};" name="&lpos=content&lid=contact_dealer">{[this.translate("contactdealer")]}</a></div>',
                	'</tpl>',*/
                	/*
                    '<div class="sp2_sort_result_right2"><a href="javascript:Page.applyForCredit(\'{stockNumber}\',\'{dealerCode}\',\'{divisionDescription}\',\'{yearDescription}\',\'{modelDescription}\',\'{modelDescription}\',\'{values.MSRP}\',\'{description}\');  Page.requestMetrics(\'content\',\'{[this.formattolowercase(values.yearDescription)]}_{[this.formattolowercase(values.divisionDescription)]}_{[this.formattolowercase(values.modelDescription)]}_apply_for_credit\');">{[this.translate("applyforcredit")]}</a></div>',
                    '<div class="sp2_sort_result_right2"><a href="javascript:Page.estimatePayment(\'{stockNumber}\',\'{dealerCode}\',\'{divisionDescription}\',\'{modelDescription}\',\'{yearDescription}\',\'{values.MSRP}\',\'{description}\');  Page.requestMetrics(\'content\',\'{[this.formattolowercase(values.yearDescription)]}_{[this.formattolowercase(values.divisionDescription)]}_{[this.formattolowercase(values.modelDescription)]}_estimate_payment\');">{[this.translate("estimatePayment")]}</a></div>',
                	*/
                '</div>',
            '</td></tr></table></div>',             
            '</form>',
            '</tpl>',            
            	{					
					translate: function (key)
					{
						return ASC.message(key);
					},
					getImgLocalePath: function(){
						return ASC.cfg.getImgLocalePath();
					},
					getImage:function(extImage)
					{
						if(!extImage)
						{
							return this.getImgLocalePath()+"/cpov/no_image.gif";
						}
						return extImage;
					},
					getMoneyFormat: function(money){
						return ASC.util.formatCurrency(money,0);
					},
					isCertified: function( inventoryType ){
						return inventoryType == 'C';
					},
					formattolowercase: function(strValue)
					{
						return strValue.toLowerCase();
					},
					isFiveStar: function( fiveStarValue )
					{
						return fiveStarValue == 'Y';
					},
					shouldShowContactDealer:function(fiveStarValue,email){
						return email && email.toLowerCase() != 'null' && fiveStarValue != 'Y';
					},
					getZipDistance: function(zipDistance)
					{
						if(zipDistance == null || zipDistance =="")
							return Page.zipDistance;
						else
							return zipDistance;
					},
					displayMsrpPrice: function (msrp) {
						if (msrp>0) {
							return this.getMoneyFormat(msrp);
						} else {
							// CHRUAT-1988
							//return ASC.message("contactdealer");
							return "";
						}
					},
					getModelYearCode: function(modelYearCode){
						if(modelYearCode == null ){
							return "" ;
						}else
						{
							return modelYearCode;
						}
					}
				});
		
		this.vehicleTpl.compile();
	},
	initPageBar: function()
	{
		this.pageBarTpl = new Ext.XTemplate(
						'<tpl for="pageCount">',
							'<a name="&lpos=content&lid=page{[xindex]}" href="javascript:Page.setPageIndexFunction({[xindex]});" {[xindex === Page.pageIndex ? "class=copvPageLinkClass_select":""]} >{[xindex]}</a>',
						'</tpl>'
				)
		this.pageBarTpl.compile();
	},
	update:function(vehicleData)
	{
		this.vehicleData = vehicleData;
		this.render();
	}
});

ASC.namespace('ASC.Chrysler.CPOV.YearDropDown');
ASC.Chrysler.CPOV.YearDropDown = ASC.extend(Ext.util.Observable,{
	
	renderTo:null,
	yearList:null,
	currentSelected:null,
	yearListType:null,
	
	constructor: function (yearList, yearListType, selYear, cfg)
	{
		ASC.Chrysler.CPOV.YearDropDown.superclass.constructor.apply(this);
		ASC.apply(this, cfg);		
		this.addEvents({"render":true});
		this.initTemplates();
		this.loadData(yearList, yearListType, selYear);
	},
	
	loadData: function( yearList, yearListType, selYear ){
		this.yearList = yearList;
		this.currentSelected = selYear;	
		this.yearListType = yearListType;	
		this.render(  );
	},
	
	render:function(  )
	{
		this.vehicleTpl.overwrite(this.renderTo, {years: this.yearList, sIndexDesc: this.currentSelected, compId: this.yearListType});		
		this.fireEvent("render");
	},
	
	initTemplates: function ()
	{
		//alert(this.vehicleData.data.invertotyVehicles);
		this.vehicleTpl = new Ext.XTemplate(
				'<select class="changfontsize changwidth" id="{compId}Sel" onchange="Page.dropDownOnChange(\'filter\', this.id);">',
			 	'<tpl for="years">',
			 		'<option value="{description}" {[this.isSelected(parent.sIndexDesc, values.description)?"selected":""]}>{description}</option>',
			 	'</tpl>',
			 	'</select>',		          
            	{					
					translate: function (key)
					{
						return ASC.message(key);
					},
					
					isSelected: function(selIndex, description){
						return description == selIndex;
					}
				});
		
		this.vehicleTpl.compile();
	},
	
	update:function(yearList, yearDesc)
	{
		var newYearList = [];
		var selIndex = 0;
		for( i=0; i<yearList.length; i++ ){
			if( yearList[i].description == yearDesc ){
				selIndex = i;
				break;
			}
		}
		if( this.yearListType == "yearEnd" ){
			for( i=selIndex; i<yearList.length; i++ ){
				newYearList.push(yearList[i]);
			}
		}else{
			for( i=0; i<=selIndex; i++ ){
				newYearList.push(yearList[i]);
			}
		}
		this.yearList = newYearList;
		this.render();
	},
	
	setCurrentSelected: function(currentSelected){
		this.currentSelected = currentSelected;
	}
});

ASC.apply(Page, {
	vehicleList: null,
	pageSize: 25,
	pageIndex:1,
	msrp:null,
	year:null,
	model:null,
	make:null,	
	llDesc:null,
	paymentEstimator: null,
	
	init: function()
	{		
		
	},
	loadVehicles: function (data)
	{
		this.vehicleData = data;//new ASC.Chrysler.Pagination(data,this.c_pageSize,'inventoryVehicles');

		//this.vehicleData.on('indexChanging',this.onIndexChanging,Page);

		ASC.getEl("lbTotalCount").dom.innerHTML = this.vehicleData.totalVehicleCount;

		this.vehicleList = new ASC.Chrysler.CPOV.VehicleList(this.vehicleData.inventoryVehicles, {

			renderTo: 'vehicles',

			renderToPageBar: 'pageBar',

			pageSize: this.pageSize,

			pageCount: this.vehicleData.totalVehicleCount,
			
			pageIndex: this.pagIndex
		});
	},	
	searchEntireCertified:function(){
		var thisLinks = ASC.message('externalSite') + "/vehsuite/DealerSearch.jsp?mode=preowned&setCPOVSite=true&adid=&pid=&rid=&bid=&daaXmlPath=&lang=en";
		window.open (thisLinks, 'newwindow');
	},	
	financiallink:function(){
		var thisLinks = "http://www.chryslerfinancial.com";
		window.open (thisLinks, 'newwindow');
	},
	servicecontracts:function(){
		var thisLinks = "http://www.servicecontracts.chrysler.com/";
		window.open (thisLinks, 'newwindow');
	},
	carfaxlink:function(){
		var thisLinks = "http://www.carfax.com";
		window.open (thisLinks, 'newwindow');
	},
	chryslerllclink:function(){
		var thisLinks = "http://www.chryslerllc.com/en/privacy/";
		window.open (thisLinks, 'newwindow');		
	},
	brandlinks:function(){
		var thisLinks = ASC.message('externalSite');
		window.open (thisLinks, 'newwindow');		
	},
	brandspankinusedlinks:function(){
		var thisLinks = "http://www.brandspankinused.com/";
		window.open (thisLinks, 'newwindow');		
	},
	getAQuote:function(stock_number, dealer_id, vehicle, year){
		var target = 'gaq';
		var thisLinks = ASC.cfg.getBridgeUrl() + "?target=" + target + "&vehicle=" + escape(vehicle) + "&year=" + year + "&dealer_id=" + dealer_id + "&stock_number=" + stock_number ;
		window.location.href=thisLinks;		
	},
	scheduleTestDrive:function(stock_number, dealer_id, vehicle, year) {
		var target = 'testdrive';
		var thisLinks = ASC.cfg.getBridgeUrl() + "?target=" + target + "&vehicle=" + escape(vehicle) + "&year=" + year + "&dealer_id=" + dealer_id + "&stock_number=" + stock_number ;
		window.location.href=thisLinks;	
	},
	getsearchlink:function(dealercode,zipDistance){
		var thisLinks = ASC.cfg.getContextPath() + "/cpov/vehicleResults.do?dealerCode=" + dealercode + "&zipDistance=" + zipDistance;
		window.open (thisLinks, '_top');	
	},
	openPopupWindow: function(dealerCode, dealerDMA)
	{
		window.open ("cpovWarranty.do?dealerCode="+dealerCode+'&dealerDMA='+dealerDMA, "newwindow", "height=750, width=550, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, status=yes")
	},
	/*
	 * setPageIndex, and it will fire the event 'indexChanging'.
	 * then pass the pageIndex and items to the event
	 * 
	 */
	setPageIndexFunction: function(pageIndex){
		this.pageIndex = pageIndex;
		//this.fireEvent("indexChanging",{pageIndex:this.pageIndex,items:this.getItems(this.pageIndex)});		
		this.dropDownOnChange('pageIndex');
	},
	applyForCredit: function (stockNumber, dealerCode, division, year, model, trim, msrp, llpDesc)
	{
		var url = this.cfUrl + '?cobrand='+this.brand+'&year='+year+'&make='+division+'&model='+model+'&trim='+trim+'&dealerId='+dealerCode+'&vehicleType=U&msrp='+msrp+'&zipCode='+this.zipCode+'&stockNum='+stockNumber+'&trim='+llpDesc;
		window.open(url, 'chryslerFinancialWindow');						
	},
	searchNewInventory: function (dealerCode, modelYearCode)
	{
		var url = ASC.cfg.getContextPath() + "/sni/inventorySearch.do?dealerCode=" + dealerCode + "&modelYearCode=" + modelYearCode;
		window.open(url, '_top');					
	},	
	estimatePayment: function(stockNumber, dealerCode, make, model, year, msrp, llpDesc) {

		Page.make = make;
		Page.model = model;
		Page.year = year;
		Page.msrp = msrp;
		Page.stockNumber = stockNumber;
		Page.llpDesc = llpDesc;
		Page.dealerCode = dealerCode;
		
		if(this.paymentEstimator == null){
			this.paymentEstimator = new ASC.Chrysler.CPOV.PaymentEstimatorStandAlone();
		}
		this.paymentEstimator.show();
				
		this.paymentEstimator.on({
			beforeShow: {
				fn: Page.setPaymentEstParams,
				scope: Page
			}
		});
		
		this.paymentEstimator.show();				
	},
	
	setPaymentEstParams: function () {
		if (!this.paymentEstimator) {
			return;
		}

		var params = {
			msrp: Page.msrp,
			zipCode: ASC.Chrysler.Cookies.getZipCode(),
			make: Page.make,
			model: Page.model,
			year: Page.year,
			vehicleType: 'U',
			stockNum: Page.stockNumber,
			trim: Page.llpDesc,
			dealerCode: Page.dealerCode
		};
		
		return params;
	},
		
	requestMetrics:function(lposValue,lidValue)
	{
		ASC.Chrysler.trackLinkMetrics(lposValue,lidValue);
	},
	dropDownMetrics: function(lposValue, objName)
	{
		var objValue = null;
		if(objName == "maxPrice" || objName == "maxMileage")
			objValue = ASC.getEl(objName).getValue();
		else
			objValue = ASC.getEl(objName).dom.options[ASC.getEl(objName).dom.selectedIndex].text;
		
		if(objName == "maxPrice" || objName == "maxMileage")
		{
			if(objValue == "")
				objValue = "no_maximum";
			else
			{
				if(objName == "maxPrice")
					objValue = "max_price_" + objValue;
				else
					objValue = "max_mileage_" + objValue;
			}
		}		
		if(objName == "yearStartSel" || objName == "yearEndSel")
			objValue = "year_range_" + objValue;
		if(objName == "sortBy")
			objValue = "sort_by_" + objValue;
		objValue = this.getFormatStr(objValue);
		ASC.Chrysler.trackLinkMetrics(lposValue,objValue);
	},
	getFormatStr:function(formatStr)
	{
		var oldStr = formatStr.toLowerCase();
		var pattern =/[^a-z0-9]+/;
		return oldStr.replace(pattern,"_");
	}
});


/*
 * ASC.Chrysler.CPOV.PaymentEstimator
 * */
ASC.namespace('ASC.Chrysler.CPOV.PaymentEstimatorStandAlone');
ASC.Chrysler.CPOV.PaymentEstimatorStandAlone = ASC.extend(Ext.Window, {
	
	id: '',
	/**
	 * @param {Object} cfg Window configurator parameters that are passed on to Ext.Window
	 */
	constructor: function (cfg)
	{	
		//this.initDlgTemplates();				
		var html = '<div id="objPaymentEstimator_container">' +
			'<div style="text-align:center; margin:5px;">' +
				'<h5>Adobe Flash Player is required to use the Payment Estimator</h5>' +							
				'<div style="padding: 5px 0 20px 0;">We have detected that you do not have Adobe Flash Player installed.</div>' +
				'<p>Please install Adobe Flash Player <a href="http://www.adobe.com/go/getflashplayer" title="Install Adobe Flash Player"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></p>' +
			'</div>' +
		'</div>';

		var winCfg = ASC.apply({			
			closeAction: 'hide',
			headerAsText: false,
			closable: true,
			plain: false,
			layout: 'fit',
			modal: true,
			constrainHeader: true,
			border: false,
			modal: true,
			resizable: false,
			width: 729,
			height:595,
			frame:true,
			hideBorders:true,
					
			items: {
				html: html
			}
			
		}, cfg);				
				
		ASC.Chrysler.CPOV.PaymentEstimatorStandAlone.superclass.constructor.call(this, winCfg);

		var me = this;
		this.on('beforeshow', function () {			
			if (!me.initializedFlash) {
				var swfUrl = ASC.cfg.getFinancialUrl() + 'paymentestimator/paymentestimator.swf';
				var so = new SWFObject(swfUrl, 'objPaymentEstimator', '710', '580', '9.0.47', '#869ca7', 'high');
				so.addVariable('host', ASC.cfg.getFinancialUrl());
				so.addVariable('mode', 'standalone')
				so.addVariable('cobrand', ASC.cfg.getTheme());
				so.addVariable('loadComplete', 'Page.setPaymentEstParams');
				so.useExpressInstall(ASC.cfg.getContextPath() + '/resources/js/swf/expressinstall.swf');
				
				so.addParam('movie', swfUrl);
				so.addParam('allowScriptAccess', 'always');
				
				so.write("objPaymentEstimator_container");
				
				me.initializedFlash =true;
			}
			
		}, me);			
	},

	getPayment: function ()
	{
		return this.getFlexDom().getPayment();
	},
	
	getFlexDom: function ()
	{
		return ASC.getEl('objPaymentEstimator').dom
	}	
});


ASC.onReady(Page.init, Page);

