function jm_psc_init_alt(identifikator) {
	$('<input type="hidden" id="' + identifikator +'_hidden" name="' + identifikator + '_hidden" />')
		.val($("#" + identifikator).val())
		.insertBefore($("#" + identifikator));
	$("#" + identifikator).change(jm_psc_init_alt_change);
}


function jm_psc_init_alt_remove(identifikator) {
	$("#" + identifikator).unbind('change', jm_psc_init_alt_change);
	$("#" + identifikator + '_hidden').remove();

}


function jm_psc_init_alt_change() {
	var id = $(this).attr('id');
	$("#" + id + '_hidden').val($("#" + id).val());
}


function jm_psc_init_identifikace(prefix) {
	if (prefix == undefined) {
		var identifikace = $(this).val();
		var id = $(this).attr('id');
		var prefix = id.substr(0,id.length-"identifikace".length);
	} else {
		var identifikace = $('#' + prefix + 'identifikace').val();
	}
	$('#' + prefix + 'okres').parent().html('<select id="'+prefix+'okres" name="'+prefix+'okres"></select>');
	$('#' + prefix + 'obec').parent().html('<select id="'+prefix+'obec" name="'+prefix+'obec"></select>');
	$('#' + prefix + 'cast_obce').parent().html('<select id="'+prefix+'cast_obce" name="'+prefix+'cast_obce"></select>');
	hideElementError(prefix + "psc");
	if (identifikace == 'psc') {
//		$('#' + prefix + 'okres').parent().html('<select id="'+prefix+'okres" name="'+prefix+'okres"></select>');
		$('#' + prefix + 'okres')
			.attr('disabled', 'disabled')
			.html('<option value="">... doplňte celé PSČ ...</option>');
//		$('#' + prefix + 'obec').parent().html('<select id="'+prefix+'obec" name="'+prefix+'obec"></select>');
		$('#' + prefix + 'obec')
			.attr('disabled', 'disabled')
			.html('<option value="">... doplňte celé PSČ ...</option>');
		$('#' + prefix + 'cast_obce')
			.attr('disabled', 'disabled');
//		$('#' + prefix + 'cast_obce').parent().html('<select id="'+prefix+'cast_obce" name="'+prefix+'cast_obce"></select>');
		$('#' + prefix + 'cast_obce')
			.attr('disabled', 'disabled')
			.html('<option value="">... doplňte celé PSČ ...</option>');
		$('#id_' + prefix + 'cast_obce').hide();
		$('#' + prefix + 'psc')
			.attr('disabled', '')
			.val('');
		$('#id_' + prefix + 'psc').remove().insertBefore($('#id_' + prefix + 'okres'));
		$('#' + prefix + 'psc').change(function(){
				validatePsc(this)
		});
		// $('#' + prefix + 'psc').focus();
		jm_psc_init_alt_remove(prefix + 'psc');
		jm_psc_init_alt(prefix + 'okres');
		jm_psc_init_alt(prefix + 'obec');
	} else {
		$('#' + prefix + 'okres').parent().html('<input type="text" id="'+prefix+'okres" name="'+prefix+'okres"/>');
		$('#' + prefix + 'okres')
			.attr('disabled', '')
			.html('');
		$('#' + prefix + 'obec')
			.attr('disabled', '')
			.html('<option value=""> ... vyberte okres ... </option>');
		$('#' + prefix + 'cast_obce')
			.attr('disabled', '')
			.html('<option value=""> ... vyberte okres a obec ... </option>');
		$('#id_' + prefix + 'cast_obce')
			.show();
		$('#' + prefix + 'psc')
			.attr('disabled', 'disabled')
			.val('');
		$('#id_' + prefix + 'psc').remove().insertAfter($('#id_' + prefix + 'cast_obce'));
		// $('#' + prefix + 'okres').focus();
		jm_psc_init_alt_remove(prefix + 'okres');
		jm_psc_init_alt_remove(prefix + 'obec');
		jm_psc_init_alt(prefix + 'psc');
	}
}


