$(function(){
    $("select#kraj").change(function(){
          var t1 = document.getElementById("typy_1");
          var tt1 = 0;
          if (t1.checked == true) tt1 = 1;
          var t2 = document.getElementById("typy_2");
          var tt2 = 0;
          if (t2.checked == true) tt2 = 1;
          var t3 = document.getElementById("typy_3");
          var tt3 = 0;
          if (t3.checked == true) tt3 = 1;
          $.getJSON("/include2/wojs.php",{id: $(this).val(), typ1: tt1, typ2: tt2, typ3: tt3, ajax: 'true'}, function(j){
          var options = '';
          for (var i = 0; i < j.length; i++) {
            options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
          }
          $("select#woj").html(options);
        });
          setTimeout("change()",1000);
      });
});

$(function(){
    $("select#kraj2").change(function(){
          $.getJSON("/include2/wojs.php",{id: $(this).val(), typ1: 0, typ2: 0, typ3: 0, ajax: 'true'}, function(j){
          var options = '';
          for (var i = 0; i < j.length; i++) {
            options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
          }
          $("select#woj2").html(options);
        });
      });
});

    function change() {
        var sel = document.getElementById("woj");
        addCountries(sel, miasto);
    }

//var origOptions = null;
var request=null;

function getURLParams(nazwa) {
	var urlParams = {}; 
	var s=document.location.search;
	if (s.length==0) return;
	var s1 = (s.split('?'))[1];
	if (s1.length>0) { 
		var s2 = s1.split('&');
		if (s2.length>0) { 
			for (var i=0; i<s2.length; i++) { 
				var p=s2[i].split('=');
				if (p[0] == nazwa) { 
					return p[1] 
				} 
			} 
		} 
	}
	return 0; 
} 

var kraj = getURLParams('kraj');
var miasto = getURLParams('city');
var wojs = getURLParams('woj');

window.onload=function(){
    var sel0 = document.getElementById("kraj");
    var sel = document.getElementById("woj");
    var sel2 = document.getElementById("city");
    var t1 = document.getElementById("typy_1");
    var t2 = document.getElementById("typy_2");
    var t3 = document.getElementById("typy_3");
    if(sel != null) {
        sel.onchange=function(){
            sel2.disabled = true;
            addCountries(this, miasto);
        };
        sel.onfocus=function(){
            sel2.disabled = true;
            addCountries(this, miasto);
        };
        t1.onclick=function(){
            //$('#typ1').val($(this).attr('checked') * 1);
            if ($(this).attr('checked')) {
                $('#typ1').val('1');
            } else {
                $('#typ1').val('0');
            }
            $('#city').attr('disabled', 'disabled');
            addCountries(sel, miasto);
            /*
            document.getElementById("typ1").value=t1.checked?1:0;
            sel2.disabled = true;
            addCountries(sel, miasto);
            */
        };
        t2.onclick=function() {
            if ($(this).attr('checked')) {
                $('#typ2').val('1');
                $('#profil').show();
                $('#profil').css('visibility', 'visible');
                $('#profil_label').show();
                $('#profil_label').css('visibility', 'visible');
            } else {
                $('#typ2').val('0');
                $('#profil').css('visibility', 'hidden');
                $('#profil_label').css('visibility', 'hidden');
            }
            $('#city').attr('disabled', 'disabled');
            addCountries(sel, miasto);
            /*
            document.getElementById("typ2").value=t2.checked?1:0;
            if (t2.checked) show_hide(2); else show_hide(1);
            sel2.disabled = true;
            addCountries(sel, miasto);
            */
        };
        t3.onclick=function(){
            if ($(this).attr('checked')) {
                $('#typ3').val('1');
            } else {
                $('#typ3').val('0');
            }
            $('#city').attr('disabled', 'disabled');
            addCountries(sel, miasto);
            /*
            document.getElementById("typ3").value=t3.checked?1:0;
            sel2.disabled = true;
            addCountries(sel, miasto);
            */
        };
        if (sel.value==0) {
            addCountries(sel, miasto);
        }
    }
//    origOptions = new Array();
//    for(var i = 0; i < sel2.options.length; i++){
//        origOptions[i]=sel2.options[i];
//   }
    

    if (wojs > 0) {
        sel2.disabled = true;
        addCountries(sel, miasto);
    }
}

