var _forms = [];
var inputs = new Array();
var selects = new Array();
var radios = new Array();
var checkboxes = new Array();
var buttons = new Array();
var selects = new Array();
var all_selects = false;
var active_select = null;
var agt = navigator.userAgent.toLowerCase();
//this.ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var isMac = is_mac();
var selectText = "please select";


var _timeouts = [];
var _stimeout = 5000000;

var IN_CFORMS = true;

var _heightSelect = 24;
var _border = 1;

function is_mac() {
	if (navigator.appVersion.indexOf("Safari") != -1)
	{
		if(!window.getComputedStyle)
		{
   			return true;
  		}
	}
	return false;
}

function init() {
	if(!document.getElementById) {return false;}
	getElements();
	separateElements();
	replaceSelects();
	//replaceRadios();
	//replaceButtons();
	//replaceCheckboxes();
}

// getting all the required elements
function getElements() {
	for (var nf = 0; nf < document.getElementsByTagName("form").length; nf++) {
		for(var nfi = 0; nfi < document.forms[nf].getElementsByTagName("input").length; nfi++) {
			var tmp = document.forms[nf].getElementsByTagName("input")[nfi];
			if (!tmp.replaced)
			{
				inputs.push(tmp);
			}
		}
		for(var nfs = 0; nfs < document.forms[nf].getElementsByTagName("select").length; nfs++) {
			var tmp = document.forms[nf].getElementsByTagName("select")[nfs];
			if (!tmp.replaced)
			{
				selects.push(tmp);
			}
		}
	}
}

// separating all the elements in their respective arrays
function separateElements() {
	var r = 0; var c = 0; var t = 0; var rl = 0; var cl = 0; var tl = 0; var b = 0;
	for (var q = 0; q < inputs.length; q++) {
		if(inputs[q].type == "radio" && !inputs[q].replaced) {
			radios[r] = inputs[q]; ++r;
		}
		if(inputs[q].type == "checkbox" && !inputs[q].replaced) {
			checkboxes[c] = inputs[q]; ++c;
		}
		if(((inputs[q].type == "submit") || (inputs[q].type == "button")) && !inputs[q].replaced) {
			buttons[b] = inputs[q]; ++b;
		}
	}
}

//replacing radio buttons
function replaceRadios() {
	for (var q = 0; q < radios.length; q++) {
		if (!radios[q].replaced)
		{
			radios[q].className = "outtaHere";
			var radioArea = document.createElement("div");
			if(radios[q].checked) {
				radioArea.className = "radioAreaChecked";
			}
			else
			{
				radioArea.className = "radioArea";
			}
			radioArea.id = "myRadio" + q;
			radios[q].parentNode.insertBefore(radioArea, radios[q]);
			radios[q]._ra = radioArea;
	
			radioArea.onclick = new Function('rechangeRadios('+q+')');
		}
		radios[q].replaced = true;
	}
	return true;
}

//checking radios
function checkRadios(who) {
	var what = radios[who]._ra;
	for(var q = 0; q < radios.length; q++) {
		if((radios[q]._ra.className == "radioAreaChecked")&&(radios[q]._ra.nextSibling.name == radios[who].name))
		{
			radios[q]._ra.className = "radioArea";
		}
	}
	what.className = "radioAreaChecked";
}

//changing radios
function changeRadios(who) {
	if(radios[who].checked) {
		for(var q = 0; q < radios.length; q++) {
			if(radios[q].name == radios[who].name) {
				radios[q].checked = false;
			} 
			radios[who].checked = true; 
			checkRadios(who);
		}
	}
}

//rechanging radios
function rechangeRadios(who) {
	if(!radios[who].checked) {
		for(var q = 0; q < radios.length; q++) {
			if(radios[q].name == radios[who].name)	{
				radios[q].checked = false; 
			}
			radios[who].checked = true; 
			checkRadios(who);
		}
	}
}