function jm_psc_init(prefix) {


    var stat = $('#'+prefix+'stat').val();
	// console.log(prefix, stat);
    var zpusob = $('#'+prefix+'identifikace').val();
    
	// console.log(zpusob);

    var okres = $('#'+prefix+'okres');
    var obec = $('#'+prefix+'obec');
    var cast_obce = $('#'+prefix+'cast_obce');
    var psc = $('#'+prefix+'psc');

	// console.log(psc);

    var name;

    okres.unautocomplete();

	//$("#"+prefix+"identifikace").change(jm_psc_init_identifikace);
	jm_psc_init_identifikace(prefix);

    if (stat == 'CZ' || stat == undefined) {
       /* ========== STAT JE CESKA REPUBLIKA ========== */
       $("#id_"+prefix+"identifikace").show(); 
        
       if (zpusob == "psc") {
           /* ============= Vyber pres PSC ============= */
           /* OKRES */
		   $("#id_"+prefix+"okres").show();
           $('#'+prefix+'okres').change(function() {
                var id = this.id; var prefix = id.substr(0,id.length-"okres".length);
                var selected = $(this).val();
                if (selected) {
                    var obec = $('#'+prefix+'obec');
                    var psc = $('#'+prefix+'psc').val();
                    obec.html('<option value="">... načítám ...</option>');
                    var url = jm_url_prefix+"data_obce_psc.php?d="+encodeURIComponent(selected)+"&z="+encodeURIComponent(psc);
                    obec.load(url, null, function(){
						obec.change();
					});

                }

//				console.log('change okres value' , $(this).val());
            });

           /* PSC */
            $('#'+prefix+'psc').keydown(function(event) {
                if (event.keyCode == 9) return;
                var id = this.id;
				var prefix = id.substr(0,id.length-"psc".length);
                $('#'+prefix+'okres').html('');
                $('#'+prefix+'obec').html('');
                $('#'+prefix+'cast_obce').html('');
                setTimeout('pm_psc("'+this.id+'", null, null);',500);
            });

            /* OBEC */
            $('#'+prefix+'obec').change(function() {
                var id = this.id; var prefix = id.substr(0,id.length-"obec".length);
                var okres = $('#'+prefix+'okres').val();
                var obec = $(this).val();
                var psc = $('#'+prefix+'psc').val();
                var url = jm_url_prefix+"data_cobce_psc.php?d="+encodeURIComponent(okres)+"&c="+encodeURIComponent(obec)+"&z="+encodeURIComponent(psc);
                var cast_obce = $('#'+prefix+'cast_obce');
                cast_obce.html('<option value="">... načítám ...</option>');
                cast_obce.load(url);
            });
            
       } else  {
           /* ============= Vyber pres OKRES ============= */ 
           /* OKRES */
           okres.parent().html('<input type="text" id="'+prefix+'okres" name="'+prefix+'okres"/>');
		   $("#id_"+prefix+"okres").show();
           $('#'+prefix+'okres').autocomplete(jm_url_prefix + "data_okresy.php", {
                autoFill:true,
                minChars:1,
                scroll:true,
                scrollHeight:100,
                selectFirst:true,
				cacheLength:100
            }).result(function(event, data, formatted){
                var obec = $('#'+prefix+'obec');
                var cast_obce = $('#'+prefix+'cast_obce');
                var psc = $('#'+prefix+'psc');
                obec.html('');
                cast_obce.html('');
                psc.val('');
                //$('#log').append(url+"<br>");
                if (data) {
                    obec.html('<option value="">... načítám ...</option>');
                    var url = jm_url_prefix + "data_obce.php?q=" + encodeURIComponent(formatted);
                    obec.load(url, null, function(){
						obec.change();
						var co = $('#'+prefix+'cast_obce');
						co.html('<option value="">... vyberte obec ...</option>');
					});
                }
            });

            /* OBEC */
            $('#'+prefix+'obec').parent().html('<select id="'+prefix+'obec" name="'+prefix+'obec"><option> ... vyberte okres ... </option></select>');
            $('#'+prefix+'obec').change(function() {
				var psc = $('#'+prefix+'psc');
				psc.val('');
                var okres = $('#'+prefix+'okres').val();
                var obec = $('#'+prefix+'obec').val();
                var url = jm_url_prefix + "data_cobce.php?d=" + encodeURIComponent(okres) + "&c=" + encodeURIComponent(obec);
                //$('#log').append(url+"<br>");
                var co = $('#'+prefix+'cast_obce');
                co.html('<option value="">... načítám ...</option>');
                co.load(url, function(){
					if ($('#'+prefix+'cast_obce').val() != '') {
						$('#'+prefix+'cast_obce').change();
					}
				});


            });

            /* CAST OBCE */
            $('#'+prefix+'cast_obce').parent().html('<select id="'+prefix+'cast_obce" name="'+prefix+'cast_obce"><option> ... vyberte okres a obec ... </option></select>');
			
            $('#'+prefix+'cast_obce').change(function() {
				cobce_val_arr = explode(';',$(this).val());
				cobce_val_psc = cobce_val_arr[0];
                $('#'+prefix+'psc').val(cobce_val_psc);
				$("#" + prefix + 'psc_hidden').val(cobce_val_psc);
            });
       }
    } else {
        /* ========== STAT NENI CESKA REPUBLIKA ========== */
        $("#id_"+prefix+"identifikace").hide();
        /* OKRES */
		$("#"+prefix+"okres").parent().html('<input type="text" id="'+prefix+'okres" name="'+prefix+'okres"/>');
		$("#id_"+prefix+"okres").hide();
        /* PSC */
        $("#"+prefix+"psc").parent().html('<input type="text" id="'+prefix+'psc" name="'+prefix+'psc"/>');
        /* OBEC */
        $("#"+prefix+"obec").parent().html('<input type="text" id="'+prefix+'obec" name="'+prefix+'obec"/>');
        /* CAST OBCE */
        $("#"+prefix+"cast_obce").parent().html('<input type="text" id="'+prefix+'cast_obce" name="'+prefix+'cast_obce"/>').show();
		$("#id_"+prefix+"cast_obce").show();

		$('#id_' + prefix + 'psc').remove().insertAfter($('#id_' + prefix + 'cast_obce'));
    }
}

