/* 
 * Javascript that provides UI interactions with any of the wishlist specific tools. I.e empty, edit, create, sort, filter
 * 
 */

window.wishlist = new Wishlist();

function Wishlist()
{  }

Wishlist.prototype.externalWishList = function(args)
{
    $ws("select[name='externalWishList']").decoratedSelect("destroy");
    $("select[name='externalWishList']").each(function()
    {
        var productCode = $(this).attr("productCode");
        
        $ws(this).decoratedSelect(
        {
            title: "Add to Wishlist",
            external: true,
            externalPath: args.masterUrl + "addEntry.jhtml?productCodes="+productCode,
            onselect: function(select, key, value, userParams)
            {
                if (key == "") {
                    window.location = args.masterUrl;
                } else if (key == "default") {
                    window.location = args.masterUrl + "addEntry.jhtml?productCodes="+productCode;
                } else {
                    window.location = args.masterUrl + "addEntry.jhtml?productCodes="+productCode+"&id="+key;
                }
            }
        });
    });
}

/*
 * Javascript that performs selecting a wishlist from a drop down.
 *
 * Parameters:
 *   masterUrl: The url to call the master list
 *   
 *   
 */
Wishlist.prototype.selectWishList = function(args)
{
    $ws("select[name='selectWishList']").decoratedSelect("destroy");
    $ws("select[name='selectWishList']").decoratedSelect(
    {
        title: "select list",
        onselect: function(select, key, value, userParams) 
        {
            if (key == "")
                window.location = args.masterUrl;
            else {
                //get the full url  from the option so that the jsession id isn't stuck in the middle
                var url = $(select).next().find(".ws-select-options").find("[value='" + key + "']").attr("url");
                window.location = url;
            }
        }
    });
}


/*
 * Javascript that performs creating a wishlist from a button.
 *
 * Parameters:
 *   createUrl: The url to call the master list
 *   
 *   
 */
Wishlist.prototype.createWishList = function(args)
{
    $ws("input[name='createWishList']").formDialogue({
        height: 450,
        title: 'Create New List',
        url: args.createUrl,
        oncomplete: function(button, userParams, returnJSON) {
            window.location.reload();
        }
    });
}


/*
 * Javascript that performs updating a wishlist from a button.
 *
 * Parameters:
 *   updateUrl: The url to for calling the update
 *   
 *   
 */
Wishlist.prototype.updateWishList = function(args)
{
    $("a.ws-wishlist-update").each(function()
    {
        var listId = $(this).attr("listId");
        
        $ws(this).formDialogue(
        {
            height: 450,
            title: 'Update List',
            url: args.updateUrl + "?id=" + listId,
            oncomplete: function(button, userParams, returnJSON) {
                window.location.reload();
            }
        });
    });
}

/*
 * Javascript that performs sharing a wishlist from a button.
 *
 * Parameters:
 *   shareUrl: The url to call the master list
 *   
 *   
 */
Wishlist.prototype.shareWishList = function(args)
{
    $("input[name='shareWishList'],a.ws-wishlist-share").each(function()
    {
        var listId = $(this).attr("listId");
        $ws(this).formDialogue(
        {
            title: 'Share List',
            url: args.shareUrl + "?id=" + listId,
            height: "600",
            oncomplete: function(button, userParams, returnJSON) {
                window.location.reload();
            }
        });
    });
}

Wishlist.prototype.confirmShareWishList = function(args)
{
    $ws("input[name=confirmShareWishList],a.ws-wishlist-confirmshare").confirmDialogue(
    {
        title: 'Share List',
        desc: "Are you sure you want to share this list? It is empty.",
        onok: function(thisElement)
        {
            $button = $(thisElement).parent().find('.ws-wishlist-share .ui-corner-all');
            if ($button.length > 0) {
                $button.trigger('click');
            } else {
                $(thisElement).parent().parent().find('.ws-wishlist-share').trigger('click');
            }
        }
    });
}
/*
 * Javascript that empties a wishlist list using a button.
 *
 * Parameters:
 *   emptyUrl: The url to call the master list
 *   
 *   
 */
