var AdSearchBar={
	init:function () {
		AdSearchBar._initSearchOpen();
		AdSearchBar._initTextSearch();
		AdSearchBar._initPropertySearch();
		AdSearchBar._initSearchButtons();
		AdSearchBar._initEnterButtonClick();
		AdSearchBar._syncInputsAndQs();

		// when hitting back the Ads.search is activated with the data saved
		// but it should also sync the inputs of the search bar with current search data
		if (typeof(Ads)!="undefined") {
			Ads.addEvent("onSearching",function (searchTerms,searchTags,topRated,editorsChoice) {
				AdSearchBar.updateInputs(searchTerms,searchTags);
			});
		}
	},
	_autoCompleteOpened:false,
	_syncInputsAndQs:function () {
		var q=QS.get("Q"),tagIds=QS.get("TagIds");
		if (q) q=q.split(" ");
		if (tagIds) tagIds=tagIds.split(",").map(function (i) { return +i; });
		AdSearchBar.updateInputs(q,tagIds);
		if (q || tagIds) AdSearchBar._openSearch.callOnce(true);
	},
	_initSearchOpen:function () {
		AdSearchBar._openSearch(true);
//		$("ad-search").addEvent("mousedown",function () {
//			AdSearchBar._openSearch.callOnce();
//			this.removeEvent("mousedown",arguments.callee); // arguments.callee - this very function!
//		});
	},
	_openSearch:function (disableFx) {
		if (disableFx) {
			//$("ad-search").setStyle("width",931);
			//$("ad-search-properties").show().setStyles("width",705);
		}
		else {
//			$("ad-search").effects().start({width:931}).chain(function () {
//				$("ad-search-properties").show().setStyles({overflow:"hidden",width:0,opacity:0}).effects().start({width:705,opacity:1});
//			});
		}
		new CheckBoxes("#ad-search-properties li li label");
	},
	_initSearchButtons:function () {
		$$("#ad-search-properties-button","#ad-text-search-button").addReplacingEvent("click",function (e) {
			AdSearchBar.search();
		});
	},
	_initEnterButtonClick:function(){
		$("ad-text-search-input").addEvent("keydown",function(e) {
			if (e.key=="enter" && (!AdSearchBar._autoCompleteOpened || !AdSearchBar.completer.selected)) {
				AdSearchBar.completer.hideChoices(); // hide auto complete choices
				AdSearchBar.search();
			}
		});
	},
	_initTextSearch:function () {
		AdSearchBar.completer=new Autocompleter.MultiTagSearch(
			$("ad-text-search-input"),
			"Services/AdSearchAutocomplete.ashx",
			{
				postVar:"Q",
				maxChoices:100,
				onRequest:function () {
					$("ad-text-search").addClass("loading");
				},
				onComplete:function () {
					$("ad-text-search").removeClass("loading");
				},
				onShow:function () {
					AdSearchBar._autoCompleteOpened=true;
				},
				onHide:function () {
					AdSearchBar._autoCompleteOpened=false;
				}
			}
		);

		function setWatermark() {
			$("ad-text-search-label").hide();
			(function () { $("ad-text-search-input").focus(); }).delay(1);
		}
		$("ad-text-search-label").addEvent("mousedown",setWatermark);
		$("ad-text-search-input").addEvents({
			"focus":setWatermark,
			"blur":function () {
				if (!this.value.trim()) $("ad-text-search-label").show();
			}
		});
		if ($("ad-text-search-input").value.trim()) $("ad-text-search-label").hide();
	},
	_initPropertySearch:function () {
		// widths of the buttons that open the filters
		var CLOSED_BUTTON=98,
			SEMI_OPEN_BUTTON=111,
			OPENED_BUTTON=127;

		var last;
		var filters=$$("#ad-search-properties ul li a");
		// for retrieve or store
		function getFx() {
			return this.effects({duration:200,wait:false,transition:Fx.Transitions.Back.easeInOut});
		}
		filters
			.setProperty("hideFocus","hideFocus")
			.hover(
				function (e) {
					if (this.retrieve("opened")) return;
					this.retrieveOrStore("fx",getFx).start({width:SEMI_OPEN_BUTTON});
				},
				function (e) {
					if (this.retrieve("opened")) return;
					this.retrieve("fx").start({width:CLOSED_BUTTON});
				}
			).addEvent("click",function (e) {
				e.stop();
				if (this.retrieve("opened")) return;
				this.retrieveOrStore("parent",function () { return this.getParent(); });
				if (last) {
					if (last.retrieve("fx")) last.retrieve("fx").start({width:CLOSED_BUTTON});
					last.retrieve("parent").removeClass("current").getElement("ul").hide();
					last.store("opened",false);
				}
				this.store("opened",true);
				last=this;
				this.retrieve("fx").start({width:SEMI_OPEN_BUTTON}).chain(function () {
					this.retrieve("parent").addClass("current");
					this.retrieve("fx").start({width:OPENED_BUTTON});
				}.bind(this));

				this.retrieve("parent").getElement("ul").set("opacity",0).show().effects().start({opacity:1});
			});

		// open first property filter
		var first=filters[0];
		if (first) {
			first.store("opened",true).store("parent",first.getParent());
			first.retrieve("parent").addClass("current").getElement("ul").show();
			last=first;
		}

		// init clear all and select all for checkboxes
		$("ad-search-properties-controls").getElement(".clear-all").addReplacingEvent("click",function () {
			var checks=$$("#ad-search-properties-list>ul>li.current input[type=checkbox]");
			CheckBoxes.setState(checks,false);
			$("ad-text-search-label").show();
			$("ad-text-search-input").value="";
			
		});
		$("ad-search-properties-controls").getElement(".select-all").addReplacingEvent("click",function () {
			var checks=$$("#ad-search-properties-list>ul>li.current input[type=checkbox]");
			CheckBoxes.setState(checks,true);
		});
	},

	search:function () {
		var serachData=AdSearchBar._gatherSearchData();
		
		// if Ads found -- search over them
		if (typeof(Ads)!="undefined") Ads.search(serachData.terms,serachData.tags,false,false);
		// else - redirect to the ad search page with query string
		else {
			var tags=serachData.tags;
			// if all checked - send empty tags
			if (!tags || tags.length==$$("#ad-search-properties-list input[type=checkbox]").length) tags=[];
			location.href="Default.aspx?Q="+serachData.terms.join(" ")+"&TagIds="+tags.join(",");
		}
	},

	updateInputs:function (terms,tags) {
		// updates all inputs by the search arguments given
		if (!terms) terms=[];
		$("ad-text-search-input").value=terms.join(" ");
		if (terms.length) $("ad-text-search-label").hide();
		if (tags && tags.length) {
			var checked=[],unchecked=[];
			$$("#ad-search-properties-list input[type=checkbox]").each(function (cb) {
				if (tags.contains(+cb.value)) checked.push(cb);
				else unchecked.push(cb);
			});
			if (checked.length) CheckBoxes.setState(checked,true);
			if (unchecked.length) CheckBoxes.setState(unchecked,false);
		}
		// if no tags supplied - check them all
		else CheckBoxes.setState($$("#ad-search-properties-list input[type=checkbox]"),true);
	},

	// gathers all search data from the form
	// prepares a dictionary
	// { key=type,value=value }
	// key=words, value=csv of all words from search input
	// key=tags, value=csv of all tags from properties input
	_gatherSearchData:function () {
		var terms=[];

		// get from search input
		var searchInputTerms=$("ad-text-search-input").value.trim().split(/\s+/);
		if (searchInputTerms[0]) searchInputTerms.each(function (term) { terms.push(term); });

		// get from property filters
		var tags=[];
		// all tag types list

		//AdSearchBar._gatherSearchData()
		$$("#ad-search-properties-list input[type=checkbox]").each(function (cb) {
			if (cb.checked) tags.push(+cb.value);
			//tags.push(cb.retrieve("label").get("text").trim());
		});

		return {
			terms:terms,
			tags:tags
		};
	}
};
$DL(AdSearchBar.init);

