/*
*@package EnvisioNext javascript library
*@subpackage Input helper
*@copyright (C) 2007 EnvisioNext.com  <support@EnvisioNext.com>
*@author Anton Zavidov <anton.zavidov@envisionext.com.ua>
*/

/* Register base class*/
InputHelper = new Object;
/* Register configuration object*/
var input_helper = new Object;
 
/* Base class*/
InputHelper = function ()
{

	addedClass = "clearfix";
	
	if(typeof input_helper != "object") {
		return false;
	}
	
	/* Get parent node*/
	this.p = function(element, count)
	{
		while (count > 0) {
			count--;
			element = element.parentNode;
		}
		return element;
	}
	
	/* Strip spacers*/
	this.strip = function(element)
	{
		tmp = $(input_helper[element].textFieldId).value; 
		/*tmp = $('input_helper_asist').value; */
		return tmp;
		
		while(tmp.substr(tmp.length-1,tmp.length) == " ") {
			tmp = tmp.substr(0,tmp.length-1);
		}
		while(tmp.substr(0,1) == " ") {
			tmp = tmp.substr(1,tmp.length);
		}
		var reg1 = '  ';
		tmp = tmp.replace(reg1, ' ');
		return tmp;
	}
	
	/* updateInput*/
	this.updateInput = function (element, s, isChecked){
		while (element.nodeName != "DIV") {
			element = element.parentNode;
		}
		var inputField = $(input_helper[element.id].textFieldId);
		var checkboxes = $$("#" + element.id + " input");
		/*var checkboxes=$$('input[rel]');
		var inputField=$('input_helper_asist');	*/
					
		var similarIsOn=false;
		var itemtext ="";
		
		var start=inputField.value.toLowerCase().indexOf(s.toLowerCase());
		if (start>-1){		/*if such value is found, then if not checked - remove	*/
			if (!isChecked){	/*to remove a substring from a string	*/
				/*similarIsOn	*/
				checkboxes.each(function(item){
					if (item.checked){
						itemtext = (navigator.userAgent.indexOf("MSIE")>-1) ? this.p(item,1).innerText : this.p(item,1).textContent;
						itemtext = (itemtext.indexOf(" ") > 0) ? '"' + itemtext + '"' : itemtext;/*read the text near checkboxes*/
						if (itemtext.indexOf(s)>-1){	/*such string is found*/
							similarIsOn=true;
						}	  
					}
				});	
				if (!similarIsOn || (similarIsOn == true && s == "Anal")){/* if there's no such text among checked */
					var reg1 = new RegExp(",*" + s,"i");
					var reg2 = new RegExp("^,*|,*$","i");
					var v = (" "+inputField.value).replace(reg1, '');
					inputField.value = v.substr(1,v.length);
					inputField.value = inputField.value.replace(reg2, '');
					inputField.value = this.strip(element.id);
					/*setTimeout(function(){
						if ($('input_helper_asist').value == "Anal") {
							$('input_helper_asist').value = ""
						}
					},100)*/
				} 
			}
		}	
		else{  /*if such value isn't found, if checked - add*/
			if (isChecked){	/*to add a substring to the string	*/
				if(inputField.value == '') {
					inputField.value+=s;
				} else {
					inputField.value+="," + s;
				}
				
			} 
		}
		
	}
	
	/* Check opened*/
	this.checkOpened = function(element)
	{
		for(var c=0; c<element.childNodes.length; c++) {
			if(element.childNodes[c].nodeName == "LI") {
				for (var n = 0; n < element.childNodes[c].childNodes.length; n++) {
					if (element.childNodes[c].childNodes[0].checked == true) {
						return true;
					}
				}
			}
		}
		return false;
	}
	
	/* Registration event handlers*/
	this.checks = {
  		keywordEvent: function(event, element)
		{
			Event.stop(event);
			var rootUl = $$("#" + element + " ." + element + "_root")[0];
			if (!input_helper[i].setOpen) {
				input_helper[i].setOpen = true;
				var ff = $(input_helper[i].formField)
				ff.className = "active open_list "+addedClass;
				rootUl.style.display = "block";
				var checkboxes = $$("#" + element + " input");
				var tmp = "*" + $(input_helper[element].textFieldId).value;
				for (var c = 0; c<checkboxes.length; c++) {
					if (checkboxes[c].type == "checkbox" && checkboxes[c].className != "checkAll") {
						var reg = (navigator.userAgent.indexOf("MSIE")>-1) ? this.p(checkboxes[c],1).innerText.substr(0, this.p(checkboxes[c],1).innerText.length) : this.p(checkboxes[c],1).textContent;
						reg = escape(reg);
						checkboxes[c].checked = (tmp.toLowerCase().search(reg.toLowerCase())>0) ? true : false;
					}
				}
				var tmpA = (navigator.appName == "Microsoft Internet Explorer") ? 1 : 2;
				for (var r=0; r<rootUl.childNodes.length; r++) {
					if(rootUl.childNodes[r].tagName == "LI") {
						rootUl.childNodes[r].style.display = "block";
						if(rootUl.childNodes[r].childNodes.length > tmpA) {
							if (rootUl.childNodes[r].childNodes[1].tagName == "UL") {
								if (rootUl.childNodes[r].childNodes[1].style.display == "none") {
									rootUl.childNodes[r].className = rootUl.childNodes[r].className.replace(/expand/, "collapse");
								}
							}
						}
					}
				}
			} else {
				input_helper[i].setOpen = false;
				$(input_helper[i].formField).className = "active "+addedClass;
				rootUl.style.display = "none";
				for (var r=0; r<rootUl.childNodes.length; r++) {
					if(rootUl.childNodes[r].tagName == "LI") {
						rootUl.childNodes[r].style.display = "none";	
					}
				}
			}
			if (!window.firstOpenKeywords) {
				$A(rootUl.select('.toggler')).each(function(span){
					clickOnElem(span);
				});
				window.firstOpenKeywords = true;
			}
		},
		aEvent: function(event, element)
		{
			var parent = this.p(element,1).childNodes[1];
			if (!window[this.p(element,1).childNodes[1].id] || typeof window[this.p(element,1).childNodes[1].id] == "object") {
				window[this.p(element,1).childNodes[1].id] = true;
				parent.style.display = "block";
				this.p(element,1).className = this.p(element,1).className.replace(/collapse/, "expand");
				this.p(element,1).className = this.p(element,1).className.replace(/opened/, "");
				for (var r=0; r<parent.childNodes.length; r++) {
					if(parent.childNodes[r].tagName == "LI") {
						parent.childNodes[r].style.display = "block";
					}
				}
				
			} else {
				window[this.p(element,1).childNodes[1].id] = false;
				parent.style.display = "none";
				this.p(element,1).className = this.p(element,1).className.replace(/expand/, "collapse");
				for (var r=0; r<parent.childNodes.length; r++) {
					if(parent.childNodes[r].tagName == "LI") {
						parent.childNodes[r].style.display = "none";
					}
				}
				var checkboxes = $$("#" + element.parentNode.childNodes[1].id + " input");
				for (var c = 0; c<checkboxes.length; c++) {
					if (checkboxes[c].type == "checkbox" && checkboxes[c].className != "checkAll" && checkboxes[c].checked == true) {
						this.p(checkboxes[c],1).style.display = "block";
						this.p(checkboxes[c],2).style.display = "block";
						this.p(checkboxes[c],3).style.display = "block";
						this.p(checkboxes[c],3).className = this.p(checkboxes[c],3).className.replace(/collapse/, "expand");
						if(checkboxes[c].checked){
							this.p(checkboxes[c],4).style.display = "block";
							if(this.p(element,1).className.indexOf("opened")<0) {
								this.p(element,1).className += " opened";
							}
						} else {
							this.p(checkboxes[c],4).style.display = "none";
						}
					}
				}
			}
			Event.stop(event);
		},
		checkLi: function (event, element)
		{
			element.checked = (element.checked) ? false : true;
			var thisAll = $$("#" + this.p(element,2).id + " .checkAll");
			var full = $$(".checkFull");
			if(element.checked != true)
			{
				thisAll[0].checked = false;
				full[0].checked = false;
				if (this.p(element,3).className.indexOf("opened")>0) {
					this.p(element,1).style.display = "none";
					if(!this.checkOpened(this.p(element,2))) {
						var tmp = this.p(element,3).className.split(" ");
						this.p(element,3).className = tmp[0] + " collapse";
						this.p(element,2).style.display = "none";
					}
				}
			}
			var text = elContent(this.p(element,1));
			text = (text.indexOf(" ") > 0) ? '"' + text + '"' : text;
			this.updateInput(element,text,element.checked);
		},
		checkAllLi: function (event,element)
		{
			element.checked = (element.checked) ? false : true;
			if(!element.checked) {
				$$(".checkFull")[0].checked = false;
			}
			var ul = this.p(element,2);
			if (ul.id != "null") {
				var checkboxes = $$("#" + ul.id + " input");
				for (var c = 0; c<checkboxes.length; c++) {
					if (checkboxes[c].type == "checkbox" && (checkboxes[c].className != "checkAll" || this.p(element,2).className == ul.parentNode.id + "_root")) {
						checkboxes[c].checked = element.checked;
						if (element.checked) {
							if (this.p(checkboxes[c],1).style.display != "block") {
								if(this.p(checkboxes[c],3).className.indexOf("opened")<0) {
									this.p(checkboxes[c],3).className += " opened";
								}
								this.p(checkboxes[c],2).style.display = "block";
								if(checkboxes[c].className != "checkAll"){
									this.p(checkboxes[c],1).style.display = "block";
								}
							}
						} else {
							if (this.p(checkboxes[c],1).style.display == "block") {
								if(this.p(checkboxes[c],3).className.indexOf("opened")>0) {
									this.p(checkboxes[c],1).style.display = "none";
									if(!this.checkOpened(this.p(checkboxes[c],2))) {
										this.p(checkboxes[c],3).className = this.p(checkboxes[c],3).className.split(" ")[0] + " collapse";
										this.p(checkboxes[c],2).style.display = "none";
									}
								}
							}
							if(element.className == "checkAll checkFull")
							{
								var splited = this.p(checkboxes[c],3).className.split(" ");
								if(splited[splited.length-1] == "opened")
								{
									this.p(checkboxes[c],3).className = splited[0] + " collapse";
									this.p(checkboxes[c],2).style.display = "none";
								}
							}
						}
					var text = elContent(this.p(checkboxes[c],1));
					text = (text.indexOf(" ") > 0) ? '"' + text + '"' : text;
					/* Check All */
					if (text.indexOf('"Check All"')>-1)
						text=text.substring(0,text.indexOf('"Check All"'))+text.substring(text.indexOf('"Check All"')+11);
					
					if (element.checked == true) {
					this.updateInput(checkboxes[c],text,element.checked);
					} else if (element.checked == false){
						this.updateInput(checkboxes[c],text,element.checked);
						//$('input_helper_asist').value = "";
					}
					
					
					
					}
				}
			} 
		},
		changeEvent: function (event,element)
		{
			var checkboxes = $$("#" + element + " input");
			var tmp = "*" + this.strip(element);
			for (var c = 0; c<checkboxes.length; c++) {
				if (checkboxes[c].type == "checkbox" && checkboxes[c].className != "checkAll" && checkboxes[c].className != "checkAll checkFull") {
					var reg = (navigator.appName == "Microsoft Internet Explorer") ? this.p(checkboxes[c],1).innerText.substr(0, this.p(checkboxes[c],1).innerText.length-1) : this.p(checkboxes[c],1).textContent;
					if(tmp.toLowerCase().indexOf(reg.toLowerCase())>0) {
						checkboxes[c].checked = true;
						if (this.p(checkboxes[c],1).style.display != "block") {
							if(this.p(checkboxes[c],3).className.indexOf("opened")<0) {
								this.p(checkboxes[c],3).className += " opened";
							}
							this.p(checkboxes[c],2).style.display = "block";
							this.p(checkboxes[c],1).style.display = "block";
						}
					} else {
						checkboxes[c].checked = false;
						if (this.p(checkboxes[c],1).style.display == "block") {
							if(this.p(checkboxes[c],3).className.indexOf("opened")>0) {
								this.p(checkboxes[c],1).style.display = "none";
								if(!this.checkOpened(this.p(checkboxes[c],2))) {
									this.p(checkboxes[c],3).className = this.p(checkboxes[c],3).className.split(" ")[0] + " collapse";
									this.p(checkboxes[c],2).style.display = "none";
								}
							}
						}
					}
				}
			}
		}
	}
	/* Registration support object*/
	for (var i in input_helper) {
		input_helper[i].setFocus = false;
		input_helper[i].setOpen = false;
		Event.observe($(input_helper[i].keywordButtonId),'click',this.checks.keywordEvent.bindAsEventListener(this,i));
		Event.observe($(input_helper[i].formField),'change',this.checks.changeEvent.bindAsEventListener(this,i));
		Event.observe($(input_helper[i].formField),'mouseover',function(){
			try{
				if($(input_helper[i].formField).className == "passive "+addedClass) {
					$(input_helper[i].formField).className = "active "+addedClass;
				}
			}catch(e){}
		});
		Event.observe($(input_helper[i].formField),'mouseout',function(){
			try{
				if(!input_helper[i].setFocus && !input_helper[i].setOpen){
				$(input_helper[i].formField).className = "passive "+addedClass;
			}
			}catch(e){}
		});
		Event.observe($(input_helper[i].textFieldId),'focus',function(){
			try{
				$(input_helper[i].formField).className = "active";
			input_helper[i].setFocus = true;
			
			}catch(e){}
		});
		Event.observe($(input_helper[i].textFieldId),'blur',function(){
			try{
				if (!input_helper[i].setOpen) {
				$(input_helper[i].formField).className = "passive";
			}
			input_helper[i].setFocus = false;
			
			}catch(e){}
		});
		var expanders = $$(" .toggler");	  /* togglers - categories, sexual etc.*/
		for (var a = 0; a<expanders.length; a++) {
			Event.observe(expanders[a],'click',this.checks.aEvent.bindAsEventListener(this,expanders[a]));
		}
		var uls = $$("#" + i + " ul");
		for (var u = 0; u<uls.length; u++) {
			if (uls[u].parentNode.id == i) {
				uls[u].className = i + "_root";
				uls[u].id = i + "_" + u;
				for(var ils = 0; ils<uls[u].childNodes.length; ils++)
				{
					if(uls[u].childNodes[ils].tagName == "LI") {
						uls[u].childNodes[ils].className = i + "_first_item collapse";
					}
				}
				new Insertion.Bottom(uls[u],'<li class="' + i + '_first_item all collapse"><input type="checkbox" class="checkAll checkFull" rel="noChange">Check All</li>');

function elContent (el){
	var result;
	if (navigator.userAgent.indexOf("MSIE")>-1){
		result=el.innerText;
	}
	else{
		result=el.textContent;
	}
	return result;
}
	Event.observe(uls[u].childNodes[ils],'click',this.checks.checkAllLi.bindAsEventListener(this,uls[u].childNodes[ils].childNodes[0]));
			} else {
				uls[u].className = i + "_folder";
				uls[u].id = i + "_" + u;
				for(var ils = 0; ils<uls[u].childNodes.length; ils++)
				{
					if(uls[u].childNodes[ils].tagName == "LI") {
						uls[u].childNodes[ils].className = i + "_element";
						new Insertion.Top(uls[u].childNodes[ils],'<input type="checkbox" rel="noChange">');
						Event.observe(uls[u].childNodes[ils],'click',this.checks.checkLi.bindAsEventListener(this,uls[u].childNodes[ils].childNodes[0]));
						Event.observe(uls[u].childNodes[ils].childNodes[0],'click',function (event){
							element = Event.element(event);
							element.checked = (element.checked) ? false : true;
						});
					}
				}
				new Insertion.Bottom(uls[u],'<li class="' + i + '_element all"><input type="checkbox" class="checkAll" rel="noChange">Check All</li>');
				Event.observe(uls[u].childNodes[ils],'click',this.checks.checkAllLi.bindAsEventListener(this,uls[u].childNodes[ils].childNodes[0]));
			}
		}
		var checkAll = $$("#" + i + " input.checkAll");
		for (var c = 0; c<checkAll.length; c++) {
			Event.observe(checkAll[c],'click',function (event){
				element = Event.element(event);
				element.checked = (element.checked) ? false : true;
			});
		}
	}
/*alert("init");*/
findAndCheck();	
}
var InputHelperInit = function()
{
	setTimeout(InputHelper,300);
}
document.observe("dom:loaded", function() {
	InputHelperInit();
});