function addCountries(obj, miasto){
    if (obj == null ) { return; }
    var url = "";
    var optsArray = obj.options;
    var val = "";
    for(var i=0; i < optsArray.length; i++){
        if(optsArray[i].selected) {
            val=optsArray[i].value; break;
        }

    }
    val21 = document.getElementById("typ1").value;
    val22 = document.getElementById("typ2").value;
    val23 = document.getElementById("typ3").value;
    val24 = document.getElementById("kraj").value;
    
    if (miasto == undefined) {
        miasto = 0;
    }
    
    url = "/include2/cities.php?woj="+encodeURIComponent(val)+"&typ1="+encodeURIComponent(val21)+"&typ2="+encodeURIComponent(val22)+"&typ3="+encodeURIComponent(val23)+"&city="+encodeURIComponent(miasto)+"&kraj="+encodeURIComponent(val24);
    httpRequest("GET",url,true);

}

// Obsługa zdarzeń dla obiektu XMLHttpRequest.
function handleResponse(){
   try{
      if(request.readyState == 4){
         if(request.status == 200){
            var resp =  request.responseText;
            if(resp != null) {
               // Wartość zwrotna jest tablic?.
               var objt = eval(resp);
               addToSelect(objt, miasto);
            }
         } else {
            // Jeżeli aplikacja nie jest dostępna, wtedy stan żądania wynosi 503,
            // natomiast w przypadku błędu w aplikacji stan żądania wynosi 500.
            //alert(
            //   "Wystąpił problem z komunikacją między obiektem XMLHttpRequest, "+
            //   "a programem serwera.");
         }
      }// Koniec zewnętrznej pętli if.
   } catch (err) {
     // alert("Serwer nie jest dostępny "+
     //    "dla tej aplikacji. Proszę wkrótce spróbować"+
     //    " ponownie. \nBłąd: "+err.message);

   }
}

function addToSelect(obj, miasto){
   var _select = document.getElementById("city");
   var el;
   // W pierwszej kolejności usunięcie wszystkich opcji, ponieważ element select 
   // mógł dołączyć nowo dodane miasta z poprzednich kliknięć.
   while(_select.hasChildNodes()){
      for(var i = 0; i < _select.childNodes.length; i++){
         _select.removeChild(_select.firstChild);
      }
   }
   // Dodanie po prostu oryginalnych opcji
   //for(var h=0; h < origOptions.length;h++) {
   //   _select.appendChild(origOptions[h]);
   //}
   _obj = obj[0];
   _obj_id = obj[1];
   _obj_sel = obj[2];
   // _obj jest tablicą nazw miast nowych opcji.
   // _obj_id jest tablicą wartości nowych opcji.
   el = document.createElement("option");
   el.setAttribute("value", 0);
   el.appendChild(document.createTextNode("--wybierz miasto--"));
   //_select.insertBefore(el,_select.nextSibling);
   _select.appendChild(el);
   for(var i=_obj.length-1; i >= 0;i--) {
      //alert(_obj_id[i], _obj_sel[i], _obj[i]);
      el = document.createElement("option");
      el.setAttribute("value", _obj_id[i]);
      if (_obj_sel[i]==1) el.setAttribute("selected", 1);
      el.appendChild(document.createTextNode(_obj[i]));
      //_select.insertBefore(el,_select.nextSibling);
      _select.appendChild(el);
   }
   _select.disabled=false;
   
   if ($("#link_bookmark1_search").is(".selected")) {
       $('#city').show();
   } else {
       $('#city').hide();
   }
}

/* Inicjalizacja obiektu żądania, który został już skonstruowany. */
function initReq(reqType,url,bool){
    try{
        /* Określenie funkcji, która będzie obsługiwała odpowiedź HTTP. */
        request.onreadystatechange=handleResponse;
        request.open(reqType,url,bool);
        request.send(null);
    } catch (errv) {

      //  alert(
      //          "Aplikacja nie może w tej chwili nawiązać połączenia z serwerem."+
      //          " Proszę wkrótce spróbować ponownie.");
    }
}

/* Funkcja opakowująca do skonstruowania obiektu żądania.
Parametry:
   reqType: typ żądania HTTP, na przykład GET lub POST.
   url: adres URL programu serwerowego.
   asynch: czy żądanie będzie wysłane asynchronicznie, czy też nie. */
function httpRequest(reqType,url,asynch){
   // Przegl?darki na bazie Mozilli.
   if(window.XMLHttpRequest){
      request = new XMLHttpRequest();
   } else if (window.ActiveXObject){
      request=new ActiveXObject("Msxml2.XMLHTTP");
      if (! request){
         request=new ActiveXObject("Microsoft.XMLHTTP");
      }
   }
   // Jeżeli nie powiodła się nawet inicjalizacja ActiveXObject,
   // wówczas żądanie wciąż może być typu null.
   if(request){
      initReq(reqType,url,asynch);
   } else {
      alert(
         "Używana przeglądarka nie pozwala na wykorzystanie "+
         "wszystkich funkcji tej aplikacji!");
   }
}

