/**
 * url 		  - url pro ziskani JSON seznamu oblasti [id, name] s /id parametrem rodice
 * urlMain 	  - url pro ziskani JSON seznamu rodicovskych oblasti [id, name]
 * firstText  - text prvni (prazdne) polozky
 * firstText  - text prvni (prazdne) polozky v druhem levelu
 * id 		  - id aktualni oblasti (pro editaci)
 * idMain 	  - id aktualni rodicovske oblasti (pro editaci)
 * processFce - fce pro eval pri spusteni 
 */
$.fn.doubleLevelSelect = function(url, urlMain, firstText, first2Text, id, idMain, processFce) {
	
    // konstanty
	var mainId = 'provinceMainIdAjax';
	
	if (firstText == null) firstText = "";
	  
    return this.each(function() {
    	
    	var selectProvinces = $(this);
    	
    	//selectProvinces.html('');
    	selectProvinces.css('visibility', 'hidden');

    	var htmlCode = '<select id="'+ mainId +'"><option value="">'+ firstText +'</option>';

    	$.getJSON(urlMain,
    		function(data){
    			$.each(data, function(i, item){
    				htmlCode += '<option value="'+ item.id +'"';
    				if (idMain != null && item.id == idMain) {
    					htmlCode += ' selected="selected"';		
    				}
    				htmlCode += '">'+ item.name +'</option>';		
    			});
    			htmlCode += '</select>&nbsp; ';
    			selectProvinces.parent().html(htmlCode + selectProvinces.parent().html());

    			var selectMain = $('select#'+ mainId);
    			
    			selectMain.change(function() {
    			  if (processFce != null) eval(processFce);
    			
    				if ($(this).val() == "") {
    					var select = $('select#'+ selectProvinces.attr('id'));
    					// pridame a vybereme prazdnou hodnotu a schovame
    					select.html('<option />')
    						  .val('')
    						  .css('visibility', 'hidden');    					
    					return;
    				}
    				doGetJSON(selectMain, selectProvinces, url, id, first2Text, processFce);
    			});		
    			
    			// pokud je zadane id, inicializuje podle nej
    			if (id != null) {
    				doGetJSON(selectMain, selectProvinces, url, id, first2Text, processFce);
    			}
    		}
    	);
    });
};

function doGetJSON(selectMain, selectProvinces, url, id, first2Text, processFce) {
	$.getJSON(url+ selectMain.val(),
		function(data) {
			// v asynchroni fci je treba znovu nacist select
			var select = $('select#'+ selectProvinces.attr('id')); 
			htmlCode = '';
			if (first2Text != null) {
				htmlCode = '<option value="_'+ selectMain.val() +'">'+ first2Text +'</option>';
			}
			$.each(data, function(i, item) {
				htmlCode += '<option value="'+ item.id +'"';
   				if (id != null && item.id == id) {
   					htmlCode += ' selected="selected"';		
   				}
   				htmlCode += '">'+ item.name +'</option>';	
			});
			select
				.css('visibility', 'visible')
				.html(htmlCode);    
				
      if (processFce != null) {
        select.change(function(){ eval(processFce); });
      }										
		}
	);	
}
