// Global variables
var sameKeyCnt = 0;
var lastKey;
var scrolled = 0;
var defScrolled = 1;

function getHoverClass() {
	activeId = $(document).find('.active').attr('id');
	hoverClass = "hover";
	if (activeId != undefined) {
		activeList = activeId.substring(3)
		hoverClass = getListHoverClass(activeList);
	}
	return hoverClass;
}

function getListHoverClass(list) {
	hoverClass = "hover";
	if (isCssClassDefined("hover_" + list)) {
		hoverClass = "hover_" + list;
	}
	return hoverClass;
}

function initMouseMoveEvents() {
	$(".dropdown dd ul li").mousemove(function () {
		if (scrolled > 0) {
		scrolled--;
		} else {
			hoverClass = getHoverClass();
			$('.' + hoverClass).removeClass(hoverClass);
			$(this).addClass(hoverClass);
		}
	});
}

var onChangeCallbacks = new Array();

function setOnChangeCallback(select, callbackfn) {
	onChangeCallbacks[select] = callbackfn;
}

function unsetOnChangeCallback(select) {
	onChangeCallbacks[select] = undefined;
}

// Main init function
// Lists in jsArray should be ordered from top to down because of IE z-index bug, so
// we set z-index manualy for each list.
function initCustomLists(jsArray) {
	
	// Keypress support
	$(document).keydown(function (event) {
		if (typeof activeList == 'undefined' || activeList == undefined) {
			return true;
		}
		hoverClass = getHoverClass();
		//alert(hoverClass);
		if (event.keyCode == 38 || event.keyCode == 37) {
			// UP || LEFT
			clid = 'cl_' + activeList; 
			var atag = $("#" + clid).find("." + hoverClass).find('span.value').parent();
			var natag = atag.parent().prev().find('a');
			if (atag.html() == null) {
				natag = $("#" + clid + " dd").find("a").last();
			}
			cnt = 0;
			ctag = $("#" + clid + " dd").find("a").first();
			while (ctag.html() != natag.html()) {
				cnt++;
				ctag = ctag.parent().next().find('a');
			}
			if (natag.html() != null) {
				$('.' + hoverClass).removeClass(hoverClass);
				$(natag).parent().addClass(hoverClass);
				h = $(document).find('.active dd ul li').height();
				$(document).find('#cl_' + activeList + ' dd ul').scrollTop(cnt * h);
				scrolled = defScrolled;
			}
			return false;
		} else if (event.keyCode == 40 || event.keyCode == 39) {
			// DOWN || RIGHT
			clid = 'cl_' + activeList; 
			var atag = $("#" + clid).find("." + hoverClass).find('span.value').parent();
			var natag = atag.parent().next().find('a');
			if (atag.html() == null) {
				natag = $("#" + clid + " dd").find("a").first();
			}
			cnt = 0;
			ctag = $("#" + clid + " dd").find("a").first();
			while (ctag.html() != natag.html()) {
				cnt++;
				ctag = ctag.parent().next().find('a');
			}
			//alert(cnt);
			if (natag.html() != null) {
				$('.' + hoverClass).removeClass(hoverClass);
				$(natag).parent().addClass(hoverClass);
				h = $(document).find('.active dd ul li').height();
				$(document).find('#cl_' + activeList + ' dd ul').scrollTop(cnt * h);
				scrolled = defScrolled;
			}
			return false;
		} else if (event.keyCode == 13) {
			// ENTER
			clid = 'cl_' + activeList; 
			var curtext = $(document).find("." + hoverClass).find('span.value').parent().html();
			var value = $(document).find("." + hoverClass).find('span.value').html();
			//clid = $(document).find("." + hoverClass).parent().parent().parent().attr('id'); 
			//alert(curtext);
			// on click simulation
			if (clid != undefined) {
				$('#' + clid + ' dt a').html(curtext);
				$('#' + clid + ' dd ul').hide();
				$('#' + clid).removeClass('active');
				try {
					$('#' + clid.substring(3)).val(value);
				} catch (err) {
					//IGNORE
				}
				$('#' + clid.substring(3) + '_value').val(value);
				if (onChangeCallbacks[clid.substring(3)] != undefined) {
					onChangeCallbacks[clid.substring(3)](value);
				}
			}
			activeList = undefined;
		} else {
			ch =  String.fromCharCode(event.keyCode).toUpperCase();
			//alert(ch);
			found = false;
			cnt = 0;
			h = $(document).find('.active dd ul li').height();
			//ch = String.fromCharCode(event.charCode).toUpperCase();
			if (ch == lastKey) {
				sameKeyCnt++;
				//alert(sameKeyCnt);
			} else {
				lastKey = ch;
				sameKeyCnt = 0;
			}
			//$(document).find("." + hoverClass).removeClass(hoverClass);
			scnt = sameKeyCnt;
			ff = undefined;
			ft = undefined;
			ae = undefined;
			ftcnt = 0;
			ffcnt = 0;
			$(document).find('.active dd ul li').find(".value").each(function() {
				if (ch == $(this).parent().html().substring(0, 1).toUpperCase() && !found) {
					if (ff == undefined) {
						ff = this;
						ffcnt = cnt;
					}
					if (scnt == 0) {
						ae = $(this).parent().parent();
						found = true;
						ft = this;
						ftcnt = cnt;
					} else {
						scnt--;
						cnt++;
					}
				} else {
					cnt++;
				}
			});
			if (found == false && ff != undefined) {
				ae = $(ff).parent().parent();
				found = true;
				cnt = ffcnt;
				sameKeyCnt = 0;
			}
			if (ft != undefined) {
				cnt = ftcnt;
			}
			if (ae != undefined) {
				$(document).find("." + hoverClass).removeClass(hoverClass);
				ae.addClass(hoverClass);
			}
			if (found) {
				$(document).find('.active dd ul').scrollTop(cnt * h);
				scrolled = defScrolled;
			}
		}
	});
			
			
			
	//MAIN FUNCTION
	(function jSelect(){
		$("td.card .card_select, .periodic_sel").each(function(i,e){ //inserting classes into select stylizer
			var sselID = $(this).attr("id");
			jsArray.push(sselID);
		});

		//z-index:9999;
		zi = 9999;
		$(jsArray).each(function(i,el) {
			$('select#'+el).hide();
			var thiSelect = $('#' + el);
			var selectedVal = thiSelect.find('option:selected');
			var options = $("option", thiSelect);
			
			$('<input type="hidden" value="0" name="' + el + '_value" id="' +  el + '_value" />').insertAfter('select#'+el);
			$('<dl id="cl_'+el+'" class="dropdown"></dl>').insertAfter('select#'+el);
			$('dl#cl_'+el).append('<dt><a onclick="$(this).blur();" href="#">'+ selectedVal.text() +'<span style="display: none;" class="value">' + selectedVal.val() + '</span></a></dt>');
			$('dl#cl_'+el).append('<dd><ul></ul></dd>');
			
			$('#cl_'+el).css('display', 'block');
			$('#cl_'+el).css('z-index', zi);
			zi--;
			
			options.each(function(){
				if ($(this).val() != 0) {
					$('dl#cl_'+el+' dd ul').append('<li><a href="#">'+ $(this).text() +'<span style="display: none;" class="value">'+ $(this).val() +'</span></a></li>');
				}
			});

			$('#cl_'+el+' dd ul li a').live('click', function(){
				var curtext = $(this).html();
				$('#cl_'+el+' dt a').html(curtext);
				$('#cl_'+el+' dd ul').hide();
				$('#cl_'+el).removeClass('active');
				try {
					$('#'+el).val($(this).find('span.value').html());
				} catch (err) {
					//IGNORE
				}
				value = $(this).find('span.value').html();
				$('#' + el + '_value').val(value);
				if (onChangeCallbacks[el] != undefined) {
					onChangeCallbacks[el](value);
				}
				//value = $(this).find('span.value').html();
				//thiSelect.find('value=' + value).attr('selected', 'selected');
				return false;
			});

			$('#cl_'+el+' dt').live('click', function() {
				hoverClass = getHoverClass();
				// Hiding all selected items
				$('.' + hoverClass).removeClass(hoverClass);
				// Hiding other lists then clicked
				$(jsArray).each(function(i,el2){
					if (el2 != el) {
						$('#cl_'+el2).removeClass('active');
						$("#cl_" + el2 + " dd ul").hide();
					}
				});

				if(thiSelect.attr("disabled")===true){
					//$('#cl_'+el+' dt a').addClass("disabled");
					disableList(el);
					return false;
				}

				$('#cl_'+el+' dd ul').toggle();
				if ($('#cl_'+el+' dd ul').is(":visible")) {
					$('#cl_'+el).addClass('active');
				} else {
					$('#cl_'+el).removeClass('active');
					activeList = undefined;
				}

				return false;
			});

			$(document).bind('click', function(e) {
				var $clicked = $(e.target);
				if (!$clicked.parents().hasClass("dropdown")) {
					$(".dropdown dd ul").hide();
				}
				if (!$clicked.parents().hasClass("active")) {
					$(".dropdown").removeClass('active');
					activeList = undefined;
				}
			});

		});

		//DEFAULT INIT
		initMouseMoveEvents();

		$(jsArray).each(function(i,el2){
			$('#cl_'+el2).removeClass('active');
			$("#cl_" + el2 + " dd ul").hide();
		});
	})();
}

