﻿// Search webservice URL.
var ShortListWSURL = '/Services/ShortList.asmx';
var _shortlistAddCruiseCallback = null;
var _shortlistRemoveCruiseCallback = null;

// Add a cruise to the server-side shortlist, then add to the client display.
// then, address any search Add/remove buttons on the page.
function addCruise(cruiseId) {
    callWebService(ShortListWSURL, 'AddListItem', "{cruiseId: " + cruiseId + "}", function (result) {
        addCruiseToGui(result.d);

        if (_shortlistAddCruiseCallback != null)
            _shortlistAddCruiseCallback(cruiseId);

        // GA Event tracking
        trackClicks('add');
    });
    return false;
}

//This method sets the callback that will get called when a cruise has finished being added to the server side and the front end
function setCruiseAddCallback(cb)
{
    _shortlistAddCruiseCallback = cb;
}

//This method sets the callback that will get called when a cruise has finished being removed from the server side and the front end
function setCruiseRemoveCallback(cb)
{
    _shortlistRemoveCruiseCallback = cb;
}

// Remove the cruise from the server-side shortlist, then remove from the client display.
// then, address any search Add/remove buttons on the page.
function removeCruise(cruiseId) {
    callWebService(ShortListWSURL, 'DeleteListItem', "{cruiseId: " + cruiseId + "}", function (result) {
        removeCruiseFromGui(cruiseId, result.d);

        if (_shortlistRemoveCruiseCallback != null)
            _shortlistRemoveCruiseCallback(cruiseId);

        // GA Event tracking
        trackClicks('remove');
    });
    return false;
}

function trackClicks(type) {
    switch (type) {
        case 'add':
            _gaq.push(['_trackEvent', 'Shortlist', 'Add', 'Add to Shortlist']);
            break;
        case 'remove':
            _gaq.push(['_trackEvent', 'Shortlist', 'Remove', 'Remove from Shortlist']);
            break;
        case 'enquire':
            _gaq.push(['_trackEvent', 'Shortlist', 'Enquire', 'Enquire about the Shortlist']);
            break;
        default:
            alert('Invalid type');
            break;
    }
}

// Undelete 
function undeleteCruise() {
    callWebService(ShortListWSURL, 'UndeleteItem', null, function(result) {
        addCruiseToGui(result.d)
    });
    return false;
}

//Add a cruise to the gui
function addCruiseToGui(result)
{
    // If the result is null, the service has refused to add the item. don't do anything on the shortlist.
    if (result == null)
        return;

    // Force outstanding shortlist animations to end.
    stopShortlistAnimations();
    $(".thisCruise:hidden").css({ height: 0, display: "" }).animate({ height: 30 }, 500);
    $(".addCruiseLink").animate({ opacity: 0.0 }, 500, function() {
        $(this).css({ display: "none", opacity: 1.0 });
        $(".removeCruiseLink").css({ display: ""}).animate({ opacity: 1.0 }, 500);
    })

    removeUndoButton();

    // If (for some reason) we have two copies of the shortlist on the page, this will act on each of them.
    $(".pod").each(function () {

        // If the emptyShortList div is visible, then we need to remove it and
        // display the actual list div, by fading one down, the other up, and changing the height of the shortlist 
        // Appropriately.
        // So, to start, fade out (and shrink) the "empty Shortlist" if it's currently visible.
        $(".emptypod:visible").animate({ height: 0, opacity: 0.0 }, 500, function () {
            $(this).css({ display: "none", opacity: 1.0 });
        }).parent().animate({ height: 176 }, 500, function () {
            // While the fade out above is ongoing, animate the height of the shortlist box down to 1 item (because it was just empty)
            // Once that's done, fade in the actual shortlist.
            // Jquery fade doesn't remove "display:none" in the currently released version (but will in the next).
            $(".podList:hidden").css({ "display": "block" }).hide().fadeIn(400, function () {
                $(this).parent().css("height", "");
            });
        });

        // Create the new shortlist item, append it as the first item in the shortlistlist Div.
        var newListItem = document.createElement('div');
        newListItem.setAttribute("class", "podItem podItem_" + result.CruiseId);

        newListItem.innerHTML = result.ShipName + "<br />";
        newListItem.innerHTML += "<a class=\"redLink podRemoveLink\" style=\"float:right; text-decoration:none !important;\" onclick=\"removeCruise(" + result.CruiseId + ")\">Remove X</a>";
        newListItem.innerHTML += result.SailDate;
        newListItem.innerHTML += " <a class=\"redLink\" href=\"" + result.CruiseUrl + "\">" + result.Price + "pp</a>";

        $(".podList").prepend(newListItem);

        // Do the "flash up the background color, and then fade it down" animation.
        $(".podList > :first-child").attr("class", "podItem podItem_" + result.CruiseId);
        $(".podList > :first-child").css("background-color", "#EDE7B1");
        $(".podList > :first-child").animate({ backgroundColor: "#ffffff" }, 3000);

        // Then find any buttons on the search page targeting this cruise, and set them to remove buttons instead.
        // Then drop focus, so that firefox doesn't leave an ugly line across the button.
        var $searchAddButton = $(".searchAddButton_" + result.CruiseId);

        // remove any onclick attributes
        $searchAddButton.removeAttr('onclick');
        $searchAddButton.attr("class", "shortListButtonAdded iconSprite sprite-addtoshortlistclick searchRemoveButton_" + result.CruiseId);

        var $searchRemoveButton = $(".searchRemoveButton_" + result.CruiseId);
        $searchRemoveButton.unbind("click").click(function () {
            removeCruise(result.CruiseId);
        });

        $searchRemoveButton.blur();
    })
}