/* (univerzalni) - vola se po zmene PSC */
function pm_psc(id, val_obec, val_okres) {
	
	$('#'+prefix+'cast_obce').attr('disabled', 'disabled').hide();
    var prefix = id.substr(0,id.length-"psc".length);
    var zip = $('#'+id).val();
	if (zip.length < 5) {
		$('#'+prefix+'okres').attr('disabled', 'disabled').html('<option value="">... doplňte celé PSČ ...</option>');
		$('#'+prefix+'obec').attr('disabled', 'disabled').html('<option value="">... doplňte celé PSČ ...</option>');
		return;
	}
	$('#'+prefix+'okres').html('<option value="">... načítám ...</option>');
	$('#'+prefix+'obec').html('<option value="">... vyberte okres ...</option>');
	var okres = $('#'+prefix+'okres');
    okres.html('<option value="">... načítám ...</option>');
	url = jm_url_prefix+'data_okresy_podle_psc.php?z='+encodeURIComponent(zip);
	if (val_okres != null) {
		url = url + "&sel=" + encodeURIComponent(val_okres);
	}
    okres.load(url, null, function() {
        var id = this.id; var prefix = id.substr(0,id.length-"okres".length);
        var selected = $(this).val();
		if ($(this).val() != '') {
			$(this).attr('disabled', 'disabled');
		} else {
			$(this).attr('disabled', '');
			$('#'+prefix+'obec').attr('disabled', '');
		}
		$('#'+prefix+'okres').change();
        if (selected) {
            var obec = $('#'+prefix+'obec'); 
            obec.html('<option value="">... načítám ...</option>');
            var url = jm_url_prefix+"data_obce_psc.php?d="+encodeURIComponent(selected)+"&z="+encodeURIComponent($('#'+prefix+'psc').val());
			if (val_obec != null) {
				url = url + "&sel=" + encodeURIComponent(val_obec);
			}
            obec.load(url, null, function () {
				if ($(this).val() != '') {
					$(this).attr('disabled', 'disabled');
				} else {
					$(this).attr('disabled', '');
				}
				$(this).change();
			});
			obec.change();
        }        
    });
}

