// 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']) {
        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 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 url = "addToFavorite.php?id=" + tripId + "&chosenTrip=" + options.tripLabelName + "&addFavorite=true";
        url += ("&myfavoriteLabel=" + myfavLabel + "&action=" + action);

        if (ajax) {
            $.ajax({type: "POST",
                url: url,
                dataType: "json",
                success: function (data, status) {
                    if (data.result) {
                        var tripOptions = {action:action, myfavoritesLabel:myfavLabel, checked:true};
                        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 parameters = 'width:300 height:225 outsideClickCloses:false';
        var url = "removeFavorite.php?id=" + tripId + "&chosenTrip=" + options.tripLabelName;
        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};
                        updateFavoriteTrip(options.tripLabelName, message, tripOptions);
                    }
                },
                error: function (req, status, error) {
                    openFBDialog(url, status, parameters);
                }
            });
        } else {
            openFBDialog(url, '', parameters);
        }
    }
}

// Filter functions
function setPriceRange(component) {
    var chosenValue = Number($(component).val());
    var priceStep = 500;
    var minPrice = -1;
    var maxPrice = -1;

    if (chosenValue > 0) {
        maxPrice = chosenValue * priceStep;
        minPrice = maxPrice - priceStep;
    }

    setElementValue("#minPrice", minPrice);
    setElementValue("#maxPrice", maxPrice);
}

// 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;
    }
}