var directionsManager;

function onSearchSelectChange() {
    this.parentNode.getElementsByTagName('LABEL')[0].innerHTML = this.options[this.selectedIndex].innerHTML;
}

function addQueryParam(queryString, paramName, paramValue) {
    if (paramValue != "")
        return queryString + paramName + "=" + paramValue + "&";
    else
        return queryString;
}

function addQueryParamFromCurrentUri(queryString, paramName) {
    var value = getQueryParamValue(paramName);
    if (value != null)
        queryString = addQueryParam(queryString, paramName, value);

    return queryString;
}

function getCheckboxGroupQueryParamValue(checkboxes, seed) {
    var values = "";
    if (seed == undefined)
        seed = 0;
    for (var i = 0; i < checkboxes.length; i++) {
        if (checkboxes[i].checked)
            values += (i + seed) + ",";
    }
    return values.substr(0, values.length - 1);
}

function getCheckboxGroupQueryParamValueByIds(checkboxes) {
    var values = "";
    for (var i = 0; i < checkboxes.length; i++) {
        if (checkboxes[i].checked)
            values += checkboxes[i].id + ",";
    }
    return values.substr(0, values.length - 1);
}

function getSeasonTravelQueryParamValue() {
    var seasonTravelSelect = $("#seasonTravel select")[0];
    if (seasonTravelSelect.selectedIndex != 0) {
        var selectedSeasons = getCheckboxGroupQueryParamValue($("#seasonTravel input").toArray().reverse(), 1);
        if (selectedSeasons != "") {
            return seasonTravelSelect.selectedIndex + "," + selectedSeasons;
        }
    }
    return "";
}

function addGeoLocationDirectionQueryParam(queryString) {
    var directionSelects = $("#directionSearch select");
    for (var i = 0; i < directionSelects.length; i++) {

        if (directionSelects[i].selectedIndex != 0) {
            var value = directionSelects[i].options[directionSelects[i].selectedIndex].value;
            if (i == 0)
                queryString += "ct=" + value + "&";
            else if (i == 1)
                queryString += "cr=" + value + "&";
            else if (i == 2)
                queryString += "rg=" + value + "&";
            else if (i == 3)
                queryString += "rs=" + value + "&";
        }
    }

    return queryString;
}

function setQueryParamAndNavigate(paramName, paramValue) {
    var params = getQueryParams();
    setQueryParam(params, paramName, paramValue);
    window.location.search = queryParamsToString(params);
}

function getQueryParams() {
    var query = window.location.search.substring(1);
    if (query == "")
        return [];

    var queryParts = query.split("&");
    var result = [];
    for (i = 0; i < queryParts.length; i++) {
        var nameValue = queryParts[i].split("=");
        if (nameValue.length == 2) {
            result.push([nameValue[0], nameValue[1]]);
        }
        else {
            result.push([nameValue[0], null]);
        }
    }
    return result;
}

function getQueryParam(params, paramName) {
    for (i = 0; i < params.length; i++) {
        if (params[i][0] == paramName)
            return params[i];
    }
    return null;
}

function getQueryParamValue(paramName) {
    var params = getQueryParams();
    var param = getQueryParam(params, paramName);
    if (param != null)
        return param[1];
    else
        return null;
}

function setQueryParam(params, paramName, paramValue) {
    var param = getQueryParam(params, paramName);
    if (param != null)
        param[1] = paramValue;
    else
        params.push([paramName, paramValue]);
}

function removeQueryParam(params, paramName) {
    for (i = 0; i < params.length; i++) {
        if (params[i][0] == paramName) {
            params.splice(i, 1);
            return;
        }
    }
}

function queryParamsToString(params) {
    var queryString = "";
    for (i = 0; i < params.length; i++) {
        queryString += i == 0 ? "?" : "&";

        if (params[i][1] != null)
            queryString += params[i][0] + '=' + params[i][1];
        else
            queryString += params[i][0];
    }
    return queryString;
}

function setPageItemsCountAndNavigate() {
    var params = getQueryParams();
    var itemsCount = this.options[this.selectedIndex].value;
    removeQueryParam(params, "page");
    if (itemsCount != "20")
        setQueryParam(params, "ic", itemsCount);
    else
        removeQueryParam(params, "ic");
    window.location.search = queryParamsToString(params);
}

function addPagingItemsCountQueryParam(queryString) {
    queryString = addQueryParamFromCurrentUri(queryString, "ic");
    return queryString;
}

function addSortQueryParam(queryString) {
    queryString = addQueryParamFromCurrentUri(queryString, "sort");
    return queryString;
}

