﻿var currentFavourites = null;
$(document).ready(function() {

    var subs = $('.subscribed');

    if (subs) {
        subs.attr('href', manageFavouritesUrl);
    }
    var fav = $('.add-to-favourites');
    if (fav) {
        fav.click(function(event) {
            if (!this.className.match(/(^|\s+)subscribed($|\s+)/)) {
                event.preventDefault();
                currentFavourites = this;
                showPopup($('#ref-' + this.id.substring("add-to-favourites-".length)).text().replace(/^\s+|\s+$/g, ""));
            }
        });
    }



    $('#popup_hidden .cancel').click(function(event) {
        event.preventDefault();
        hidePopup();
    });


    $('#popup_hidden .save').click(function(event) {
        event.preventDefault();
        saveToFavourites($('#popup_hidden .name').val());
        currentFavourites = null;
        hidePopup();
    });

    function showPopup(region) {
        $("#popup_background").fadeIn("fast");
        $('#popup_hidden').css("display", "block");
        $("#popup_background").fadeTo(0, 0.8);
        $('#popup_hidden .name').val(region + " Property Press");
        $('#popup_hidden .name').select();
    };
    function hidePopup() {
        $('#popup_hidden').css("display", "none");
        $("#popup_background").fadeOut("fast");
        $('#popup_hidden .name').val('');
    };

    function redirectToLoginPage(searchKey) {
        var loginUrl = loginAndSaveToFavouritesUrlPrefix + "&" + getSearchUrlParam();

        if (searchKey != null && searchKey.length > 0) {
            loginUrl = loginUrl + '&searchKey=' + formatSearchKeyForUrl(searchKey);
        }
        window.location.href = loginUrl;
    }

    function getSearchUrlParam() {
        return "searchUrl=" + escape($('#ref-' + currentFavourites.id.substring("add-to-favourites-".length)).attr('href'));
    }

    function saveToFavourites(searchKey) {
        if (!isUserAuthenticated()) {
            redirectToLoginPage(searchKey);
            return;
        }
        var element = document.getElementById(currentFavourites.id);
        if (saveToFavouritesUrlPrefix != null && saveToFavouritesUrlPrefix.length > 0) {
            var saveToFavouritesUrl = saveToFavouritesUrlPrefix + "?" + getSearchUrlParam();
            if (searchKey != null && searchKey.length > 0)
                saveToFavouritesUrl = saveToFavouritesUrl + "&searchKey=" + formatSearchKeyForUrl(searchKey)

            var options = {
                type: "POST",
                url: saveToFavouritesUrl,
                dataType: "json",
                async: false,
                success: function(msg) { },
                error: function(msg) { }
            };
            var returnText = $.ajax(options).responseText;

            var msgs = returnText.replace(/\"/g, '').split(",");

            if (msgs[0] == 'success') {
                element.href = msgs[1];
                element.innerHTML = "Saved";
                $("#" + currentFavourites.id).unbind("click");
            }
            else if (msgs[0] == "failed") {
                /// redirect to login page
                $("#" + currentFavourites.id).unbind("click");
                redirectToLoginPage(searchKey);

            }
        }
    }


    function formatSearchKeyForUrl(searchKey) {
        return escape(searchKey).replace(/[\/]/g, "");
    }

    //    $(".alertFrequency").change(function(event) {
    //        event.preventDefault();
    //        var element = $(this);

    //        var searchId = element[0].id;
    //        var searchvalue = element[0].options[element[0].selectedIndex].value;

    //        if (getUpdateAlertFrequencyLink != null && getUpdateAlertFrequencyLink.length > 0 && searchId && searchvalue) {
    //            var postLink = getUpdateAlertFrequencyLink + "?id=" + searchId + "&value=" + searchvalue;
    //            $.getJSON(postLink, function(data) {
    //                if (data != '') {
    //                    // Display a message
    //                    element.fadeOut(1000, function() {
    //                        element.parent().append("<strong class='addedtext'> Saved </strong>");
    //                    });

    //                    setTimeout(function() {
    //                        $("strong.addedtext").remove();
    //                        element.fadeIn(1000);
    //                    }, 2000);
    //                    //TODO: Remove checkbox selections
    //                }
    //                else {
    //                    //TODO: handle failures
    //                }
    //            });
    //        }
    //    });
});

function isUserAuthenticated() {
    return userAuthenticated;
}

function isInFavourites() {
    return inFavourites;
}