/*var flagOpened=false;*/
function findAndCheck(){
	var tempstr;
	if ($("input_helper_asist").value==" ")	$("input_helper_asist").value="";
	if ($("input_helper_asist").value!=""){
		
		while($("input_helper_asist").value.charAt($("input_helper_asist").value.length-1)==" ")
		{
			$("input_helper_asist").value = $("input_helper_asist").value.substring(0,$("input_helper_asist").value.length-1);
		}
		
		tempstr=$("input_helper_asist").value;
		
		/* deleting all spaces at the end of the search string*/
		var keywords=tempstr.split(/\s/);
		keywords=keywords.without(" ");
		var lis=$A($$(".input_helper_div_element"));
		keywords.each(function(keyword){
			lis.each(function(item){
			if(!item.hasClassName('all'))/*excluding elements which are "Check All"*/
			{
			  var itemVal = item.innerHTML.substring(item.innerHTML.indexOf('>')+1);
				 if (itemVal.toLowerCase().indexOf(keyword.toLowerCase())>-1){
					item.down("input").checked=true;
					item.style.display="block";
					item.up().style.display="block";
					item.up().up().removeClassName("collapse");
					item.up().up().addClassName("expand");
					item.up().up().addClassName("opened");
				 }
			}
			});	
		});
	 
		/* generate event click on the Keywords button to expand the needed categories */
		/*if (!$('input_helper_form_field').hasClassName('open_list')!flagOpened){*/
		if ($('input_helper_div_0').style.display!="block"/*!flagOpened*/){	
			/*alert($('input_helper_div_0').getAttribute("style")+'=closed. opening...');*/
			clickOnKeyword();		
			/*flagOpened=true;	*/
		}
		/*if no space at the end - we add it*/
		if ($("input_helper_asist").value.charAt($("input_helper_asist").value.length-1)!=" ")
			$("input_helper_asist").value+=" ";	
		if ($("input_helper_asist").value==" ")
			$("input_helper_asist").value="";
	}
}

function keyPressSpace(evt){
	var evt = (evt) ? evt : (window.event) ? event : null;
	var keyCode = evt.keyCode ? evt.keyCode : evt.charCode ? evt.charCode :	evt.which ? evt.which : void 0;
	if (keyCode==32){
		/*alert("space");*/
		findAndCheck();
		$("input_helper_asist").value=$("input_helper_asist").value.substr(0,$("input_helper_asist").value.length-1); /*delete last space*/
	}
}

function clickOnKeyword(){/* emulating click only when list is closed*/
	if (navigator.userAgent.indexOf("MSIE")>=0){
			$("input_helper_start").fireEvent("onclick");		/*ie*/
	}
	else{
		var evt = document.createEvent("MouseEvents");		/*ff*/
	  	evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
		$("input_helper_start").dispatchEvent(evt);
	}
}

function clickOnElem(elm){/* emulating click only when list is closed*/
	if (navigator.userAgent.indexOf("MSIE")>=0){
		elm.fireEvent("onclick");		/*ie*/
	}
	else{
		var evt = document.createEvent("MouseEvents");		/*ff*/
	  	evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
		elm.dispatchEvent(evt);
	}
}