function addMapsQueryParam(queryString, showMap, showSearchMap) {
    if (showMap) {
        queryString = addQueryParam(queryString, "mp", 1);
        if (showSearchMap)
            queryString = addQueryParam(queryString, "ov", 1);
    }
    return queryString;
}

function addClosestToQueryParam(queryString) {
    queryString = addQueryParamFromCurrentUri(queryString, "clh");
    queryString = addQueryParamFromCurrentUri(queryString, "clr");
    queryString = addQueryParamFromCurrentUri(queryString, "clp");
    queryString = addQueryParamFromCurrentUri(queryString, "clt");
    return queryString;
}

function geoLocationDirectionManager() {

    this.initialize = function () {
        doInitialize();
    }

    var continentIdLocal;
    var countryIdLocal;
    var regionIdLocal;
    var resortIdLocal;
    var getData;

    this.setDirection = function (continentId, countryId, regionId, resortId) {
        continentIdLocal = continentId;
        countryIdLocal = countryId;
        regionIdLocal = regionId;
        resortIdLocal = resortId;
        if (hasValue(continentId)) {
            if (isLoaded("continents")) {
                setSelectedValue(getGeoLocationItemPath("continents"), continentId);
                getGeoLocationTypes("Countries", getGeoLocationItemPath("countries"), continentId);
            }
            else {
                getGeoLocationTypes("Continents", getGeoLocationItemPath("continents"), null);
            }
        }
        else if (hasValue(countryId)) {
            if (isLoaded("countries")) {
                setSelectedValue(getGeoLocationItemPath("countries"), countryId);
                getGeoLocationTypes("Regions", getGeoLocationItemPath("regions"), countryId);
            }
            else {
                getGeoLocationTypes("Countries", getGeoLocationItemPath("countries"), null);
            }
        }
    }

    this.reset = function () {
        continentIdLocal = null;
        countryIdLocal = null;
        regionIdLocal = null;
        resortIdLocal = null;
        resetAllExceptSelected(-1);
        doInitialize();
    }

    var doInitialize = function () {
        getGeoLocationTypes("Continents", getGeoLocationItemPath("continents"), null);
        getGeoLocationTypes("Countries", getGeoLocationItemPath("countries"), null);
    }

    var getGeoLocationTypes = function (geoLocationType, selectPath, parentId) {
        if (parentId == -1)
            return;
        getData = $.ajax({
            url: "/GeoLocationDirection.ashx",
            dataType: "json",
            data: { geoLocationType: geoLocationType, geoLocationParentId: parentId, catalogItemType: catalogItemType },
            success: function (items) {
                getData = null;
                if (geoLocationType == "Regions" && items.length == 0) {
                    getGeoLocationTypes("Resorts", getGeoLocationItemPath("resorts"), getSelectedItem("countries").value);
                }
                else {
                    var select = $(selectPath).get(0);
                    select.options.length = 1;
                    $.each(items, function (index, item) {
                        select.options[select.options.length] = new Option(item.Value, item.Id);
                    });

                    if (geoLocationType == "Continents" && hasValue(continentIdLocal)) {
                        setContinent(continentIdLocal);
                        continentIdLocal = null;
                    }
                    if (geoLocationType == "Countries" && hasValue(countryIdLocal)) {
                        setCountry(countryIdLocal);
                        countryIdLocal = null;
                    }
                    if (geoLocationType == "Regions" && hasValue(regionIdLocal)) {
                        setRegion(regionIdLocal);
                        regionIdLocal = null;
                    }
                    if (geoLocationType == "Resorts" && hasValue(resortIdLocal)) {
                        setResort(resortIdLocal);
                        regionIdLocal = null;
                    }
                }
            }
        });
    }

    this.onCountriesClick = function () {
        if (!isRequested()) {
            var continents = getSelect(continents);

            if (!isLoaded("countries")) {
                getGeoLocationTypes("Countries", getGeoLocationItemPath("countries"), continents.options[continents.selectedIndex].value);
            }
        }
    }

    this.onRegionsClick = function () {
        if (!isRequested()) {
            var countries = getSelect("countries");

            if (!isLoaded("regions")) {
                getGeoLocationTypes("Regions", getGeoLocationItemPath("regions"), countries.options[countries.selectedIndex].value);
            }
        }
    }

    this.onResortsClick = function () {
        if (!isRequested()) {
            var regions = getSelect("regions");

            if (!isLoaded("resorts")) {
                getGeoLocationTypes("Resorts", getGeoLocationItemPath("resorts"), regions.options[regions.selectedIndex].value);
            }
        }
    }

    this.onContinentsSelectChange = function () {
        updateContinents();
    }

    this.onCountriesSelectChange = function () {
        updateCountries();
    }

    this.onRegionsSelectChange = function () {
        updateRegions();
    }

    this.onResortsSelectChange = function () {
        updateResorts();
    }

    var updateContinents = function () {
        $(getGeoLocationItemPath("continentsLabel")).get(0).innerHTML = getSelectedItem("continents").innerHTML;
        resetAllExceptSelected(0);

        var selectedValue = getSelectedItem("continents").value;
        cancelRequest();
        if (selectedValue == -1) {
            getGeoLocationTypes("Countries", getGeoLocationItemPath("countries"), null);
        }
        else {
            getGeoLocationTypes("Countries", getGeoLocationItemPath("countries"), selectedValue);
        }
    }

    var updateCountries = function () {
        $(getGeoLocationItemPath("countriesLabel")).get(0).innerHTML = getSelectedItem("countries").innerHTML;
        resetAllExceptSelected(1);
        cancelRequest();
        getGeoLocationTypes("Regions", getGeoLocationItemPath("regions"), getSelectedItem("countries").value);
        var country = $(getGeoLocationItemPath("countriesLabel")).get(0).innerHTML;
        $.ajax({
            url: "/GetContinent.ashx",
            data: { country: country },
            dataType: "json",
            success: function (data) {
                $(getGeoLocationItemPath("continentsLabel")).get(0).innerHTML = data.Continent;
            }
        });
    }

    var updateRegions = function () {
        $(getGeoLocationItemPath("regionsLabel")).get(0).innerHTML = getSelectedItem("regions").innerHTML;

        resetAllExceptSelected(2);
        cancelRequest();
        getGeoLocationTypes("Resorts", getGeoLocationItemPath("resorts"), getSelectedItem("regions").value);
    }

    var updateResorts = function () {
        $(getGeoLocationItemPath("resortsLabel")).get(0).innerHTML = getSelectedItem("resorts").innerHTML;
    }

    var setContinent = function (continentId) {
        if (continentId != null) {
            setSelectedValue(getGeoLocationItemPath("continents"), continentId);
            updateContinents();
        }
    }

    var setCountry = function (countryId) {
        if (countryId != null) {
            setSelectedValue(getGeoLocationItemPath("countries"), countryId);
            updateCountries();
        }
    }

    var setRegion = function (regionId) {
        if (regionId != null) {
            setSelectedValue(getGeoLocationItemPath("regions"), regionId);
            updateRegions();
        }
    }

    var setResort = function (resortId) {
        if (resortId != null) {
            setSelectedValue(getGeoLocationItemPath("resorts"), resortId);
        }
    }

    var setLabelValue = function () {
        $(getGeoLocationItemPath("continentsLabel")).get(0).innerHTML = getSelectedItem("continents").innerHTML;
        $(getGeoLocationItemPath("countriesLabel")).get(0).innerHTML = getSelectedItem("countries").innerHTML;
        $(getGeoLocationItemPath("regionsLabel")).get(0).innerHTML = getSelectedItem("regions").innerHTML;
        $(getGeoLocationItemPath("resortsLabel")).get(0).innerHTML = getSelectedItem("resorts").innerHTML;
    }

    var resetAllExceptSelected = function (selectIndex) {
        var selects = $("#directionSearch select");
        for (var i = 0; i < selects.length; i++) {
            if (i > selectIndex) {
                selects[i].length = 1;
                selects[i].selectedIndex = 0;
                setLabelValue();
            }
        }
    }

    var setSelectedValue = function (selectPath, value) {
        var select = $(selectPath).get(0);
        for (var i = 0; i < select.options.length; i++) {
            if (select.options[i].value == value) {
                select.selectedIndex = i;
                setLabelValue();
                break;
            }
        }
    }

    var getGeoLocationItemPath = function (selectId) {
        return "#directionSearch #" + selectId;
    }

    var cancelRequest = function () {
        if (getData != null) {
            getData.abort();
            getData = null;
        }
    }

    var getSelectedItem = function (selectId) {
        return $("#" + selectId).get(0).options[$("#" + selectId).get(0).selectedIndex];
    }

    var isRequested = function () {
        return getData != null;
    }

    var hasValue = function (value) {
        return value != null && value != "" && value != 0;
    }

    var getSelect = function (selectId) {
        return $(getGeoLocationItemPath(selectId)).get(0);
    }

    var isLoaded = function (selectId) {
        return getSelect(selectId).options.length > 1;
    }
}

function registerEscapeButtonFor(element) {
    var $elementObject = $('# ' + element);
    $elementObject.find('input:text, input:password').keypress(function (e) {
        if (e.which == 13) {
            $(this).blur();
            $elementObject.find('input:submit').focus().click();
        }
    });
    $elementObject.find('input:text').focus();
}

function unregisterEscapeButtonFor(element) {
    $('# ' + element).find('input:text, input:password').unbind("keypress");
}
