// Page specific functions
function initSearchPage() {
    $("#searchType").change(function () {
        if ($("#searchType").val() == 1) {
            hideComponent("#whereTabOption");
            hideComponent("#where-tab");
            hideComponent("#priceLabel");
            hideComponent("#price");
            hideComponent("#transportationLabel");
            hideComponent("#transportation");
            hideComponent("#ratingLabel");
            hideComponent("#rating");
        } else if ($("#searchType").val() == 2) {
            showComponent("#whereTabOption");
            showComponent("#where-tab");
            showComponent("#priceLabel");
            showComponent("#price");
            showComponent("#transportationLabel");
            showComponent("#transportation");
            showComponent("#ratingLabel");
            showComponent("#rating");
        }
    });
	
    $("#category").change(function () {
        if (Number($("#category").val()) == 8) {
            showComponent("#departurePort");
            showComponent("#departurePortLabel");
        } else {
            hideComponent("#departurePort");
            hideComponent("#departurePortLabel");
        }
    });
	
    $("#nodate").click(function () {
        hideComponent("#setdate");
        enableComponent("#sendBtn");
        $("#chosendate").val($("#nodate").val());
        return true;
    });

    $("#date").click(function () {
        showComponent("#setdate");
        enableComponent("#sendBtn");
        $("#chosendate").val($("#datepicker").val());
        return true;
    });
	
    $("#tabs").tabs();
    $("#priceSlider").slider({
        range: true,
        min: 0,
        max: (Number($("#maxPriceRange").val()) + 0),
        values: [$("#minPrice").val(), $("#maxPrice").val()],
        slide: function(event, ui) {
            setElementValue("#minPrice", ($("#priceSlider").slider("values", 0)));
            setElementValue("#maxPrice", ($("#priceSlider").slider("values", 1)));
            setElementValue("#minAmount", ($("#priceSlider").slider("values", 0)));
            setElementValue("#maxAmount", ($("#priceSlider").slider("values", 1)));
        }
    });
	
    $("#datepicker").datepicker({
        dateFormat: 'dd-mm-yy',
        gotoCurrent: true,
        showButtonPanel: false,
        changeMonth: true,
        changeYear: true,
        onSelect: function(dateText) {
            $("#chosendate").val(dateText);
            enableComponent("#sendBtn");
        }
    });
	
    setToolTip("#category");
    setToolTip("#accommodationType");
    setToolTip("#person");
    setToolTip("#nodate");
    setToolTip("#date");
    setToolTip("#duration");
}

function submitForm(mode) {
    var modeElem = document.getElementById("mode");
    if (modeElem) {
        modeElem.value = mode;
        document.forms[0].submit();
    }
}

function submitFormForFilter(searchType) {
    // if advanced then keep it advanced.
    if (Number(searchType) > Number($("#searchType").val())) {
        setElementValue("#searchType", searchType);
    }
    submitForm("filter");
}

function gotoPage(page) {
    var pageElem = document.getElementById("page");
    if (pageElem) {
        pageElem.value = page;
        submitForm('page');
    }
}

function showMultimedia(data) {
    if (data) {
        var elements = data.split("&");
        for (var index in elements) {
            if (elements[index]) {
                var values = elements[index].split("=");
                if (values[0].match("img")) {
                    $(("#" + values[0])).attr("href", values[1]);
                    $(("#" + values[0] + " img")).attr("src", values[1]);
                    showComponent(("#" + values[0]));
                }
            }
        }
    }
}

function openFBDialog(url, message, parameters) {
    var windowParameters = "width:250 height:200";
    if (parameters) {
        windowParameters = parameters;
    }

    if (fb) {
        var newUrl = (generateNewUrl(url) + ('msg=' + message));
        fb.start({href:newUrl, rev:windowParameters});
    }
}

function closeFBDialog() {
    if (fb) fb.end(true);
}

function updateFavoriteTrip(chosenTrip, message, options) {
    if (chosenTrip && message && !options['tripToBeRemoved']) {
        var useLabel = true;
        if (options.useLabel != null) {
            useLabel = options.useLabel;
        }

        if (useLabel) {
            if (options.checked) $(("#" + chosenTrip)).attr('checked', 'checked');
            else $(("#" + chosenTrip)).removeAttr('checked');

            $(("label[for='" + chosenTrip + "']")).children().remove();
            $(("label[for='" + chosenTrip + "']")).text((message + " "));
            $(("label[for='" + chosenTrip + "'] ~ span.moreinfo")).remove();
            if (options.action == "add") {
                $(("label[for='" + chosenTrip + "']")).parent()
                    .append($("<span>").addClass('moreinfo').addClass('myfavorites')
                        .append($("<a>").attr({href:'favorites.php'})
                            .text(options.myfavoritesLabel)));
            }
        } else {
            $(("#" + chosenTrip)).text((message + " "));
        }
    } else if (options['tripToBeRemoved']) {
        $(('#favorite_' + options.tripToBeRemoved)).remove();
        $(('#favoritedelete_' + options.tripToBeRemoved)).remove();

        var url = window.location.href;
        // remove '#' from url
        var hashPos = window.location.href.indexOf("#");
        if (hashPos >= 0) url = window.location.href.substring(0, hashPos);
        // remove '?' from url
        var questionPos = url.indexOf("?");
        if (questionPos >= 0) url = url.substring(0, questionPos);

        if (url.indexOf('?') < 0) url += "?";
        window.location.href = (url + "page=" + $("#page").val() +"&sort=" + $("#sort").val());
    }
}

