$(document).ready(function() {
	var KEY = {
		RETURN: 13,
		ESC: 27,
		DOWN: 38,
		UP: 40,
		ESC: 27
	};
	$("#alege")
		//Binds keyup event on the input
		.keyup(function(e) {	
			var ev = e || window.event;
			ev.preventDefault();
			switch (ev.keyCode) {
				case KEY.RETURN:
					if ($('#citySuggestion').hasClass("opened") && $('#citySuggestion li.active').length) {
						$('#citySuggestion li.active').click();						
					}										
					return false;
					break;
				case KEY.ESC:	
					$(this).trigger("listclose");
					break;
				case KEY.DOWN:moveCursor(ev.keyCode);break;
				case KEY.UP:moveCursor(ev.keyCode);break;
				default:
					city_search();
					break;
			}

			e.preventDefault();
		})
		//Binds a listclose custom event on the input
	    .bind("listclose", function() {
			$(document).unbind("mousedown");
			$('#citySuggestion').hide().removeClass("opened");
			ieShowSelects();
		})
		//Binds focus event on the input
		.focus(function() {
			$('#citySuggestion')
				.has("li")
				.slideDown("fast",function() {$(this).addClass("opened");})
				.trigger("listopen");			
		});
	//Binds a listopen custom event on the suggestions list	
	$('#citySuggestion')
		.bind("listopen",function() {
			var zis = $(this);
			ieHideSelects();			
			$(document).mousedown(checkExternalClick);				
			$("li",this)
				.unbind()
				//Navigate with the mouse on the suggestions list
				.hover(
					function() {
						zis.find("li.active").removeClass("active");
						$(this).addClass("active");},
					function() {
						zis.find("li.active").removeClass("active");
						$(this).removeClass("active");}
				)
				//On click we close the list and put the selected value in the input
				.click(function() {
					$("#alege").val($(this).text());
					$("#showLinkId").val($(this).attr("rel"));
					$("#alege").trigger("listclose");				
				});
		});	
});
//On external click we hide the suggestions list
var checkExternalClick = function(event) {
	if ($(event.target).parents('.input-textWrap').length === 0) { $("#alege").trigger("listclose"); }
};
//Bug in ie: the jNice selects will appear over the suggestions list
function ieHideSelects() {
	if ($.browser.msie && $.browser.version <= 7) {
		$(".jNiceWrapper").css("visibility","hidden");
	}	
}
function ieShowSelects() {
	if ($.browser.msie && $.browser.version <= 7) {
		$(".jNiceWrapper").css("visibility","visible");
	}	
}
//Navigate on the suggestions list with up/down arrows
function moveCursor(ecode) {
	if ($('#citySuggestion').hasClass("opened")) {
		var ul = $('#citySuggestion'),
			liHeight = $('li:first',ul).height() 
						 + parseInt($('li:first',ul).css("padding-top")) 
						 + parseInt($('li:first',ul).css("padding-bottom")),
			listHeight = ul.height();
		
		poz = -1;
		cscroll = ul.scrollTop();
				
		if ($('li.active',ul).length) {
			poz = $("li",ul).index($("li.active",ul));
		}
		
		activeLiPoz = poz * liHeight;
				
		switch (ecode) {
			case 38:
				if (poz == -1) break;
				else {
					//the active item is below the scroll
					if (activeLiPoz > cscroll + listHeight) {
						poz = Math.floor((cscroll + listHeight) / liHeight) - 1;
					//the active item is above the scroll
					} else if (activeLiPoz <= cscroll) {
						ul.scrollTop(activeLiPoz - 3*liHeight);
						cscroll = ul.scrollTop();
					} else {poz--;}						
				}	
				break;
			case 40:			
				if (poz == $("li",ul).length - 1) break;
				else {					
					//the active item is above the scroll
					if (activeLiPoz < cscroll) {
						poz = Math.ceil(cscroll / liHeight);						
					//the active item is below the scroll
					} else if (activeLiPoz >= cscroll + listHeight - liHeight) {						
						ul.scrollTop(cscroll + 3*liHeight);
						cscroll = ul.scrollTop();
					} else {poz++;}						
				}
				break;
		}
		
		if (poz > -1) {
			ul
			.find("li.active")
			.removeClass("active")
			.end()
			.find("li:eq("+poz+")")
			.addClass("active");
		}		
	}
}

var vremeaPreloader = {
	show: function(w) {
		$(w + " .vremea-loader").show();
	},
	hide: function(w) {
		$(w + " .vremea-loader").hide();
	}
}

