$(function()
{
    var authenticationUrl = $('#tripPlannerAuthenticationUrl').attr('content');
    $('.favouritesSave').each(function()
    {
        new FavouriteSaveButton(this, authenticationUrl);
    });
});

function FavouriteSaveButton(domElement, authenticationUrl)
{

    this.init = function(domElement, authenticationUrl)
    {
        this.authenticationUrl = authenticationUrl;
        this.button = $(domElement);
        this.button.click(callback(this, 'authenticateAndSave'));
        this.button.ie6PNGFix();
    }

    this.authenticateAndSave = function()
    {
        jQuery.getJSON(this.authenticationUrl, callback(this, 'save'));
    }

    this.save = function(response)
    {
        if (response.authenticated)
        {
            this.ajaxSave();
        }
        else
        {
            this.nonAjaxSave();
        }
    }

    this.ajaxSave = function()
    {
        this.message = $("<span class='favouritesSave saving'>SAVING...</span>");
        this.button.after(this.message).remove();
        jQuery.ajax({
            url: this.button.attr('href') + '&redirect=false',
            success: callback(this, 'success'),
            error: callback(this, 'error')
        });
    }

    this.nonAjaxSave = function()
    {
        document.location = this.button.attr('href');
    }

    this.success = function(data, statusText)
    {
        this.message.removeClass('saving').empty();
        this.message.addClass('saved').append('<span>Saved</span>').append('to your favourites in your profile');
        this.message.children('span').ie6PNGFix();
    }

    this.error = function(data, statusText)
    {
        this.message.removeClass('saving').empty();
        this.message.addClass('error').append("Sorry, that didn't work. Why not try again later?");
    }

    this.init(domElement, authenticationUrl);
}

function callback(object, methodName)
{
    var context = object;
    return function(param1, param2)
    {
        context[methodName](param1, param2);
        return false;
    }
}