/*
 * get data from countrysubdivision
 */
var csd_url = "/csd"
	
function csd_print_data(id) {
	a = $(id).val();
	alert(a)
	a = $(id + ' :selected').text();
	alert(a)
}

function csd_get_data(base_url, id, target) {
    
	url = base_url + "/" + id + "/json"
    
    $.blockUI({ 
    	css: { 
            border: 'none',
            top:  ($(window).height() - 200) /2 + 'px', 
            left: ($(window).width() - 200) /2 + 'px', 
            width: '200px', 
            padding: '5px', 
            backgroundColor: '#000', 
            '-webkit-border-radius': '10px', 
            '-moz-border-radius': '10px', 
            opacity: .5, 
            color: '#fff' 
    	},
    	message: 'Caricamento in corso'
    }); 
	
	setTimeout("$.unblockUI()",15000);
	
    $.ajax({
        url: url,
        cache: false,
        dataType: 'json',
        success: function(data) {
    		$.unblockUI()
            csd_select_populate(target, data)},
        error: function (e) {
        	$.unblockUI()
        	alert(e)
        }
    });
}

function csd_select_populate(el, items) {
    el.options.length = 0;
    if (items.children.length > 0)
        el.options[0] = new Option("Seleziona un'opzione", '');
    else
    	el.options[0] = new Option('Nessuna opzione', '');
    
    $.each(items.children, function () {
        el.options[el.options.length] = new Option(this.name, this.id);
    });
}

function csd_select_clean(id) {
	$(id).children().remove().end().append('<option value="">Nessuna Opzione</option>') ;
}

function csd_select_reset(){
    csd_select_clean($('#province').get(0))
    csd_select_clean($('#municipality').get(0))
}

function csd_select_bindings(base_url) {
    $('#region').bind('change', function() {
    	csd_select_clean($('#province').get(0))
    	csd_select_clean($('#municipality').get(0))
    	id = $('#region').val()
    	if (id != "")
    		csd_get_data(base_url, id, $('#province').get(0))
    });
	
    $('#province').bind('change', function() {
    	csd_select_clean($('#municipality').get(0))
		id = $('#province').val()
		if (id != "")
			csd_get_data(base_url, id, $('#municipality').get(0))
    });
}