function homeForecast() {
	var cityIndex = document.getElementById("home_weather_location").selectedIndex,
		cityId = document.getElementById("home_weather_location").options[cityIndex].value;
	var currentUrl = document.location.href;
	if(currentUrl.indexOf('?')!=-1)
		currentUrl += '&tx_weatheraccu_pi1[homeforecast]=1&tx_weatheraccu_pi1[cityId]='+cityId+'&type=45&no_cache=1&location_id='+cityId;
	else 
		currentUrl += '?tx_weatheraccu_pi1[homeforecast]=1&tx_weatheraccu_pi1[cityId]='+cityId+'&type=45&no_cache=1&location_id='+cityId;
	$.ajax({
		url: currentUrl,
		cache: true,
		type: "GET",
		dataType: "html",
		success: function(html){
			//$.jNice.SelectRemove($("#sidebar-vremea .jNice"));
			$("#sidebar-vremea").replaceWith(html);			
			//$("#sidebar-vremea .jNice").jNice();
  		}
	});
}

function weatherDetails() {
	var cityIndex = document.getElementById("iframe_weather_location").selectedIndex,
		cityId = document.getElementById("iframe_weather_location").options[cityIndex].value;
	var currentUrl = document.location.href;
	if(currentUrl.indexOf('?')!=-1)
		currentUrl += "&location_id="+cityId;
	else 
		currentUrl += "?location_id="+cityId;
	$.ajax({
		url: currentUrl,
		cache: true,
		type: "GET",
		dataType: "html",
		success: function(html){
			$("#sidebar-vremea").replaceWith(html);			
		}
	});
}

function city_search() {	
	var val = $("#alege").val(),
		cityId = $("#showLinkId").val(),
		ul = $('#citySuggestion'),
		testval = /^[a-zA-Z\s]*$/,
		testmember = new RegExp(val,"gi");
    
	vremeaPreloader.show(".city-wrapper");
		
	if (val.match(testval)) {
		var currentUrl = 'index.php?eID=searchCities&word='+val+'&tx_weatheraccu_pi1[showCityLink]=1&tx_weatheraccu_pi1[cityId]='+cityId;
		$.ajax({
		url: currentUrl,
		cache: true,
		type: "GET",
		dataType: "html",
		success: function(html){
			ul
			.html(html)
			.slideDown("fast",function() {$(this).addClass("opened");})
			.trigger("listopen");
			vremeaPreloader.hide(".city-wrapper");
  		}
	});
	}
}

function afiseaza_orase(litera){

	vremeaPreloader.show(".cities-wrapper");
	
	var currentUrl = document.location.href;
	if(currentUrl.indexOf('?')!=-1)
		currentUrl += '&tx_weatheraccu_pi1[ajax_browse]=1&tx_weatheraccu_pi1[letter]='+litera+'&type=42&no_cache=1';
	else 
		currentUrl += '?tx_weatheraccu_pi1[ajax_browse]=1&tx_weatheraccu_pi1[letter]='+litera+'&type=42&no_cache=1';
	
	$.ajax({
		url: currentUrl,
		cache: true,
		type: "GET",
		dataType: "html",
		success: function(html){
			$("#vremeOrase").html(html);
			vremeaPreloader.hide(".cities-wrapper");
  		}
	});
	
	$("#cities .initials")
		.find("li.active").removeAttr("class")
		.end().find("#"+litera).addClass("active");
}

function alege_orase() {
	var string = document.getElementById("alege").value,
		cityId = document.getElementById("showLinkId").value;
	
	vremeaPreloader.show(".city-wrapper");
	
	var currentUrl = document.location.href;
	if(currentUrl.indexOf('?')!=-1)
		currentUrl += '&type=42&no_cache=1&tx_weatheraccu_pi1[letter]='+string+'&tx_weatheraccu_pi1[cityId]='+cityId+'&tx_weatheraccu_pi1[showCityLink]=1';
	else 
		currentUrl += '?type=42&no_cache=1&tx_weatheraccu_pi1[letter]='+string+'&tx_weatheraccu_pi1[cityId]='+cityId+'&tx_weatheraccu_pi1[showCityLink]=1';
	
	$.ajax({
		url: currentUrl,
		cache: true,
		type: "GET",
		dataType: "html",
		success: function(html){
			$.jNice.SelectRemove($("#selectLetter"));
			$.jNice.SelectRemove($("#selectCity"));
			$("#selectors").html(html);
			vremeaPreloader.hide(".city-wrapper");
			$("#selectLetter").parents("fieldset").jNice();
			$("#selectCity").parents("fieldset").jNice();
  		}
	});
}

