$(document).ready(function(){
	$(".SelectCity #c").change(select_city);
	select_city('document_ready');
});


function is_array(input) {
	return typeof(input)=='object'&&(input instanceof Array);
}


function in_array( what, where ){
	var a=false;
	for(var i=0;i<where.length;i++){
		if(what == where[i]){
			a=true;
			break;
		}
	}
	return a;
}


function select_city(action) {
	var value = $(".SelectCity #c").val();
	var value_string = is_array(value) ? value.join(',') : '';
	
	// Blokuje pola.
	//$(".SelectCity #c, .SelectMarket #m").attr("disabled", true);
	$(".SelectCity #c").block({ message: null })
	$(".SelectMarket #m").block({ message: null }); 
	
	// Ajax.
	$.post("?mod=kmm_offer&action=ajax", { cities:value_string }, function(response, textStatus){
		if (textStatus == "success") {
			var options = [];
			options.push('<option value="0">--- wybierz market ---</option>');
			
			$("market", response).each(function(){
				options.push('<option value="' + $(this).attr("id") + '">' + $(this).text() + '</option>');
			});
			
			// Przypisanie marketow do selecta.
			$(".SelectMarket #m").html(options.join(''));
			
			// Przy pierwszym zaladowaniu strony po przefiltrowaniu, zaznaczam wybrane markety.
			if (action == 'document_ready') {
				$(".SelectMarket #m option").each(function(){
					if (in_array($(this).val(), selected_markets)) {
						$(this).attr("selected", true);
					}
				});
			}
		}
		else {
			var msg = false;
			
			switch(textStatus) {
				case "timeout": msg = "czas połączenia przekroczył limit"; break;
				//case "error": msg = "błąd nieokreślony. Spróbuj ponownie."; break;
				//case "notmodified": msg = "błąd nieokreślony. Spróbuj ponownie."; break;
				case "parseerror": msg = "nieprawidłowa odpowiedź serwera"; break;
			}
			
			if (msg == false)
				alert("Wystąpił nieokreślony błąd podczas wczytywania listy marketów.");
			else
				alert("Podczas wczytywania listy marketów wystąpił błąd: " + msg + ". Odśwież stronę i spróbuj ponownie.");
		}
		
		// Odblokowuje pola.
		//$(".SelectCity #c, .SelectMarket #m").attr("disabled", false);
		$(".SelectCity #c").unblock()
		$(".SelectMarket #m").unblock(); 
		$(".SelectCity #c option:first").focus();
		if ($.browser.msie)
		{
			var tmpH = $(".SelectMarket #m").outerHeight();
			$(".SelectMarket #m").css('height', (tmpH+1)+'px');
			$(".SelectMarket #m").css('height', tmpH+'px');
		}

	}, "xml");
}

function select_all(){
	$(".SelectCity #c option").not(":first").attr("selected", true);
	$(".SelectMarket #m option").not(":first").attr("selected", true);
	$(".SelectStand #j option").not(":first").attr("selected", true);
}
