// Implementation of a Search Manager object which allows the web site to handle
// multiple search options in one place by switching through different search forms

var SearchManager = {
		
	init: function() {
	
		this.element = document.getElementById("search_in");
		this.value = document.getElementById("search_in_value");
		this.label = document.getElementById("search_in_label");
		
		this.formid = "searchform_";
		this.itemid = "search_in_";
		
		this.forms = WebElements.Utils.getElementsByClassName(document, "div", "searchform");
		this.items = WebElements.Utils.getElementsByClassName(document, "div", "select_item");
		
		this.element_focused_classname = "focused";
		this.item_active_classname = "selected";
		this.form_hidden_classname = "hidden";
		
		this.current = 0;
		this.cookie_path = "/";
		this.cookie_name = "SearchManager_current";
		this.use_cookies = true;
		this.focused = false;
		
		var self = this;
		
		WebElements.Utils.addEventListener(this.element, "click", function(){ self.toggleFocus(); });
		
		if(this.use_cookies && WebElements.Utils.getCookie(this.cookie_name) != null) this.current = WebElements.Utils.getCookie(this.cookie_name);
		
		// show the current form
		this.forms[this.current].className = this.forms[this.current].className.replace(this.form_hidden_classname, "");
		
		this.searchIn(this.itemid + this.current);
	},

	searchIn: function(id) {
	
		// set label and hidden field
		this.value.value = id;
		this.label.firstChild.data = document.getElementById(id).firstChild.data;
		
		// unselect the old select item
		this.items[this.current].className = this.items[this.current].className.replace(this.item_active_classname, "");
		// unselect the old form
		this.forms[this.current].className += " " + this.form_hidden_classname;
		
		// set the new selection index
		this.current = parseInt(id.replace(this.itemid, ""));
		
		// select the new select item
		this.items[this.current].className += " " + this.item_active_classname;
		// select the new form
		this.forms[this.current].className = this.forms[this.current].className.replace(this.form_hidden_classname, "");
		
		if(this.use_cookies) WebElements.Utils.setCookie(this.cookie_name, this.current, null, this.cookie_path);
	},
	
	toggleFocus: function() {
		
		if(!this.focused)
		{
			this.element.className += " " + this.element_focused_classname;
			
			this.focused = true;
		}
		else
		{
			this.element.className = this.element.className.replace(this.element_focused_classname, "");
			
			this.focused = false;
		}
	}
}

WebElements.Utils.addLoadEvent(function(){ SearchManager.init(); });