Wishlist.prototype.emptyWishList = function(args)
{
    $ws("input[name=emptyWishList]").confirmDialogue(
    {
        title: 'Empty List',
        desc: "Are you sure you want to empty this list?",
        onok: function(thisElement)
        {
            var listId =  $(thisElement).attr("listId");
            
            $ws().ajaxProcessing(
            {
                url: args.emptyUrl + "?id=" + listId,
                returnType: 'json',
                success: function(json)
                {
                    $("#" + listId).find(".ws-wishlist-entry").remove();
                    wishlistEntry.updateWishListEntriesDom();
                },
                error: function(e)
                {
                    //Alert re: error, reason why not added.
                    alert("There was an error whilst trying to empty your wishlist. Your page will be automatically refreshed after you click ok.");
                    window.location.reload();
                }
            });
        }
    });
}


/*
 * Javascript that deletes a wishlist list using a button.
 *
 * Parameters:
 *   deleteUrl: The url to delete the list
 *   defaultUrl: The url to goto the master list
 *   
 *   
 */
Wishlist.prototype.deleteWishList = function(args)
{
    $ws("input[name=deleteWishList]").confirmDialogue(
    {
        title: 'Delete List',
        desc: "Are you sure you want to delete this list?",
        onok: function(thisElement)
        {
            var listId =  $(thisElement).attr("listId");
            
            $ws().ajaxProcessing(
            {
                url: args.deleteUrl + "?id=" + listId,
                returnType: 'json',
                success: function(json)
                {
                    window.location = args.defaultUrl;
                },
                error: function(e)
                {
                    //Alert re: error, reason why not added.
                    alert("There was an error whilst trying to delete your wishlist. Your page will be automatically refreshed after you click ok.");
                    window.location.reload();
                }
            });
        }
    });
}


/*
 * Javascript that puts all wishlist items into the shopping basket.
 *
 * Parameters:
 *   basketAddUrl: The url where the webstore is located
 *   imagesUrl: The url where images are stored
 *   
 *   
 */
Wishlist.prototype.purchaseAllItems = function(args)
{
    $ws("input[name='purchaseAllItems']").button(
    {
        onclick: function(userparams, buttonArgs)
        {
            // Get the list that this button belong too, and the products within it
            var listId = $(buttonArgs.button).attr("listId");
            var items = $("#" + listId).find(".ws-wishlist-entry");
            
            var productCode = "";
            var quantity = "";
            
            $.each(items, function() 
            {
                if (productCode != "")
                    productCode += "&";
                
                productCode += "productCodes=" + $(this).attr("productCode");
                quantity += "&quantities=" + $(this).find(".item-quantity").val();
            });
            
            var button = this;

            $ws().ajaxProcessing(
            {
                url: args.basketAddUrl + "?" + productCode + quantity,
                returnType: 'json',
                success: function(json, userparams) 
                {
                    var message = "";
                    
                    for (var i=0; i<json.successfulProducts.length; i++)
                    {
                        var title = $("tr[productCode=" + json.successfulProducts[i] + "]").attr("title");
                        message += "<div class='ui-icon ui-icon-check left'></div><div class='left'>Successfully added product '" + title + "' to your shopping basket.</div>";
                    }
                    
                    for(var key in json.unsuccessfulProducts)
                    {
                        var title = $("tr[productCode=" + key + "]").attr("title");
                        message += "<div class='ui-icon ui-icon-closethick left'></div><div class='red left'>Sorry product '" + title + "' could not be added to your shopping basket: " + json.unsuccessfulProducts[key] + "</div>";
                    }
                    
                    // Create the bubble and show it
                    $(button).CreateBubblePopup(
                    {
                        innerHtml: message,
                        position: 'right',
                        manageMouseEvents: false,
                        selectable: true,
                        width: 200,
                        themeName: 'black',
                        themePath: args.imagesUrl + 'jquerybubblepopup-theme'
                    });
                    
                    $(button).ShowBubblePopup();
                    
                    // get the id of the bubble popup
                    var bubbleId = $(button).GetBubblePopupID();
                    
                    // Now attach the close button to this window (its an ajax one)
                    $('#' + bubbleId).find(".jquerybubblepopup-top-right").append("<div style='position: absolute'><img src='" + args.imagesUrl + "jquerybubblepopup-theme/close.png' style='position: relative; left: -8px; top: -10px; cursor: pointer;'/></div>");

                    $('#' + bubbleId).find(".jquerybubblepopup-top-right").find("img").click(function(){
                        $(button).HideAllBubblePopups();
                    });

                },
                error: function(e)
                {
                    //Alert re: error, reason why not added.
                    alert("There was an error whilst trying to add your wishlist to your basket. Your page will be automatically refreshed after you click ok.");
                    window.location.reload();
                }
            });

            return false;
        }
    });
}


