﻿function Favorites(parent, pID)
{
    var parentElement = parent,
                currentControl = this,
                providerID = pID;

    this.anchorTag = null;
    this.isFavorite = false;
    this.Unload = function Seansoft$Favorites$Unload()
    {
        parentElement.removeChild(childDivs[0].parentNode);
        currentControl = null;
    };

    this.SetupElements = function Seansoft$Favorites$SetupElements()
    {
        currentControl.anchorTag = document.createElement("a");
        // Get server data for isFavorite
        $.get('/Member/GetFavorite/' + providerID, function(data)
        {
            // Setup the favorite value
            currentControl.isFavorite = data.isFavorite;
            // Setup label for favorites link
            currentControl.SetLinkLabel();
        });

        // Setup click event for favorites link
        $(currentControl.anchorTag).click(function() { currentControl.UpdateFavoriteStatus(); });

        // Add us to the screen
        parentElement.appendChild(currentControl.anchorTag);
    };

    this.SetLinkLabel = function Seansoft$Favorites$SetLinkLabel()
    {
        // Default to add
        var linkLabel = "Add to favorites";
        if (currentControl.isFavorite)
        {
            // Provider is not yet marked as favorite by the user, enable
            linkLabel = "Remove favorite";
        }
        currentControl.anchorTag.innerText = linkLabel;
    };

    this.UpdateFavoriteStatus = function Seansoft$Favorites$UpdateFavoriteStatus()
    {
        if (currentControl.isFavorite)
        {
            $.get('/Member/RemoveFavorite/' + providerID, function(data)
            {
                currentControl.isFavorite = false;
                currentControl.SetLinkLabel(); 
            });
        }
        else
        {
            $.get('/Member/AddFavorite/' + providerID, function(data)
            {
                currentControl.isFavorite = true;
                currentControl.SetLinkLabel(); 
            });
        }
    };
    currentControl.SetupElements();
}
