/*#############################################################
Name: Niceforms
Version: 1.0
Author: Lucian Slatineanu
URL: http://www.badboy.ro/

#############################################################*/

//Global Variables
var niceforms = document.getElementsByTagName('form');
var selects = new Array();
var selectText = "Kérjük válasszon!";
var agt = navigator.userAgent.toLowerCase();
this.ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var isMac = new RegExp('(^|)'+'Apple'+'(|$)');

//Theme Variables - edit these to match your theme
var selectRightSideWidth = 21;
var selectLeftSideWidth = 8;
var selectAreaHeight = 16;
var selectAreaOptionsOverlap = 2;
var imagesPath = "images/";

//Initialization function - if you have any other 'onload' functions, add them here
function init() {
	if(!document.getElementById) {return false;}
	getElements();
	replaceSelects();
}


//getting all the required elements
function getElements() {
	var re = new RegExp('(^| )'+'niceform'+'( |$)');
	for (var nf = 0; nf < document.getElementsByTagName('form').length; nf++) {
		if(re.test(niceforms[nf].className)) {
			for(var nfs = 0; nfs < document.forms[nf].getElementsByTagName('select').length; nfs++) {selects.push(document.forms[nf].getElementsByTagName('select')[nfs]);}
		}
	}
}
//separating all the elements in their respective arrays

function replaceSelects() {
    for(var q = 0; q < selects.length; q++) {
		//create and build div structure
		var selectArea = document.createElement('div');
		var left = document.createElement('div');
		var right = document.createElement('div');
		var center = document.createElement('div');
		var button = document.createElement('a');
		var text = document.createTextNode(selectText);
		center.id = "mySelectText_"+selects[q].id;
		var selectWidth = parseInt(selects[q].className.replace(/width_/g, ""));
		center.style.width = selectWidth - 10 + 'px';
		selectArea.style.width = selectWidth + selectRightSideWidth + selectLeftSideWidth + 'px';
		button.style.width = selectWidth + selectRightSideWidth + selectLeftSideWidth + 'px';
		button.style.marginLeft = - selectWidth - selectLeftSideWidth + 'px';
		button.href = "javascript:showOptions('"+selects[q].id+"')";
		button.onkeydown = selectEvent;
		button.className = "selectButton"; //class used to check for mouseover
		selectArea.className = "selectArea";
		selectArea.id = "sarea"+selects[q].id;
		left.className = "left";
		right.className = "right";
		center.className = "center";
		right.appendChild(button);
		center.appendChild(text);
		selectArea.appendChild(left);
		selectArea.appendChild(right);
		selectArea.appendChild(center);
		//hide the select field
        selects[q].style.display='none'; 
		//insert select div
		selects[q].parentNode.insertBefore(selectArea, selects[q]);
		//build & place options div
		var optionsDiv = document.createElement('div');
		optionsDiv.style.width = selectWidth + 14 + 'px';
		optionsDiv.className = "optionsDivInvisible";
		optionsDiv.id = "optionsDiv_"+selects[q].id;
		optionsDiv.style.left = findPosX(selectArea) + 'px';
		optionsDiv.style.top = findPosY(selectArea) + selectAreaHeight - selectAreaOptionsOverlap + 'px';
		//get select's options and add to options div
		for(var w = 0; w < selects[q].options.length; w++) {
			var optionHolder = document.createElement('p');
			var optionLink = document.createElement('a');
			var optionTxt = document.createTextNode(selects[q].options[w].text);
            
            if (selects[q].id=='link') {
                optionLink.href = "javascript:document.location.href='"+selects[q].options[w].value+"';";
            }          
            else if (selects[q].id=='link2') {
                optionLink.href = "javascript:document.currForm.link2.value='"+selects[q].options[w].value+"';document.currForm.submit();";
            }
            else if (selects[q].id=='link4') {
                optionLink.href = "javascript:document.currForm.link4.value='"+selects[q].options[w].value+"';document.currForm.submit();";
            }            
            else if (selects[q].id=='link5') {
                optionLink.href = "javascript:document.currForm.link5.value='"+selects[q].options[w].value+"';document.currForm.submit();";
            }
            else if (selects[q].id=='link8') {
                optionLink.href = "javascript:document.currForm.link8.value='"+selects[q].options[w].value+"';document.currForm.submit();";
            }          			
            else {
                optionLink.href = "javascript:showOptions('"+selects[q].id+"'); selectMe('"+selects[q].id+"',"+w+",'"+selects[q].id+"');";
            }			
			//optionLink.href = "javascript:showOptions("+q+"); selectMe('"+selects[q].id+"',"+w+","+q+");";
			optionLink.appendChild(optionTxt);
			optionHolder.appendChild(optionLink);
			optionsDiv.appendChild(optionHolder);
			//check for pre-selected items
			if(selects[q].options[w].selected) {selectMe(selects[q].id,w,selects[q].id,true);}
		}
		//insert options div
		document.getElementsByTagName("body")[0].appendChild(optionsDiv);
	}
}
function showOptions(g) {
		elem = document.getElementById("optionsDiv_"+g);
		if(elem.className=="optionsDivInvisible") {elem.className = "optionsDivVisible";}
		else if(elem.className=="optionsDivVisible") {elem.className = "optionsDivInvisible";}
		elem.onmouseout = hideOptions;
}
function hideOptions(e) { //hiding the options on mouseout
	if (!e) var e = window.event;
	var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
	//if(((reltg.nodeName != 'A') && (reltg.nodeName != 'DIV')) || ((reltg.nodeName == 'A') && (reltg.className=="selectButton") && (reltg.nodeName != 'DIV'))) {this.className = "optionsDivInvisible";};
	if(((reltg.nodeName != 'A') && (reltg.className != 'optionsDivVisible')) || ((reltg.nodeName == 'A') && (reltg.className=="selectButton"))) {this.className = "optionsDivInvisible";};
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}
function resetFilter(filterId, filterName, resetButton)
{
	if (!filterId || !filterName) return;
	
	var el = $('filter_'+filterId);
	var els = el.getElements('input');
	for (var i = 0; i < els.length; i++)
	{
		var elType = els[i].type;
		switch (elType)
		{
			case 'radio':
			case 'checkbox':
				els[i].checked = false;
				break;
				
			case 'text':
				els[i].value = '';
				break;
				
			case 'hidden':
				els[i].value = '';
				break;
		}
	}
	
	var lnks = el.getElements('a');
	for (var i = 0; i < lnks.length; i++)
	{
		if (lnks[i].className == 'filter_link_active')
		{
			lnks[i].className = "filter_link";
		}
	}
	
	eval("document.filterForm."+filterName+".value = '';");
	
	if (resetButton)
	{
		var sels = el.getElements('select');
		for (var i = 0; i < sels.length; i++)
		{
			selectMe(sels[i].id, 0, sels[i].id);
		}
		
		if (resetButton != 's') resetButton.setStyle('display', 'none');
	}
	
	return true;
}
function setFilterValue(filterType, oper, elName, elValue, linkEl)
{
	if (elName.indexOf("{") > -1) return;
	if (!firstRun[elName] && filterType == 'select')
	{
		firstRun[elName] = 1;
		return;
	}
	elValue = document.getElementById(elValue).options[document.getElementById(elValue).selectedIndex].value;
	eval("var elTemp = document.filterForm."+elName);
	if (navigator.appName == "Microsoft Internet Explorer") {
		var elParent = elTemp.offsetParent;
	} else {
		var elParent = elTemp.getParent();
	}
	var filterId = elParent.id.substring(elParent.id.indexOf("_")+1);
	
	if (filterType == "check")
	{
		if (oper) elTemp.value += ","+elValue;
		else
		{
			var tempValue = elTemp.value.split(",");
			var newValue = tempValue.erase(elValue);
			elTemp.value = newValue.join(",");
		}
	}
	else
	{
		if (linkEl && filterType == 'link')
		{
			resetFilter(filterId, elName, 's');
			linkEl.className = 'filter_link_active';
		}
		else resetFilter(filterId, elName);
		elTemp.value = elValue;
	}
	
	var els = elParent.getElements('div');
	for (var i = 0; i < els.length; i++)
	{
		if (els[i].className == 'resetFilter')
		{
			els[i].setStyle('display', 'block');
			break;
		}
	}
	
	//if (formSubmit) document.filterForm.submit();
}