//replacing checkboxes
function replaceCheckboxes() {
	for (var q = 0; q < checkboxes.length; q++) {
		if (!checkboxes[q].replaced) {
			checkboxes[q].className = "outtaHere";
			var checkboxArea = document.createElement("div");
			if(checkboxes[q].checked) {
				checkboxArea.className = "checkboxAreaChecked";
			}
			else {
				checkboxArea.className = "checkboxArea";
			}
			checkboxArea.id = "myCheckbox" + q;
			checkboxes[q].parentNode.insertBefore(checkboxArea, checkboxes[q]);
			checkboxes[q]._ca = checkboxArea;
			checkboxArea.onclick = new Function('rechangeCheckboxes('+q+')');
			
			checkboxes[q].onkeydown = checkEvent;
			checkboxes[q].replaced = true;
		}
	}
	return true;
}

//checking checkboxes
function checkCheckboxes(who, action) {
	var what = checkboxes[who]._ca;
	if(action == true) {
		what.className = "checkboxAreaChecked";
		what.checked = true;
	}
	if(action == false) {
		what.className = "checkboxArea";
		what.checked = false;
	}
}

//changing checkboxes
function changeCheckboxes(who) {
	if(checkboxes[who].checked) {
		checkCheckboxes(who, false);
	}
	else {
		checkCheckboxes(who, true);
	} 
}

//rechanging checkboxes
function rechangeCheckboxes(who) {
	var tester = false;
	if(checkboxes[who].checked == true) {
		tester = false;
	}
	else {
		tester = true;
	}
	checkboxes[who].checked = tester;
	checkCheckboxes(who, tester);
}

//check event
function checkEvent(e) {
	if (!e) var e = window.event;
	if(e.keyCode == 32) {for (var q = 0; q < checkboxes.length; q++) {if(this == checkboxes[q]) {changeCheckboxes(q);}}} //check if space is pressed
}

// replacing buttons
function replaceButtons() {
	for (var i = 0; i < buttons.length; i++) {
		if (!buttons[i].replaced)
		{
			// button holder
			var buttonHolder = document.createElement("div");
			buttonHolder.className = "buttonSubmit";
			buttons[i].parentNode.appendChild(buttonHolder);
			
			// left image
			var buttonLeft = document.createElement("span");
			buttonLeft.className = "left";
			buttonHolder.appendChild(buttonLeft);
		
			// append button into holder
			buttonHolder.appendChild(buttons[i]);
		
			//right image
			var buttonRight = document.createElement('span');
			buttonRight.className = "right";
			buttonHolder.appendChild(buttonRight);
			buttons[i].replaced = true;
		}
	}
}

//replacing selects
function replaceSelects() {
	for(var q = 0; q < selects.length; q++) {
	if (!selects[q].replaced && selects[q].offsetWidth)
	{
		selects[q]._number = q;

			//create and build div structure
			var selectArea = document.createElement("div");
		
			var left = document.createElement("span");
			left.className = "left";
			selectArea.appendChild(left);
		
			var disabled = document.createElement("span");
			disabled.className = "disabled";
			selectArea.appendChild(disabled);
		
			selects[q]._disabled = disabled;
		
			var center = document.createElement("span");
			var button = document.createElement("a");
			var text = document.createTextNode(selectText);
			center.id = "mySelectText"+q;
			center.id = "mySelectText"+q;
			center._q = q;

		
			var stWidth = selects[q].offsetWidth;
			selectArea.style.width = stWidth + "px";

			button.href = "javascript:showOptions("+q+")";
			button.onkeydown = selectEvent;
			button.className = "selectButton";
			button._q = q;
			selectArea.className = "selectArea";
			selectArea.className += " " + selects[q].className;
			selectArea.id = "sarea"+q;
			center.className = "center";
			center.appendChild(text);
			selectArea.appendChild(center);
			selectArea.appendChild(button);
		
			//hide the select field
			selects[q].className += " outtaHere";
			//insert select div
			selects[q].parentNode.insertBefore(selectArea, selects[q]);
			//build & place options div

			var optionsDiv = document.createElement("div");
		
			var optionsList = document.createElement("ul");
			optionsDiv.appendChild(optionsList);
			var selectBtmDiv = document.createElement("div");
			selectBtmDiv.innetHTML = '&nbsp;bottom div&nbsp;';
			optionsDiv.appendChild(selectBtmDiv);
		
			selects[q]._options = optionsList;
	
			optionsDiv.style.width = stWidth - (_border*2) + "px";
			optionsDiv._parent = selectArea;
		
			optionsDiv.className = "optionsDivInvisible";
			optionsDiv.id = "optionsDiv"+q;
			optionsDiv._q = q

                        			
			optionsDiv.onmouseover = function()
		{
			if(_timeouts[this._q])
			{
				clearTimeout(_timeouts[this._q]);
			}
		}
                    optionsDiv.onmouseout = function()
                    {
                            _elem = document.getElementById("optionsDiv"+this._q);
                            if(_elem && _elem.className != "optionsDivInvisible")
                                    _timeouts[this._q] = setTimeout('showOptions(' + this._q + ')',_stimeout);
                    }

                    button.onmouseover = optionsDiv.onmouseover;
                    button.onmouseout = optionsDiv.onmouseout;
                    center.onmouseover = optionsDiv.onmouseover;
                    center.onmouseout = optionsDiv.onmouseout;

										var func = null;

										if($(selects[q]).hasClass('countrycountry'))
										{
											func = true;
										}

                    populateSelectOptions(selects[q], func);
                    //selectArea.appendChild(optionsDiv);
                    document.getElementsByTagName("body")[0].appendChild(optionsDiv);
                    selects[q].replaced = true;

                    if(jQuery(selects[q]).hasClass('addclass1'))
                    {
                        jQuery(optionsDiv).addClass('addclass1');
                    }
                    if(jQuery(selects[q]).hasClass('addclass2'))
                    {
                        jQuery(optionsDiv).addClass('addclass2');
                    }
                    if(jQuery(selects[q]).hasClass('addclass3'))
                    {
                        jQuery(optionsDiv).addClass('addclass3');
                    }
		}
	}
	all_selects = true;
}