function selectValueFromList(list, value) {
	if (value == 0) {
		return false;
	}

	clid = 'cl_' + list;
	hoverClass = getListHoverClass(list);
	curtext = null;
	
	$(document).find('#' + clid + ' dd ul li').find(".value").each(function() {
		if ($(this).html() == value) {
			curtext = $(this).parent().html();
			$(this).parent().parent().addClass(hoverClass);
		} else {
			$(this).parent().parent().removeClass(hoverClass);
		}
	});
	
	if (curtext == null) {
		return false;
	}
	
	$('#' + clid + ' dt a').html(curtext);
	$('#' + clid + ' dd ul').hide();
	$('#' + clid).removeClass('active');
	activeList = undefined;
	try {
		$('#' + clid.substring(3)).val(value);
	} catch (err) {
		//IGNORE
	}
	$('#' + clid.substring(3) + '_value').val(value);
	if (onChangeCallbacks[clid.substring(3)] != undefined) {
		onChangeCallbacks[clid.substring(3)](value);
	}

	return true;
}

function disableList(list) {
	$("#" + list).attr('disabled', true);
	if (isCssClassDefined("disabled_" + list)) {
		$('#cl_' + list +' dt a').addClass("disabled_" + list);
	} else {
		$('#cl_' + list +' dt a').addClass("disabled");
	}
	$('#cl_' + list).removeClass('active');
	activeList = undefined;
	$("#cl_" + list + " dd ul").hide();
}

