function redirectSkiinfo(selectId) {
    var select = document.getElementById(selectId);
    var url = select.options[select.selectedIndex].value;
    window.location = url;
}

function infotab(a) {
    $("#tab1").removeClass("selected");
    $("#tab2").removeClass("selected");
    $(a).addClass("selected");

    $("#infobox-body1").hide();
    $("#infobox-body2").hide();
    $("#infobox-searchbutton").hide();

    if ($(a).attr('id')=='tab1') {
        $("#infobox-body1").show();
        $("#infobox-searchbutton").show();
    }else{
        $("#infobox-body2").show();
    }

    return false;
}

function clearSelect(select_id) {
    select = $("#" + select_id)[0];
    options = select.options;
    while (options.length>0) {
        options[0] = null;
    }
}

/**
 * On select change reload other selects.
 */
function searchChanged(elementid, baseUrl) {
    urlData = assemblyUrl();
    urlData += "/changed/" + elementid
    url = baseUrl + "/ajax" + urlData;

    jsonSearchRequest(url);
}

/**
 * Restore initial selects state.
 */
function restoreSearchState(type, country, place, baseUrl) {
    urlData = "/type/" + type + "/country/" + country + "/place/" + place + "/restore/" + "1";
    url = baseUrl + "/ajax" + urlData;

    jsonSearchRequest(url);
}

/**
 * Generate and process ajax request. Process returned data.
 */
function jsonSearchRequest(url) {
    jQuery.getJSON(url, function(data) {
        for(var i=0; i<data.length; i++) {
            updateSelect(data[i]);
        }
    });
}

/**
 * sample json data: a={'id': 'country', 'selected':'d', 'options': [{'text':'a', 'value': 'b'}, {'text':'c', 'value':'d'}]}
 */
function updateSelect(jsondata) {
    id = jsondata.id;

    element = document.getElementById(id);
    if (!element) {
        return;
    }
    
    clearSelect(id);

    options = jsondata.options;
    selectedValue = jsondata.selected;
    for (i=0; i<options.length; i++) {
        value = options[i].value;
        text = options[i].text;
        var o = new Option(text, value, false, value==selectedValue);        
        element.options[element.options.length] = o;
    }
}

/**
 * Assembly url part with user provided form elements data.
 */
function assemblyUrl() {
    ids = ["search-type", "search-country", "search-place"];

    url = "";
    for (i=0; i<ids.length; i++) {
        element = document.getElementById(ids[i]);
        if (!element) {
            continue;
        }

        //no options
        if (element.options.length==0) {
            continue;
        }

        selected = element.options[element.selectedIndex].value;
        name = element.name;
        if (selected.length>0) {
            url += '/' + name + '/' + selected
        }
    }
    return url;
}