(function () {
	var YL = YAHOO.lang,
		YUD = YAHOO.util.Dom,
		YUE = YAHOO.util.Event,
		get = YUD.get;

	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,
			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);
	};
	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 != "" || searchInput.getAttribute("hasKeyword") == "true") {
				searchInput.hasFocus = true;
				searchInput.value = AE.util.xmlDecode(searchInput.value);
				if (typeof (logKeywordsHistory) == 'function') {
					logKeywordsHistory(searchInput.value)
				};
			} else {
				this.searchHint(searchInput, "hint", this.tabSelected.getElementsByTagName("a")[0].getAttribute("hint"));
			}
			config.form.attributes["action"].value = config.setups[this.selectedType].actionUrl;
			this.defaultSelect();
			_self.intelligentObj = this.intSearchIntelligent();
			if (get(config.fackSelectorConfig.selectId)) {
				var selectorTop = new AE.widget.xSelector();
				selectorTop.init(config.fackSelectorConfig);
				_self.selectorTop = selectorTop;
			}
			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 () {
			if (this.config.intelSearchConfig) {
				var controler = new AE.widget.intelligentSearch();
				controler.init(this.config.intelSearchConfig);
				return controler;
			}
		},
		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) {
			if (input.createTextRange) {
				var rng = input.createTextRange();
				if (input.hasFocus) rng.moveStart('character', input.value.length);
				rng.collapse(true);
				rng.select();
			} else if (input.setSelectionRange) {
				var rng = input.setSelectionRange(0, 0);
			}
			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 {
					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 (YAHOO.lang.trim(searchInput.value) == '' || !searchInput.hasFocus) {
				alert(submitErrors.isEmpty);
				return false;
			}
			if (searchInput.value.length > 50) {
				alert(submitErrors.tooLong);
				return false;
			}
			if (!/^[\x00-\x7F]*$/.test(YAHOO.lang.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;
			}
			YUE.removeListener(config.form, "submit");
			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();
			}
		}
	};
}());