function myFunc()
{
		var ar = new Array('D&nbsp;-', 'A&nbsp;-', 'CH&nbsp;-');
		var iso = '';
		switch($('#registrationAnbieterFirst_country').val())
		{
			default:
			case "2010":
				iso = ar[0];break;
			case "1942":
				iso = ar[1];break;
			case "2135":
				iso = ar[2];break;
		}

		$('.input12-without-background').html(iso);


		$('#registrationAnbieterFirst_postcode').val('');
		$('#mySelectText2').html('Nicht gefunden');
		$('#optionsDiv2 ul').html('');
		$('#optionsDiv2 ul').append(
			$(document.createElement('li'))
				.append(
					$(document.createElement('a'))
						.html('Nicht gefunden')
						.attr('href', '/')
						.click(function(){
							showOptions(2);
							selectMe("registrationAnbieterFirst_city_id",0,2);
							return false;
						})
				)
		);
		$('#optionsDiv2 ul').css({
			height : 'auto'
		});
}

//collecting select options
function populateSelectOptions(me, func) {
	me._options.innerHTML = "";
	
	for(var w = 0; w < me.options.length; w++) {
		
		var optionHolder = document.createElement('li');
		var optionLink = document.createElement('a');
		var optionTxt = document.createTextNode(me.options[w].text);
		
		optionLink.href = "javascript:showOptions("+me._number+"); selectMe('"+me.id+"',"+w+","+me._number+");";

		if(func)
		{
			optionLink.href = "javascript:showOptions("+me._number+"); selectMe('"+me.id+"',"+w+","+me._number+"); myFunc();";
		}

		optionLink.appendChild(optionTxt);



		optionHolder.appendChild(optionLink);
		me._options.appendChild(optionHolder);
		//check for pre-selected items
		if(me.options[w].selected) {
			selectMe(me.id,w,me._number);
		}
	}
	if (me.disabled) {
		me._disabled.style.display = "block";
	}
	else {
		me._disabled.style.display = "none";
	}
}

//select event
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;
	}
}