/*
 * Javascript that toggles whether all the entries in a given list are showing or hiding.
 *
 * Parameters:
 *   None
 *    
 */
Wishlist.prototype.toggleExpandAllEntries = function(args)
{
    var showAllItemsHtml = "<div class='ws-wishlist-show-entries-icon ws-wishlist-show-entries-expand right'></div><div class='right' style='margin-top: 3px; margin-right: 3px;'>Show all Items</div><div class='clear'></div>";
    var hideAllItemsHtml = "<div class='ws-wishlist-show-entries-icon ws-wishlist-show-entries-hide right'></div><div class='right' style='margin-top: 3px; margin-right: 3px;'>Minimise Items</div><div class='clear'></div>";
    
    $(".ws-wishlist-entry").show();
    
    // First check to see if any of the lists have more than 3 items. If so they need to be hidden and the expand toggle needs adding
    $(".ws-wishlist").each(function()
    {
        var entries = $(this).find(".ws-wishlist-entry");
        
        // if there are more than 3 items then go through and hide them
        if ($(this).find(".ws-wishlist-entry:visible").length > 3)
        {
            for (var i=3; i<entries.length; i++)
                $(entries[i]).hide();
            
            $(this).find(".ws-wishlist-show-entries").parents("tr").filter(":first").show();
            $(this).find(".ws-wishlist-show-entries").html(showAllItemsHtml);
        }
    });
    
    $(".ws-wishlist-show-entries").unbind("click");
    $(".ws-wishlist-show-entries").click(function()
    {
        // Get the entries in the list
        var entries = $(this).parents(".ws-wishlist").find(".ws-wishlist-entry");
        
        // Check to see what state the entries are in (hidden or expanded)
        if ($(this).parents(".ws-wishlist").find(".ws-wishlist-entry:visible").length > 3)
        {
            for (var i=3; i<entries.length; i++)
                $(entries[i]).hide();
            
            $(this).html(showAllItemsHtml);
        }
        else
        {
            entries.show();
            $(this).html(hideAllItemsHtml);
        }
        
        return false;
    });
}


/*
 * Javascript that decorates the sort select
 *
 * Parameters:
 *   none
 *    
 */
Wishlist.prototype.sortListBy = function(args)
{
    $ws("select[name='sort']").decoratedSelect("destroy");
    
    $("select[name='sort']").each(function()
    {
        var sortBySelected = $(this).find("option[selected='true']").text();
        
        if(args){
            $(this).parents("form").attr("action",args.sortUrl);
        }
        
        $ws(this).decoratedSelect(
        {
            title: sortBySelected,
            onselect: function(select, key, value, userParams) 
            {
                // Set the value of the select and submit the form
                $(select).val(key);
                
                $(select).parents("form").filter(":first").submit();
            }
        });
    });
}


Wishlist.prototype.backToMaster = function(args)
{
    $ws("input[name='backToMaster']").button(
    {
        onclick: function(userparams, buttonArgs)
        {
            window.location = args.masterUrl;
        }
    });
}

