AE.namespace('AE.searchBar');
AE.searchBar = function(){
	this.config = {
		bar : get("searchBar"),
		form : get("SearchForm"),
		tabsBox : get("searchTabsBox"),
		searchInput : get("SearchTextIdx"),
		intelligent : get("searchIntelligent"),
		hintClass : "hint",
		countrySelect : get("searchCountry"),
		submitBtn : get("searchSubmit"),
		hiddenIndexArea : get("searchIndexArea"),
		advanceSearchLink : "http://www.alibaba.com/trade/advancesearch",
		onlyOneShow : false,	// 是否只显示一个
		isNeedSubmit: true,
		isBlank : false,
		selectlinkDatas : {
			country_home:{
				AU:'Australia',
				BR:'Brazil',
				CA:'Canada',
				CN:'China (Mainland)',
				EG:'Egypt',
				HK:'Hong Kong',
				IN:'India',
				ID:'Indonesia',
				JP:'Japan',
				MY:'Malaysia',
				PH:'Philippines',
				SG:'Singapore',
				KR:'South Korea',
				TW:'Taiwan',
				TH:'Thailand',
				TR:'Turkey',
				UK:'United Kingdom',
				US:'United States',
				VN:'Vietnam',
				advanceSearch:'More ...'
			},
			country_listing:{
				AU:'Australia',
				BR:'Brazil',
				CA:'Canada',
				CN:'China (Mainland)',
				EG:'Egypt',
				HK:'Hong Kong',
				IN:'India',
				ID:'Indonesia',
				JP:'Japan',
				MY:'Malaysia',
				PH:'Philippines',
				SG:'Singapore',
				KR:'South Korea',
				TW:'Taiwan',
				TH:'Thailand',
				TR:'Turkey',
				UK:'United Kingdom',
				US:'United States',
				VN:'Vietnam',
				'':'----------------------',
				afr:'[Africa]','nam,csa':'[Americas]',
				'asi,gcn':'[Asia]',
				asi:'[Asia (except China)]',
				aoc:'[Oceania]',
				csa:'[Central and South America]',
				eec:'[Eastern Europe and CIS]',
				'weu,eec':'[Europe and CIS]',
				gcn:'[Great China]',
				mea:'[Middle East]',
				nam:'[North America]',
				weu:'[Western Europe]',
				advanceSearch:'More ...'
			}
		},
		locations : {AF:'Afghanistan',AL:'Albania',DZ:'Algeria',AS:'American Samoa',AD:'Andorra',AO:'Angola',AI:'Anguilla',AQ:'Antarctica',AG:'Antigua and Barbuda',AR:'Argentina',AM:'Armenia',AW:'Aruba',AU:'Australia',AT:'Austria',AZ:'Azerbaijan',BS:'Bahamas',BH:'Bahrain',BD:'Bangladesh',BB:'Barbados',BY:'Belarus',BE:'Belgium',BZ:'Belize',BJ:'Benin',BM:'Bermuda',BT:'Bhutan',BO:'Bolivia',BA:'Bosnia and Herzegowina',BW:'Botswana',BV:'Bouvet Island',BR:'Brazil',IO:'British Indian Ocean Territory',BN:'Brunei Darussalam',BG:'Bulgaria',BF:'Burkina Faso',BI:'Burundi',KH:'Cambodia',CM:'Cameroon',CA:'Canada',CV:'Cape Verde',KY:'Cayman Islands',CF:'Central African Republic',TD:'Chad',CD:'Channel Island',CL:'Chile',CN:'China (Mainland)',CX:'Christmas Island',CC:'Cocos (Keeling) Islands',CO:'Colombia',KM:'Comoros',CG:'Congo',ZR:'Congo, The Democratic Republic Of The',CK:'Cook Islands',CR:'Costa Rica',CI:'Cote D\'Ivoire',HR:'Croatia (local name: Hrvatska)',CU:'Cuba',CY:'Cyprus',CZ:'Czech Republic',DK:'Denmark',DJ:'Djibouti',DM:'Dominica',DO:'Dominican Republic',TP:'East Timor',EC:'Ecuador',EG:'Egypt',SV:'El Salvador',GQ:'Equatorial Guinea',ER:'Eritrea',EE:'Estonia',ET:'Ethiopia',FK:'Falkland Islands (Malvinas)',FO:'Faroe Islands',FJ:'Fiji',FI:'Finland',FR:'France',FX:'France Metropolitan',GF:'French Guiana',PF:'French Polynesia',TF:'French Southern Territories',GA:'Gabon',GM:'Gambia',GE:'Georgia',DE:'Germany',GH:'Ghana',GI:'Gibraltar',GR:'Greece',GL:'Greenland',GD:'Grenada',GP:'Guadeloupe',GU:'Guam',GT:'Guatemala',GN:'Guinea',GW:'Guinea-Bissau',GY:'Guyana',HT:'Haiti',HM:'Heard and Mc Donald Islands',HN:'Honduras',HK:'Hong Kong',HU:'Hungary',IS:'Iceland',IN:'India',ID:'Indonesia',IR:'Iran (Islamic Republic of)',IQ:'Iraq',IE:'Ireland',IL:'Israel',IT:'Italy',JM:'Jamaica',JP:'Japan',JO:'Jordan',KZ:'Kazakhstan',KE:'Kenya',KI:'Kiribati',KS:'Kosovo',KW:'Kuwait',KG:'Kyrgyzstan',LA:'Lao People\'s Democratic Republic',LV:'Latvia',LB:'Lebanon',LS:'Lesotho',LR:'Liberia',LY:'Libyan Arab Jamahiriya',LI:'Liechtenstein',LT:'Lithuania',LU:'Luxembourg',MO:'Macau',MK:'Macedonia',MG:'Madagascar',MW:'Malawi',MY:'Malaysia',MV:'Maldives',ML:'Mali',MT:'Malta',MH:'Marshall Islands',MQ:'Martinique',MR:'Mauritania',MU:'Mauritius',YT:'Mayotte',MX:'Mexico',FM:'Micronesia',MD:'Moldova',MC:'Monaco',MN:'Mongolia',MS:'Montserrat',MA:'Morocco',MZ:'Mozambique',MM:'Myanmar',NA:'Namibia',NR:'Nauru',NP:'Nepal',NL:'Netherlands',AN:'Netherlands Antilles',NC:'New Caledonia',NZ:'New Zealand',NI:'Nicaragua',NE:'Niger',NG:'Nigeria',NU:'Niue',NF:'Norfolk Island',KP:'North Korea',MP:'Northern Mariana Islands',NO:'Norway',OM:'Oman',Other:'Other Country',PK:'Pakistan',PW:'Palau',PS:'Palestine',PA:'Panama',PG:'Papua New Guinea',PY:'Paraguay',PE:'Peru',PH:'Philippines',PN:'Pitcairn',PL:'Poland',PT:'Portugal',PR:'Puerto Rico',QA:'Qatar',RE:'Reunion',RO:'Romania',RU:'Russian Federation',RW:'Rwanda',KN:'Saint Kitts and Nevis',LC:'Saint Lucia',VC:'Saint Vincent and the Grenadines',WS:'Samoa',SM:'San Marino',ST:'Sao Tome and Principe',SA:'Saudi Arabia',SN:'Senegal',SC:'Seychelles',SL:'Sierra Leone',SG:'Singapore',SK:'Slovakia (Slovak Republic)',SI:'Slovenia',SB:'Solomon Islands',SO:'Somalia',ZA:'South Africa',KR:'South Korea',ES:'Spain',LK:'Sri Lanka',SH:'St. Helena',PM:'St. Pierre and Miquelon',SD:'Sudan',SR:'Suriname',SJ:'Svalbard and Jan Mayen Islands',SZ:'Swaziland',SE:'Sweden',CH:'Switzerland',SY:'Syrian Arab Republic',TW:'Taiwan',TJ:'Tajikistan',TZ:'Tanzania',TH:'Thailand',TG:'Togo',TK:'Tokelau',TO:'Tonga',TT:'Trinidad and Tobago',TN:'Tunisia',TR:'Turkey',TM:'Turkmenistan',TC:'Turks and Caicos Islands',TV:'Tuvalu',UG:'Uganda',UA:'Ukraine',AE:'United Arab Emirates',UK:'United Kingdom',US:'United States',UM:'United States Minor Outlying Islands',UY:'Uruguay',UZ:'Uzbekistan',VU:'Vanuatu',VA:'Vatican City State (Holy See)',VE:'Venezuela',VN:'Vietnam',VG:'Virgin Islands (British)',VI:'Virgin Islands (U.S.)',WF:'Wallis And Futuna Islands',EH:'Western Sahara',YE:'Yemen',YU:'Yugoslavia',ZM:'Zambia',ZW:'Zimbabwe'}
		,
		submitErrors : {
				isEmpty : "Please input a search term.",
				tooLong : "please input a search term less than 50 characters.",
				onlyEng : "Sorry, the information you filled in is not in English. Please input the information in English instead."
		},
		setups : {
				product : { type : 'product' , actionUrl : 'http://www.alibaba.com/trade/search' , indexArea : 'product_en' , submitFormWhenClicked : false },
				sell : { type : 'sell' , actionUrl : 'http://www.alibaba.com/trade/search' , indexArea : 'offer_en' , submitFormWhenClicked : false },
				company : { type : 'company' , actionUrl : 'http://www.alibaba.com/trade/search' , indexArea : 'company_en' , submitFormWhenClicked : false },
				buy : { type : 'buy' , actionUrl : 'http://importer.alibaba.com/buyeroffers' , indexArea : 'offer_en' , submitFormWhenClicked : false },
				tradeShows : { type : 'tradeShows' , actionUrl : 'http://tradeshow.alibaba.com/search' , indexArea : 'ts_en' , submitFormWhenClicked : false }
		},
		fackSelectorConfig : {
				selectId: "searchCategory",
				fakeSelectId: "fakeSelectorBox",
				selectBoxWH: [244,20],
				selectBoxZIndex: 1000,
				optionBoxTop: "23px",
				arrowBoxLeft: "235px"
		},
		historyInput : {
			tab	:	get("historyTab"),
			searchInput : get("historySearchInput"),
			searchCountry : get("historySearchCountry")
		}
	}
	this.manualSubmit = new YAHOO.util.CustomEvent('manualSubmit', this);
	/**
	 [需求 2011071301 begin]
	 @描述 
		Searchbar打点bug fix：目前只要suggestion展开，无论是否点击，都会记为suggestion；修改为：搜索词和输入词不同的时候，才记为suggestion
	 @PD 刘思齐
	 @前端 刘帅
	 [逻辑]
	 该全局变量记录搜索词是否和输入词不同，true - 搜索词和输入词不同|false - 搜索词和输入词相同
	 */
	this.kwdFromItlSearch = false;
	/**
	 [需求 2011071301 end]
	 */
}