function enableList(list) {
	$("#" + list).attr('disabled', false);
	if (isCssClassDefined("disabled_" + list)) {
		$('#cl_' + list +' dt a').removeClass("disabled_" + list);
	} else {
		$('#cl_' + list +' dt a').removeClass("disabled");
	}
	//$('#cl_' + list).removeClass('active');
	//$("#cl_" + list + " dd ul").hide();
}

function clearList(list, defTitle) {
	$('#cl_' + list).children('dd').children('ul').empty();
	$('#' + list).empty();
	// Adding select field
	$('#' + list).append('<option value="0">' + defTitle + '</option>');
	$('#cl_' + list).children('dt').html('<a onclick="$(this).blur();" href="#">' + defTitle + '<span class="value">0</span></a>');
	if ($("#" + list).attr('disabled')) {
		if (isCssClassDefined("disabled_" + list)) {
			$('#cl_' + list +' dt a').addClass("disabled_" + list);
		} else {
			$('#cl_' + list +' dt a').addClass("disabled");
		}
		$('#cl_' + list).removeClass('active');
	}
	$('#' + list + "_value").val("0");
}

function repopulateList(list, defTitle, src, callbackfn) {
	if (typeof src == 'string') {
		repopulateListByAjaxJsonCall(list, defTitle, src, callbackfn);
	} else {
		repopulateListFromArray(list, defTitle, src, callbackfn);
	}
}

function repopulateListFromArray(list, defTitle, items, callbackfn) {
	disableList(list);
	clearList(list, defTitle);
	if ($("#" + list + "_loading") != null) {
		$("#" + list + "_loading").show();
	}
	$.each(items, function(i,item){
		$('#' + list).append('<option value="' + item.value + '">' + item.title + '</option>');
	$('#cl_' + list).children('dd').children('ul').append('<li><a href="#">' + item.title + '<span class="value">' + item.value + '</span></a></li>');
	});
	initMouseMoveEvents();
	if ($("#" + list + "_loading") != null) {
		$("#" + list + "_loading").hide();
	}
	initMouseMoveEvents();
	enableList(list);
	if (callbackfn != undefined) {
		callbackfn(list);
	}
}

function repopulateListByAjaxJsonCall(list, defTitle, url, callbackfn) {
	disableList(list);
	clearList(list, defTitle);
	if ($("#" + list + "_loading") != null) {
		$("#" + list + "_loading").show();
	}
	$.getJSON(url, function(items) {
		$.each(items, function(i,item){
			$('#' + list).append('<option value="' + item.value + '">' + item.title + '</option>');
			$('#cl_' + list).children('dd').children('ul').append('<li><a href="#">' + item.title + '<span class="value">' + item.value + '</span></a></li>');
		});
		initMouseMoveEvents();
		if ($("#" + list + "_loading") != null) {
			$("#" + list + "_loading").hide();
		}
		enableList(list);
		if (callbackfn != undefined) {
			callbackfn(list);
		}
	});
}

function isCssClassDefined(c) {
    /*
	if (!document.styleSheets) return false;
	if (typeof c == 'string') c = RegExp('\\b' + c + '\\b','i'); // IE capitalizes html selectors 

	var A, S, DS= document.styleSheets, n= DS.length, SA= [];
	while(n){
	S= DS[--n];
	A= (S.rules)? S.rules: S.cssRules;
	for(var i= 0, L= A.length; i<L; i++){
		tem= A[i].selectorText? [A[i].selectorText, A[i].style.cssText]: [A[i]+''];
		if (c.test(tem[0])) {
			return true;
		}
	}
	}
    */
	return false;
}
