ASC.namespace('ASC.Chrysler.FloatingMenu');
ASC.Chrysler.FloatingMenu = ASC.extend(Ext.util.Observable,{
	/*
	 * this.dealerCode
	 * this.modelYearCode
	 * this.zipCode
	 */
	constructor: function (config){
		this.zipCode = null;
		this.modelYearCode = null;
		this.ajax = Page.ajax;
		this.MYCIntegrationVehMap = new Ext.util.MixedCollection() ;
		ASC.Chrysler.FloatingMenu.superclass.constructor.apply(this);
		ASC.apply(this, config);
		this.initWidget();
		this.initComboBox();
		this.initLinkInformationAjax();
		this.initVehicleModelsAjax();
	},
	initWidget: function(){
		this.menu = new Ext.Layer({
			parentEl:ASC.getEl('content'),
			dh : {tag: "div", cls:"floatingMenu" }	
		});
		var menuTemplate = new Ext.XTemplate(
				'<div class="floatingMenu_content">',
				'<div id="modelYearCodeSelector"></div>',
//				'<input id="menuZipCode" name="zipCode"  maxlength="5"  style="display:none;width:50px;height:12px;"  value="" />',
				'<div class="floatingMenu_content_go" >',
					'<a id="floatingMenu_go" href="javascript:void(0);"><img src="{[ASC.cfg.getImgPath()]}/common/ico_go.gif"/></a>',
				'</div>',
				'</div>'
		);
		menuTemplate.overwrite(this.menu,{});
		ASC.getEl('floatingMenu_go').on('click',this.goActionHandler,this);
//		ASC.getEl('menuZipCode').addKeyMap({stopEvent:true,key:13,fn:this.submitFormDelegate,scope:this});
		this.menu.on('click',Ext.emptyFn ,this,{stopEvent:true });
		Ext.getBody().on('click',this.hideMenu,this);
	},
	hideMenu:function(){
		if(this.menu.isVisible()){
			this.vehicleSelectComboBox.collapse();
			this.menu.hide();
		}
	},
	initComboBox: function(){
		this.vehicleSelectStore = new Ext.data.SimpleStore({
			data:[],
    		fields: [ {name: 'modelYearCode',mapping: 'modelYearCode'},
    		          {name: 'year',mapping: 'year'},
    		          {name: 'description',mapping: 'description'}]
    	});
		Ext.QuickTips.init();
		var modelYearCodeSelector = ASC.getEl('modelYearCodeSelector');
		this.vehicleSelectComboBox = new Ext.form.ComboBox({
			autoCreate: {tag: "input", type: "text", autocomplete: "on"},
			tpl: '<tpl for="."><div ext:qtip="{description}" class="x-combo-list-item">{year} {description}</div></tpl>',
		    store: this.vehicleSelectStore,
		    id: 'modelYearCode',
		    valueField: 'modelYearCode',
		    displayField: 'description',		     
		    typeAhead: false,
		    mode: 'local',
		    forceSelection: true,
	        triggerAction: 'all',
		    emptyText:ASC.message('fad_findDealers_selectAVehicle'),
		    selectOnFocus:true,
		    renderTo: modelYearCodeSelector
		});
		this.vehicleSelectComboBox.on('select',this.vehicleSelectedHandler,this);
	},
	initLinkInformationAjax: function(){
		this.ajax.registerRequest('linkInformationAjax', ASC.cfg.getContextPath() + '/util/linkInformation.ajax');
		this.ajax.registerAjaxObject('getExternalLinkInfo', new ASC.Ajax.Response({
			events: {
				success: this.ajaxCB.storeAndRedirect,
				scope: this
			}
		}));
	},
	initVehicleModelsAjax: function(){
		this.ajax.registerRequest('vehicleModelsURL', ASC.cfg.getContextPath() + '/sni/vehicleModels.ajax');
		this.ajax.registerAjaxObject('models', new ASC.Ajax.Response({
			events: {
				success: this.ajaxCB.storeVehicle,
				scope: this
			}
		}));
	},
	ajaxCB: {		
		storeVehicle: function(response){
			if(response.data&&response.data.models&&response.data.models.length){
				for(var it in response.data.models){
					it.description = it.year +" "+ it.description;
				}
				this.vehicleSelectStore.sort("description");
				this.vehicleSelectStore.loadData(response.data.models,false);
			}
		},
		storeAndRedirect: function(response,ioArgs){
			var key = ioArgs.options.params.modelYear;
			var linkParams = response.data;
			if(linkParams){
				this.MYCIntegrationVehMap.add(key,linkParams);
				this.linkToBridgeUrl();
			}else{
				return;
			}
		}
	},
	toggle: function(evt,target,options){
//		if(options.zip){
//			ASC.getEl('menuZipCode').setValue(options.zip.subtring(0,5));
//		}
//		ASC.getEl('menuZipCode').setVisible(options.zip);
		this.getVehicle();
		var anchorTarget = ASC.getEl(options.anchorTarget || target);
		this.menu.alignTo(anchorTarget, 'tl-bl');
		if( this.currentType == options.type){
			this.menu.toggle();
		}else{
			this.menu.show();
			this.currentType = options.type;
			this.dealerCode = options.dealerCode;
		}
		if(this.menu.isVisible()){
			evt.stopEvent();
		}
	},
	vehicleSelectedHandler: function(combo){
		//stop event
		if(Ext.isIE) {					  
		    window.event.cancelBubble = true;
		    window.event.returnValue = false;
		} else {
			var func = this.vehicleSelectedHandler.caller;
			while(func!=null){ 
                var arg0=func.arguments[3];
                if(arg0)
                {
                  if((arg0.constructor==Event || arg0.constructor == MouseEvent) || (typeof(arg0)=="object" && arg0.preventDefault && arg0.stopPropagation))
                  { 
                	  arg0.stopPropagation();
                	  return;
                  }
                }
                func=func.caller;
            }
		}
	},
	getVehicle: function(){
		if(this.vehicleSelectStore.getTotalCount() == 0){
			this.ajax.sendRequest('vehicleModelsURL');			
		}
	},
	getLinkInfoByModelYearAndRedirect:function(){
		var vehMap = this.MYCIntegrationVehMap;
		if(vehMap.containsKey(this.modelYearCode) ){
			this.linkToBridgeUrl();
		}else{
			this.ajax.sendRequest('linkInformationAjax',{
				params: {
					modelYear: this.modelYearCode,
					returnFirstOnly: true
				}
			});	
		}
	},
	goActionHandler: function(evt,t,o){
		this.modelYearCode = this.vehicleSelectComboBox.getValue();
		if(this.currentType == 'gaq'){
			ASC.Chrysler.trackLinkMetrics('new_vehicle_sales_tab','get_a_quote_'+this.vehicleSelectComboBox.lastSelectionText);
		}else if( this.currentType == 'testdrive' ){
			ASC.Chrysler.trackLinkMetrics('new_vehicle_sales_tab','schedule_a_test_drive_'+this.vehicleSelectComboBox.lastSelectionText);
		}
		if(this.modelYearCode){
			this.getLinkInfoByModelYearAndRedirect();
		}
	},
	linkToBridgeUrl: function(){
		var values = this.MYCIntegrationVehMap.get(this.modelYearCode);
		var linkParams = "dealer_id="+this.dealerCode+"&vehicle="+String.escape(values.model)+"&year="+String.escape(values.year);
		var forwardUrl = "";
//		var chryslerFinancialSite ='http://www.chryslerfinancial.com';
		switch(this.currentType){
			case "sni": // search_new_inventory
				if(this.fromInterim){
					forwardUrl = ASC.cfg.getContextPath() + '/sni/inventorySearch.do?' + 'dealerCode='+this.dealerCode+'&modelYearCode='+this.modelYearCode + '&fromInterim='+this.fromInterim ;
				}else{
					forwardUrl = ASC.cfg.getContextPath() + '/sni/inventorySearch.do?' + 'dealerCode='+this.dealerCode+'&modelYearCode='+this.modelYearCode  ;
				}
				break;
			case "brochure": // get_a_brochure
				forwardUrl = ASC.cfg.getBridgeUrl()+ '?target=brochure&'+ linkParams;
				break;
			case "gaq": // get_a_quote
				forwardUrl = ASC.cfg.getBridgeUrl()+ '?target=gaq&'+ linkParams;
				break;
//			case "testdrive": // schedule_a_test_drive
//				forwardUrl = ASC.cfg.getBridgeUrl()+ '?target=testdrive&'+ linkParams;
//				break;
//		   case "incentives": 
//			   forwardUrl = ASC.cfg.getBridgeUrl()+ '?target=incentives&'+ linkParams;
//			   break;
//		   case "m_estimate":
//			  forwardUrl = chryslerFinancialSite+'/payments/index.jsp?'+'zipCode='+this.zipCode+'&'+dealerParams;
//			  break;
	     }
		window.location.href=forwardUrl;
	}
	/*
	_validate:function()
	{					
		if(!ASC.util.isZip(this.zipCode.getValue()))
		{
			alert('ASC.message(todo...) zipCode is invalid!');
			this.zipCode.focus();
			return false;
		}
		return true;
	}
	*/
});