function populeaza_orase(){
	var letterIndex = document.getElementById("selectLetter").selectedIndex,
	    letter = document.getElementById("selectLetter").options[letterIndex].value;
	
	vremeaPreloader.show(".city-wrapper");
	
	var currentUrl = document.location.href;
	if(currentUrl.indexOf('?')!=-1)
		currentUrl += '&tx_weatheraccu_pi1[loadCities]=1&type=42&no_cache=1&tx_weatheraccu_pi1[letter]='+letter;
	else 
		currentUrl += '?tx_weatheraccu_pi1[loadCities]=1&type=42&no_cache=1&tx_weatheraccu_pi1[letter]='+letter;
	
	$.ajax({
		url: currentUrl,
		cache: true,
		type: "GET",
		dataType: "html",
		success: function(html){
			$.jNice.SelectRemove($("#selectCity"));
			$.jNice.SelectRemove($("#selectLetter"));
			$("#selectedCityLink").html('');
			$("#selectCity").html(html);
			vremeaPreloader.hide(".city-wrapper");
			$("#selectLetter").parents("fieldset").jNice();
			$("#selectCity").parents("fieldset").jNice();
  		}
	});
}

function showCity() {
	var cityIndex = document.getElementById("selectCity").selectedIndex,
		cityName = document.getElementById("selectCity").options[cityIndex].text,
		cityId = document.getElementById("selectCity").options[cityIndex].value;
		
	vremeaPreloader.show(".city-wrapper");	
	
	var currentUrl = document.location.href;
	if(currentUrl.indexOf('?')!=-1)
		currentUrl += '&tx_weatheraccu_pi1[showCityLink]=1&type=42&no_cache=1&location_id='+cityId+'&tx_weatheraccu_pi1[letter]='+cityName+'&tx_weatheraccu_pi1[cityId]='+cityId;
	else 
		currentUrl += '?tx_weatheraccu_pi1[showCityLink]=1&type=42&no_cache=1&location_id='+cityId+'&tx_weatheraccu_pi1[letter]='+cityName+'&tx_weatheraccu_pi1[cityId]='+cityId;
	
	$.ajax({
		url: currentUrl,
		cache: true,
		type: "GET",
		dataType: "html",
		success: function(html){
			$.jNice.SelectRemove($("#selectLetter"));
			$.jNice.SelectRemove($("#selectCity"));
			$("#selectors").html(html);
			vremeaPreloader.hide(".city-wrapper");
			$("#selectLetter").parents("fieldset").jNice();
			$("#selectCity").parents("fieldset").jNice();
  		}
	});
}

function changeClass(obj) {
	var top = obj.parentNode,
		ob = null,
		i = 0;
		
	for ( i = 0; i < top.childNodes.length; i++ ) {
		ob = top.childNodes[i];
		alert (ob);
		ob.setAttribute("class", "");
	}
}

function cauta_orase() {
	var string = document.getElementById("cauta").value;
	
	vremeaPreloader.show(".cities-wrapper");
	var currentUrl = document.location.href;
	if(currentUrl.indexOf('?') != -1) {
		currentUrl = currentUrl+'&type=42&no_cache=1&tx_weatheraccu_pi1[ajax_browse]=1&tx_weatheraccu_pi1[letter]='+string+'&tx_weatheraccu_pi1[cauta]=1';
	} else {
		currentUrl = currentUrl+"?type=42&no_cache=1&tx_weatheraccu_pi1[ajax_browse]=1&tx_weatheraccu_pi1[letter]='+string+'&tx_weatheraccu_pi1[cauta]=1";
	}	
	$.ajax({
		url: currentUrl,
		cache: true,
		type: "GET",
		dataType: "html",
		success: function(html){
			$("#vremeOrase").html(html);
			vremeaPreloader.hide(".cities-wrapper");
  		}
	});
	var letterArray = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
	for(i=0; i < letterArray.length; i++) {
		document.getElementById(letterArray[i]).setAttribute("class", "");
	}
}

function checkEnter(e){ //e is event object passed from function invocation
	var characterCode; // literal character code will be stored in this variable
	if(e && e.which) { //if which property of event object is supported (NN4)
		e = e;
		characterCode = e.which; //character code is contained in NN4's which property
	} else {
		e = event;
		characterCode = e.keyCode; //character code is contained in IE's keyCode property
	}
	if(characterCode == 13) { //if generated character code is equal to ascii 13 (if enter key)
		cauta_orase();
		
	} else {
		return true;
	}
}

