// Global variabels
var debug = false;

// From Controller/view:
// var indexed_schools
// var schools

var country_filter_sel = '#UserSchoolcountryId';
var school_sel = '#UserSchoolId';
var school_sel_full;
var school_sel_loader = '#UserSchoolLoader';

var loader = $('<img src="/images/ajax-loader1.gif"/ alt="loading">');

/**
 * On Document loaded
 */
jQuery(function() {
    init();
})

/**
 * Initializion
 **/
function init() {
    $(country_filter_sel).change(function () {
        $(school_sel_loader).html(loader);
        updateSchools();
    });
    // Save original
    school_sel_full = $(school_sel);
    // IE
    /*$("#OcclistAddForm").click(function () {
        updateOccasion();
    });*/
    initForwardLink();
}

/**
 * Initiates the forward link in the status bar
 * */
function initForwardLink() {
    $('.link_forward input').click(function() {
        $("#UserContForm").submit();
        $("#UserRegisterForm").submit();
    });
}

function updateSchools() {
    
    var country_id = $(country_filter_sel)
        .attr('value');
    var showschools;
    $(school_sel).remove();
    var ss = $('<select id="UserSchoolId" class="text" name="data[User][school_id]"></select>');

    if (country_id == 0) {
        //showschools = schools;
        $('tr.school_sel td.form_input').append(school_sel_full);
    } else {
        showschools = indexed_schools[country_id];
        $.each(showschools, function (i, val) {
        $(ss).append(
            $('<option value="' + i + '">' + val +  '</option>'));
        });
        $('tr.school_sel td.form_input').append(ss);
    }
    $(school_sel_loader).html('');
    //d(indexed_schools[country_id]);
}

/************************************************************/
/********************  Helper Functions  ********************/
/************************************************************/

/**
 * Puts debug print to the console if debug-variable is true
 */
function d(debugvalue) {
    if (debug)
        console.log(debugvalue);
}