AE.searchBar.prototype = {
	init : function(config){
		this.config = YL.merge(this.config,config||{});
		this.defineEvent();
		this.defaultRun();
		return this;
	},
	defineEvent : function(){
		var _self = this;
		var config = _self.config;
		var tabs = config.tabsBox.getElementsByTagName("a");
		var searchSelects = config.bar.getElementsByTagName("select");
		_self.config.tabs = tabs;
		_self.config.searchSelects = searchSelects;
		var searchInput = config.searchInput;
		var searchForm = config.form;
		
		YUE.on(tabs,"click",function(){
				if(YUD.hasClass(this.parentNode, 'current')) return true;
				return _self.searchTabClick(this);
		})
		
		YUE.on(searchInput,"click",function(ev){
				_self.searchHint(this,"disable");
		})

		YUE.on(searchSelects,"mouseover",function(ev){
				YUE.removeListener(this,ev.type,arguments.callee);
				_self.fillSelect(this);
		})

		YUE.on(searchSelects,"focus",function(ev){
				YUE.removeListener(this,ev.type,arguments.callee);
				_self.fillSelect(this);
		})
		
		YUE.on(searchForm,"submit",function(ev){ 
			return _self.searchFormSubmit();
		})
		YUE.onDOMReady(function(){
			// 如果有历史记录 从隐藏域记录重填
			_self.historyRestore();
			
			// 忽略锚点情况
			/*
			if(window.location.hash.replace("#","").length==0){
				_self.collapseInput(searchInput);
			}
			*/
			
		})
		if( config.countrySelect ){
			YUE.on(config.countrySelect,"change",function(ev){
				_self.countrySelectsChange(this);
			})
		}
	},
	defaultRun : function(){
		var _self = this;var config = this.config;
		
		// 记录默认选中位置
		this.tabSelected = YUD.getElementsByClassName("current","*",config.tabsBox)[0];
		this.selectedType = this.tabSelected.getElementsByTagName("a")[0].id;

		// 增加默认提示
		var searchInput = config.searchInput;

		if( ( searchInput.value != this.tabSelected.getElementsByTagName("a")[0].getAttribute("hint") ) && (searchInput.value != "" || searchInput.getAttribute("hasKeyword") == "true") ){
			searchInput.hasFocus = true;
			searchInput.value = XMLDecode(searchInput.value);
			if(typeof(logKeywordsHistory) == 'function'){logKeywordsHistory(searchInput.value)};
		}else{ // 存在默认值
			this.searchHint(searchInput,"hint",this.tabSelected.getElementsByTagName("a")[0].getAttribute("hint"));
		}
		
		// 默认表单Action
		config.form.attributes["action"].value = config.setups[this.selectedType].actionUrl;

		// 根据selected属性重置select值
		this.defaultSelect();

		// 初始化智能联想
		_self.intelligentObj = this.intSearchIntelligent();
	
		// 初始化模拟selector
		if(get(config.fackSelectorConfig.selectId)){
			var selectorTop = new AE.widget.xSelector();
			selectorTop.init(config.fackSelectorConfig);
			_self.selectorTop = selectorTop;
		}
		
		// only one show
		if(config.onlyOneShow){
			YUE.on(config.searchInput,"click",function(){
				_self.selectorTop.rollup();
			})
			
			if(get(config.fackSelectorConfig.selectId)){
				YUE.on(config.fackSelectorConfig.fakeSelectId,"click",function(){
					_self.intelligentObj.UIController.hideList();
				})
			}
		}

	},
	searchTabClick : function(tab){
			var config  = this.config;
			// 当前选择 跳过
			if(YUD.hasClass(tab.parentNode,"current")){return false};
			// 链接 转向
			if((/https?:\/\/[^/]+/i).test(tab.href)) return true;
			this.selectedType = tab.id;
			var searchType = tab.id;
			var searchInput = config.searchInput;
			
			if(!searchInput.hasFocus || searchInput.value == ""){
				this.searchHint(searchInput,"hint",tab.getAttribute("hint"));
			}else{
				searchInput.focus();
			}

			YUD.removeClass(this.tabSelected,"current")
			this.tabSelected = tab.parentNode;
			YUD.addClass(this.tabSelected,"current");

			var oSearchConfig = config.setups[searchType];
			config.form.attributes["action"].value = oSearchConfig.actionUrl;
			config.hiddenIndexArea.value = oSearchConfig.indexArea;

			if(searchType == oSearchConfig.indexArea && oSearchConfig.submitFormWhenClicked){
				this.searchFormSubmit()
			}

			return false;
	},
	// 智能联想初始化
	intSearchIntelligent : function(){
		var _self = this;
		if(this.config.intelSearchConfig){
			var controller = new AE.widget.intelligentSearch();
			controller.init(this.config.intelSearchConfig);
			/**
			 [需求 2011071301 begin]
			 @描述 
			 	Searchbar打点bug fix：目前只要suggestion展开，无论是否点击，都会记为suggestion；修改为：搜索词和输入词不同的时候，才记为suggestion
			 @PD 刘思齐
			 @前端 刘帅
			 [逻辑]
			 在controller设置输入框值时，视为用户输入的词和搜索词不同
			 */
			controller.onSetInputElValue.subscribe(function() {
				_self.kwdFromItlSearch = true;
			});
			/** [需求 2011071301 end] */
			controller.onFormSubmit.subscribe(function(){
				_self.dataRecord();
			});
			return controller;
		}
	},
	searchHint : function(input,type,hintText){
			var _self = this;
			if(type == "hint" && hintText){
					input.value = hintText;
					YUD.addClass(input,_self.config.hintClass);
					input.hasFocus = false;
					this.collapseInput(input);
			}else if(type == "disable"){
					YUD.removeClass(input,_self.config.hintClass);
					if(input.hasFocus == false){
						input.value = "";
					}
					input.hasFocus = true;
			}
			
			YUE.on(input,"keydown",function(ev){
					if(input.hasFocus){
						return;
					}
					_self.searchHint(input,"disable");
					input.hasFocus = true;
			})
			YUE.on(input,"paste",function(ev){
					if(input.hasFocus){
						return;
					}
					_self.searchHint(input,"disable");
					input.hasFocus = true;
			})
	},
	collapseInput : function(input){
		// 锚点定位模式 避免focus打乱页面定位
		var isHashMode = (window.location.hash.replace("#","").length==0);
		// collapse categories 页面
		var isCollapseCategories = YUD.getElementsByClassName("categories-collapse").length > 0;
		
		if(input.createTextRange){
			var rng = input.createTextRange();
			if(input.hasFocus)rng.moveStart('character',input.value.length); 
			rng.collapse(true);
			if(isHashMode && !isCollapseCategories)rng.select();
		}else if(input.setSelectionRange){
			var rng = input.setSelectionRange(0,0);
		}
		if(isHashMode && !isCollapseCategories)input.focus();
	},
	fillSelect : function(select){
		if(!select.linkData || select.filled)return;
		var dataObj = select.linkData;

	  for(var key in dataObj){
	  	select.options.add(new Option(dataObj[key],key));
	  }
	  select.filled = true;
	  var key = select.getAttribute("selected");
	  if(!key || key == "")return;
	  if(dataObj[key]){
	  	select.remove(select.selectedIndex);
	  	select.value = key;
	  }
	},
	defaultSelect : function(){
				var config = this.config;
				for(i=0;i<config.searchSelects.length;i++){
						var select = config.searchSelects[i];

						var dataName = select.getAttribute("dataName");
						if(!dataName || dataName == "")continue;
						select.linkData = config.selectlinkDatas[dataName];
						if(!select.linkData)continue;
						var key = select.getAttribute("selected");
						if(!key || key == "")continue;
						if(select.linkData[key]){
							select.selectedOp = select.options.add(new Option(select.linkData[key],key));
							select.value = key;
						}else{
							//生僻国家处理 寻找locations数据
							if(config.locations[key]){
									select.selectedOp = select.options.add(new Option(config.locations[key],key));
									select.value = key;
									eval("select.linkData." + key + " = '" + config.locations[key] + "';")
								}
						}
				}
	},
	// 表单提交 校验
	searchFormSubmit : function(){
			var config = this.config;
			var historyInput = config.historyInput;
			var searchInput = config.searchInput;
			var submitErrors = config.submitErrors;
			
			if(trim(searchInput.value) == '' || !searchInput.hasFocus){
				alert(submitErrors.isEmpty);return false;
			}
			
			if(searchInput.value.length > 50){
				alert(submitErrors.tooLong);return false;
			}

			if(!/^[\x00-\x7F]*$/.test(trim(searchInput.value))){
				alert(submitErrors.onlyEng);return false;
			}

			historyInput.tab.value = this.selectedType;
			if(searchInput.hasFocus){
				historyInput.searchInput.value = searchInput.value;
			}
			
			if(config.countrySelect){
				historyInput.searchCountry.value = config.countrySelect.value;
			}
			if(!config.isBlank){
				YUE.removeListener(config.form,"submit");				
			}
			
			this.dataRecord();

			if(config.isNeedSubmit){
				config.form.submit();
			}else{
				this.manualSubmit.fire(config.form);
			}
	},
	countrySelectsChange : function(countrySelect){
			if(countrySelect.value == "advanceSearch"){
				location = this.config.advanceSearchLink;
			}
	},
	historyRestore : function(){

			var searchInput = this.config.searchInput;
			var historyInput = this.config.historyInput;
			
			if(historyInput.tab.value != ""){
					this.searchTabClick(get(historyInput.tab.value));
			}
			
			if(historyInput.searchInput.value != ""){
					searchInput.hasFocus = true;
					this.searchHint(searchInput,"disable");
					searchInput.value = historyInput.searchInput.value;
			}
			
			if( historyInput && historyInput.searchCountry.value != "" ){
					this.config.countrySelect.setAttribute("selected",historyInput.searchCountry.value)
					this.defaultSelect();
			}
	},
	dataRecord : function(){
		/**
		 [需求 2011071301 begin]
		 @描述 
			Searchbar打点bug fix：目前只要suggestion展开，无论是否点击，都会记为suggestion；修改为：搜索词和输入词不同的时候，才记为suggestion
		 @PD 刘思齐
		 @前端 刘帅
		 [逻辑]
		 当非搜索词和输入词不同时，不打点
		 */
		if ( !this.kwdFromItlSearch ) {return;}
		/**
		 [需求 2011071301 end]
		 */
		var config = this.config,
			_self = this,
			searchForm  = config.form,
			searchInput = config.searchInput,
			useSuggestion = _self.intelligentObj.UIController.needDisplayList,
			searchCatEl = get('catId') ? get('catId') : get('searchCategory'),
			categoryLimited = searchCatEl.value  == 0,
			// 接收统计数据的地址
	 		dataRecordServer = 'http://stat.alibaba.com/qr/ws_query_report.html',
			// suggestion列表中的当前输入关键字（有加黑效果）
			boldKeywordEls = YUD.getElementsByClassName('boldKeword','*','searchIntelligent'),
			// 获取用户推suggestion的源词
			boldKeyword = boldKeywordEls[0] ? boldKeywordEls[0].innerHTML : '';
			
			useSuggestion = useSuggestion && boldKeyword;
			// 打点用到的参数
			var param = {
				// 当前提交的关键字
				'ws_ckw' : searchInput.value,  
				// 类目id			
				'ws_category_id' : searchCatEl.value,		
				// 打点区域为searchbar
				'ws_area' : 'Searchbar',
				// 使用suggestion：sugg0（没有限定行业），sugg1（限定行业)
				// 未使用suggestion：0（没有限定行业）， 1（限定行业）
				'ws_type' : useSuggestion ? (categoryLimited ? 'sugg1' : 'sugg0'):(categoryLimited ? '1' : '0') ,
				// 使用suggestion：[搜索关键词]_[输入的keyword]
				// 未使用suggestion：[搜索关键词] 
				'ws_value' : useSuggestion ? (searchInput.value + '_' + boldKeyword ) : searchInput.value
			};
       dmtrack.clickstat(dataRecordServer, param);
    
	}
	
}