function addToFavorite(tripId, message, ajax, options) {
    if (tripId) {
        var action = "add";
        var parameters = 'width:550 height:400 outsideClickCloses:false';
        if (options.isLoggedIn) {
            parameters = 'width:340 height:225 outsideClickCloses:false';
        }
        
        var myfavLabel = options.myfavoritesLabel;
        var useLabel = options.useLabel;
        var url = "addToFavorite.php?id=" + tripId + "&chosenTrip=" + options.tripLabelName + "&addFavorite=true";
        url += ("&myfavoriteLabel=" + myfavLabel + "&action=" + action + "&useLabel=" + useLabel);

        if (ajax) {
            $.ajax({type: "POST",
                url: url,
                dataType: "json",
                success: function (data, status) {
                    if (data.result) {
                        var tripOptions = {action:action, myfavoritesLabel:myfavLabel, checked:true, useLabel: useLabel};
                        updateFavoriteTrip(options.tripLabelName, message, tripOptions);
                    }
                },
                error: function (req, status, error) {
                    openFBDialog(url, status, parameters);
                }
            });
        } else {
            openFBDialog(url, '', parameters);
        }
    }
}

function removeFavorite(tripId, message, ajax, options) {
    if (tripId) {
        var action = "remove";
        var tripToBeRemoved = null;
        if (options.tripToBeRemoved) tripToBeRemoved = options.tripToBeRemoved;

        var myfavLabel = options.myfavoritesLabel;
        var useLabel = options.useLabel;
        var parameters = 'width:300 height:225 outsideClickCloses:false';
        var url = "removeFavorite.php?id=" + tripId + "&chosenTrip=" + options.tripLabelName + "&useLabel=" + useLabel;
        if (tripToBeRemoved) url += "&tripToBeRemoved=" + tripToBeRemoved;

        if (ajax) {
            $.ajax({type: "POST",
                url: url,
                data: {action: action, removeFavorite: "true"},
                dataType: "json",
                success: function (data, status) {
                    if (data.result) {
                        var tripOptions = {action:action, myfavoritesLabel:myfavLabel, checked:false,
                            tripToBeRemoved:tripToBeRemoved, useLabel: useLabel};
                        updateFavoriteTrip(options.tripLabelName, message, tripOptions);
                    }
                },
                error: function (req, status, error) {
                    openFBDialog(url, status, parameters);
                }
            });
        } else {
            openFBDialog(url, '', parameters);
        }
    }
}

// Filter functions
function changeText(id, text) {
    if ($(id).length > 0) {
        $(id).text(text);
    }
}

function determinePriceRange(value, step) {
    var result = [];
    var minPrice = -1;
    var maxPrice = -1;

    if (value > 0) {
        maxPrice = value * step;
        minPrice = maxPrice - step;
        result = [minPrice, maxPrice];
    }
    return result;
}

function setPriceRange(component) {
    var prices = [-1, -1];
    if (component) {
        var id = component.id;
        if (id && id.length > "price".length) {
            if (!$(component).hasClass('filter_field_bold')) {
                var chosenValue = new Number(id.substring("price".length, id.length));
                if (chosenValue > 0) {
                    if (chosenValue < 6) {
                        // each step is by hunderd
                        prices = determinePriceRange(chosenValue, 100);
                    } else if (chosenValue < 8) {
                        // each step is by 250
                        prices = determinePriceRange((chosenValue - 3), 250);
                    } else if (chosenValue < 10) {
                        // each step is by 500
                        prices = determinePriceRange((chosenValue - 5), 500);
                    } else {
                        // each step is by above max amount
                        prices = [2000, -1];
                    }
                }
            }
        }
    }

    setElementValue("#minPrice", prices[0]);
    setElementValue("#maxPrice", prices[1]);
}

function setValue(component, fieldName, defaultValue) {
    var result = defaultValue;
    if (component) {
        var id = component.id;
        if (id && id.length > fieldName.length) {
            if (!$(component).hasClass('filter_field_bold')) {
                result = id.substring(fieldName.length, id.length);
            }
        }
    }
    document.forms[0].elements[fieldName].value = result;
}

// Generic functions
function generateNewUrl(url) {
    var result = url;
    if (url.indexOf('?') >= 0) {
        result += '&';
    } else {
        result += '?';
    }
    return result;
}

function showElement(component, subcomponent) {
    $(component).click(function () {
        showComponent(subcomponent);
        return true;
    });
}

function showComponent(component) {
    if (!$(component).is(":visible")) {
        $(component).show("scale", {
            percent: 100
        }, "slow");
    }
}

function enableComponent(component) {
    if ($(component).is(":disabled")) {
        $(component).removeAttr("disabled");
    }
}

function hideElement(component, subcomponent) {
    $(component).click(function () {
        hideComponent(subcomponent);
        return true;
    });
}

function hideComponent(component) {
    if ($(component).is(":visible")) {
        $(component).hide("scale", {
            percent: 100
        }, "slow");
    }
}

function disableComponent(component) {
    if ($(component).is(":enabled")) {
        $(component).attr("disabled","disabled");
    }
}

function setToolTip(component) {
    $(component).tooltip();
}

function setElementValue(component, value) {
    $(component).val(value);
}

function changeCursor(obj, cursor) {
    if (obj) {
        obj.style.cursor='none';
        obj.style.cursor=cursor;
    }
}

function openInNewWindow(url) {
    window.open(url);
    return false;
}