// Remove a cruise from the GUI.
function removeCruiseFromGui(cruiseId, result) {
    // Force outstanding animations to end.
    stopShortlistAnimations();

    $(".removeCruiseLink").animate({ opacity: 0.0 }, 500, function () {
        $(this).css({ display: "none", opacity: 1.0 });
        $(".addCruiseLink").css({ display: "" }).animate({ opacity: 1.0 }, 500);
    })

    // Quickly, count the number of items in the shortlist. We're going to need this to decide
    // if we remove the "list" element, and re-show the empty element.
    var listItemCount = 0;

    // Finally, check if there are any items in the shortlist. If not, fade the "empty" dialogue back up.
    $(".podItem").each(function (index, domelement) {
        listItemCount++;
    });

    // shrink the list entry down, then remove it.
    $(".podItem_" + cruiseId).animate({ height: 0, opacity: 0, border: 0, paddingTop: 0, paddingBottom: 0 }, 500, function () {
        $(this).remove();
    });

    // If the "Undo" panel is currently visible, flash it.
    $(".deletedItemUndo:visible").css({ backgroundColor: "#EDE7B1" }).animate({ backgroundColor: "#ffffff" }, 3000);

    // If it's not visible, scroll it open and fade it up at the same time, then flash it back to white.
    $(".deletedItemUndo:hidden").css({ height: 0, paddingTop: 0, paddingBottom: 0, backgroundColor: "#EDE7B1" })
        .animate({ height: 18, paddingTop: 4, paddingBottom: 4, opacity: 1.0 }, 500, function () {
            $(this).animate({ backgroundColor: "#ffffff" }, 3000);
        });

    // Find any search "Remove" buttons, change them to "add" buttons (by tagging them with searchAddButton_CruiseId
    // Also, find the shortlist Add/Remove icon inside the button, and change it to an "add" button.
    // Finally, remove all existing "click" handlers, and make the button add a cruise.
    var $searchRemoveButton = $(".searchRemoveButton_" + cruiseId);

    // remove any onclick attributes
    $searchRemoveButton.removeAttr('onclick');
    $searchRemoveButton.attr("class", "shortListButtonAdd iconSprite sprite-addtoshortlistnormal searchAddButton_" + cruiseId);

    var $searchAddButton = $(".searchAddButton_" + cruiseId);
    $searchAddButton.unbind("click").click(function () {
        addCruise(cruiseId);
    });

    $searchAddButton.blur();

    // Check the number of items in the shortlist, and show the "empty" message if it is.
    if (listItemCount <= 1) {
        $(".podList").animate({ height: 0, opacity: 0.0 }, 500, function () {
            $(this).css({ display: "none", height: "", opacity: "" });
        });
        $(".thisCruise:visible").animate({ height: 0 }, 500).css({ height: "", display: "none" });
        $(".emptypod:hidden").css("height", "0px").animate({ height: 210 }, 400, function () {
            // While the fade out above is ongoing, animate the height of the shortlist box down to 1 item (because it was just empty)
            // Once that's done, fade in the actual shortlist.
            // Jquery fade doesn't remove "display:none" in the currently released version (but will in the next).
            $(this).css("height", "");
        }).fadeIn(500, function () {
            $(this).attr("display", "block");
        })
    }
}

function removeUndoButton() {
    $(".deletedItemUndo:visible").animate({ height: 0, opacity: 0, paddingTop: 0, paddingBottom: 0 }, 500, function() {
        $(this).css("display", "none");
    });
}

function stopShortlistAnimations() {
    $(".addCruiseLink,.removeCruiseLink,.emptypod,.podList,.podList > :first-child,.podItem,.deletedItemUndo,.thisCruise").stop(true, true)
    .parent().stop(true, true);
}

// Call a .net webservice.
function callWebService(webServiceUrl, webMethodName, data, delegateFunction) {
    var url = webServiceUrl + "/" + webMethodName;

    if (data == null || data.length == 0) {
        data = '{}';
    }

    var runningRequest = $.ajax({
        type: "POST",
        url: url,
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: delegateFunction,
        error: function(error) {
            alert("There was an error processing your request.\n"
                    + "[" + error.status + "]"
                    + " [" + error.statusText + "]");
            return false;
        }
    });
    $(window).bind("beforeunload", function() {
        runningRequest.abort();
    });
}