function selectMe(selectFieldId,linkNo,selectNo,noRun) {
	//feed selected option to the actual select field
	selectField = document.getElementById(selectFieldId);
	var nText = selectField.options[linkNo].text;
	for(var k = 0; k < selectField.options.length; k++) {
		if (k==linkNo) {
			selectField.options[k].selected = true;
			if (selectField.options[k].value && selectField.options[k].value != '0')
			{
				if (!noRun)
				{
					if (selectFieldId == "county_select") showCities(selectField.options[k].value);
					if (selectFieldId == "city_select") showShops(selectField.options[k].value);
				}
			}
		}
		else {
			selectField.options[k].selected = false;
		}
	}
	//show selected option
	textVar = document.getElementById("mySelectText_"+selectNo);
	var newText = document.createTextNode(nText);
	textVar.replaceChild(newText, textVar.childNodes[0]);
	if (selectField.title) {
		var tl = selectField.title.split('|');
		//for (var i=0; i<tl.length; i++) alert(i+': '+tl[i]);
		setFilterValue(tl[0], tl[1], tl[2], tl[3], tl[4]);
    };
}
function selectEvent(e) {
	if (!e) var e = window.event;
	var thecode = e.keyCode;
	switch(thecode){
		case 40: //down
			var fieldId = this.parentNode.parentNode.id.replace(/sarea/g, "");
			var linkNo = 0;
			for(var q = 0; q < selects[fieldId].options.length; q++) {if(selects[fieldId].options[q].selected) {linkNo = q;}}
			++linkNo;
			if(linkNo >= selects[fieldId].options.length) {linkNo = 0;}
			selectMe(selects[fieldId].id, linkNo, fieldId);
			break;
		case 38: //up
			var fieldId = this.parentNode.parentNode.id.replace(/sarea/g, "");
			var linkNo = 0;
			for(var q = 0; q < selects[fieldId].options.length; q++) {if(selects[fieldId].options[q].selected) {linkNo = q;}}
			--linkNo;
			if(linkNo < 0) {linkNo = selects[fieldId].options.length - 1;}
			selectMe(selects[fieldId].id, linkNo, fieldId);
			break;
		default:
			break;
	}
}

//Useful functions
function findPosY(obj) {
	var posTop = 0;
	while (obj.offsetParent) {posTop += obj.offsetTop; obj = obj.offsetParent;}
	return posTop;
}
function findPosX(obj) {
	var posLeft = 0;
	while (obj.offsetParent) {posLeft += obj.offsetLeft; obj = obj.offsetParent;}
	return posLeft;
}

window.onload = init;