/* obnovi obsahy a vybrane polozky selectu */
function jm_psc_reload(prefix, val_obec, val_psc, val_okres, val_cast_obce) {
//	console.log("prefix: %s  okres: %s  psc: %s  obec: %s  cast obce: %s", prefix, val_okres, val_psc, val_obec, val_cast_obce);
    var stat = $('#'+prefix+'stat').val();
    var zpusob = $('#'+prefix+'identifikace').val();

    var okres = $('#'+prefix+'okres');
    var obec = $('#'+prefix+'obec');
    var cast_obce = $('#'+prefix+'cast_obce');
    var psc = $('#'+prefix+'psc');

	$("#" + prefix + 'okres_hidden').val(val_okres);
	$("#" + prefix + 'psc_hidden').val(val_psc);
	$("#" + prefix + 'obec_hidden').val(val_obec);
	$("#" + prefix + 'cast_obce_hidden').val(val_cast_obce);

    /* PSC */

	psc.val(val_psc);
	if (stat == 'CZ' && zpusob == "psc") {
		pm_psc(prefix + 'psc', val_obec, val_okres);
		/*
        obec.html('<option value="">... načítám ...</option>');
        var url;
        url = jm_url_prefix + "data_obce_psc.php?d=" + encodeURIComponent(val_okres) + '&z=' + val_psc + '&sel=' + encodeURIComponent(val_obec);
		
        obec.load(url, null, function(){console.log(url);});
		*/
		return;
	}
	
    /* OKRES */
    okres.val(val_okres);
	$("#" + prefix + 'okres_hidden').val(val_okres);

    /* obec */
    if (stat == 'CZ') {
        obec.html('<option value="">... načítám ...</option>');
        var url;
        url = jm_url_prefix + "data_obce.php?q=" + encodeURIComponent(val_okres) + '&sel=' + encodeURIComponent(val_obec);
        obec.load(url);

    } else {
        obec.val(val_obec);
    }
    
    /* cast obce */
    if (stat == 'CZ') {
        cast_obce.html('<option value="">... načítám ...</option>');
        var url;
        url = jm_url_prefix + "data_cobce.php?d=" + encodeURIComponent(val_okres) + "&c=" + encodeURIComponent(val_obec) + '&sel=' + encodeURIComponent(val_cast_obce);
        cast_obce.load(url);
    } else {
        cast_obce.val(val_cast_obce);
    }


    
}



function explode( delimiter, string, limit ) {
    // Splits a string on string separator and return array of components. If limit is positive only limit number of components is returned. If limit is negative all components except the last abs(limit) are returned.
    //
    // version: 905.412
    // discuss at: http://phpjs.org/functions/explode
    // +     original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: kenneth
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: d3x
    // +     bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: explode(' ', 'Kevin van Zonneveld');
    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
    // *     example 2: explode('=', 'a=bc=d', 2);
    // *     returns 2: ['a', 'bc=d']

    var emptyArray = { 0: '' };

    // third argument is not required
    if ( arguments.length < 2 ||
        typeof arguments[0] == 'undefined' ||
        typeof arguments[1] == 'undefined' )
    {
        return null;
    }

    if ( delimiter === '' ||
        delimiter === false ||
        delimiter === null )
    {
        return false;
    }

    if ( typeof delimiter == 'function' ||
        typeof delimiter == 'object' ||
        typeof string == 'function' ||
        typeof string == 'object' )
    {
        return emptyArray;
    }

    if ( delimiter === true ) {
        delimiter = '1';
    }

    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}