//selecting me
function selectMe(selectFieldId,linkNo,selectNo) {
	selectField = selects[selectNo];

	var id = null;
        for(var k = 0; k < selectField.options.length; k++) {
		if(k==linkNo) {
			selectField.options[k].selected = true;
                        id = selectField.options[k].value;
		}
		else {
			selectField.options[k].selected = false;
		}
	}

        if(selectFieldId == 'registrationAnbieterFirst_country')
        {
            if (!id) {
                jQuery('#registrationAnbieterFirst_postcode').attr('disabled', true);
            } else {
                jQuery('#registrationAnbieterFirst_postcode').attr('disabled', false);
                jQuery('#registrationAnbieterFirst_location').attr('disabled', false);
                jQuery('#registrationAnbieterFirst_location').attr('readonly', true);
            }
        } /*else if (selectFieldId == 'drop_country_id') {
            if (id) {
                jQuery('.form_plz').attr('readonly', false);
                jQuery('.form_plz').attr('disabled', false);
            } else {
                jQuery('.form_plz').attr('disabled', true);
                jQuery('.form_plz').attr('readonly', true);
            }
        }*/
	
	//show selected option
	textVar = document.getElementById("mySelectText"+selectNo);
	var newText = document.createTextNode(selectField.options[linkNo].text);
	textVar.replaceChild(newText, textVar.childNodes[0]);
	if (selectField.onchange && all_selects)
	{
		eval(selectField.onchange());
	}
}

//showing options
function showOptions(g) {
        _elem = document.getElementById("optionsDiv"+g);
		if (active_select && active_select != _elem) {
                        jQuery(active_select)
                            .removeClass("optionsDivVisible")
                            .addClass("optionsDivInvisible");
//			active_select.className = "optionsDivInvisible";
			active_select.style.height = "auto";
		}
                if(jQuery(_elem).hasClass("optionsDivInvisible")){
//		if(_elem.className=="optionsDivInvisible") {
			_elem.style.left = "-9999px";
			_elem.style.top = findPosY(_elem._parent) + _heightSelect + 'px';
			
//			_elem.className = "optionsDivVisible";
                        jQuery(_elem)
                            .removeClass("optionsDivInvisible")
                            .addClass("optionsDivVisible");

			if (_elem.offsetHeight > 200)
			{
				_elem.style.height = "200px";
			}
                        _elem.style.left = findPosX(_elem._parent) +'px';

			
			active_select = _elem;

			var ul = jQuery(active_select).find('ul');

			if (200 < parseInt(ul.css('height'))) {
				ul.css('height', 200);
			}
			
            if (!ul.parent().hasClass('.jScrollPaneContainer')) {
              ul.jScrollPane({
                showArrows:true,
                arrowSize: 15
              });
            }
        	
				
		}
                else if(jQuery(_elem).hasClass("optionsDivVisible")) {
//		else if(_elem.className=="optionsDivVisible") {
			_elem.style.height = "auto";
//			_elem.className = "optionsDivInvisible";

                        jQuery(_elem)
                            .removeClass("optionsDivVisible")
                            .addClass("optionsDivInvisible");

		}
		//_elem.onmouseout = hideOptions;
}

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;

jQuery(document).ready(function(){
	if (jQuery('select').length) {
		jQuery(document).mouseup(function(event){
			var opened = jQuery('.optionsDivVisible:visible');
			if (opened.length) {
				jQuery.each(opened, function(i, v){
					v = jQuery(v);
                    
                    var addionWidth = 20;
                    
                    if (jQuery('#request-popup').length && jQuery('#request-popup').is(':visible')) {
                        addionWidth += 22;
                        //console.info('222');
                    } else if (jQuery('.einstellungen-form').length) {
                        addionWidth -= 64;
                    } else if (jQuery('.school_profile_datas').length) {
                        addionWidth -= 20;
                    }
                    
					var elWidth = parseInt(v.css('width')) + addionWidth;
					var elHeight = v.height();
					var elY = findPosY(v.get(0));
					var elX = findPosX(v.get(0));
                    
                    
                    //console.debug(addionWidth);
                    //console.debug(elWidth);
                    //console.debug(elHeight);
                    //console.debug(elY);
                    //console.debug(elX);
                    
                    
					var selectId = v.attr('id').replace('optionsDiv', '');
					if ( (event.pageY > (elY+elHeight)) || event.pageY < (elY-_heightSelect) || (event.pageX < elX) || (event.pageX > (elX+elWidth)) ) {
                        //console.info('CLOSE');
						showOptions(parseInt(selectId));
					}
				});
			}
		});
	}
	
/*    jQuery('#drop_country_id').change(function(){
        if (jQuery(this).val()) {
            jQuery('.form_plz').attr('readonly', false);
            jQuery('.form_plz').attr('disabled', false);
        } else {
            jQuery('.form_plz').attr('disabled', true);
            jQuery('.form_plz').attr('readonly', true);
        }
    });
    
    jQuery('#drop_country_id').change();*/
});
