/* 
 * JavaScript to provide the user with a selectbox which is rendered / styled
 * Parameters:
 * style: standard|button - *Currently only button option is implemented*
 * title: Only required for button type option
 * height: Display height before scrolling
 * width: Display width before scrolling
 * onselect: The JavaScript function when an option is selected. Returns 
 * userparams: A JavaScript object that the user supplies to be supplied back to the above call back functions
 * 
 */


WebstoreJavaScriptContext.prototype.decoratedSelect = function(args)
{
    if (args == "destroy")
    {
        destroy(this.elements);
        return;
    }
    
    // Always supply arguements to avoid null problems
    if (args == null) args = {};
    args.refWindow = parent;
    if (args.style == null) args.style = "standard";
    if (args.title == null) args.title = "Select";
    

    for (var i=0; i<this.elements.length; i++)
    {
        // Save the args onto the elements context
        this.elements[i].decoratedSelectArgs = jQuery.extend(true, {}, args);
        this.elements[i].decoratedSelectArgs.select = this.elements[i];
        this.elements[i].decoratedSelectArgs.button = $(this.elements[i]);

        
        // Get classes and styles of the element before hiding it
        var extraCssClasses = $(this.elements[i]).attr("class");
        if (extraCssClasses == null) extraCssClasses = "";
        
        var extraCssStyle = $(this.elements[i]).attr("style");
        if (extraCssStyle == null) extraCssStyle = "";
        
        // First hide the current select
        $(this.elements[i]).hide();
        
        
        var selectOptions = "";
        
        var options = $('option', this.elements[i]);
        for (var j=0; j<options.length; j++)
        {
            selectOptions += "<div value='" + $(options[j]).val() + "' url='" + $(options[j]).attr("url") + "'>" + $(options[j]).text() + "</div>";
        }
        
        $(this.elements[i]).after("<div class='ws-select-container " + extraCssClasses + "' style='" + extraCssStyle + "'>" + 
                                    "<input type='button' style='display: block' />" + 
                                    "<div class='ws-select-options-shadow'><div class='ws-select-options'>" + 
                                        selectOptions +
                                    "</div></div>" +
                                    "</div>");

        var element = $(this.elements[i]).next();
        var buttonElement = $(element).find("input[type='button']");
        element[0].decoratedSelectArgs = this.elements[i].decoratedSelectArgs;
        
        // Set the width if one is specified
        if (this.elements[i].decoratedSelectArgs.width != null)
            $(element).css("width", this.elements[i].decoratedSelectArgs.width);
        
        var buttonTitle;
        var externalPath = this.elements[i].decoratedSelectArgs.externalPath;
        var external = this.elements[i].decoratedSelectArgs.external;
        if (external == true) {
            buttonTitle = "<span style='float: right;' class='ui-icon ui-icon-triangle-1-s externalTriangle'></span><span class='externalTitle'>" + 
                                    this.elements[i].decoratedSelectArgs.title + "</span>";
        } else {
            buttonTitle = "<span class='left ui-icon ui-icon-triangle-1-s'></span>" + 
                                    this.elements[i].decoratedSelectArgs.title;
        }
        $ws(buttonElement).button({
            title: buttonTitle,
            external: external,
            onclick: function()
            {
                var thisSelect = $(this).parents(".ws-select-container").filter(":first");
                var selectDropDown = $(thisSelect).find(".ws-select-options-shadow");
                var selectableDropElements = $(thisSelect).find(".ws-select-options div");

                var hoveringButton = true;
                var hoveringMenu = true;

                // Show the selects dropdown menu
                selectDropDown.slideDown("fast");

                if (external == true && selectableDropElements.length == 0) {
                    //$(thisSelect).find(".ws-select-options").append("<div id=\"externalLoading\" style=\"text-align: centre;\">Loading...</div>");
                    $(thisSelect).find(".ws-select-options").append("<div id=\"externalLoading\" style=\"border: 1px #000000 solid;\"><img style=\"height: 15px; margin-left: 25px; margin-right: 10px;\" src=\"/w/images/ajax-loading-bar-20.gif\">");
                    $.ajax({
                        context: this,
                        url: "/w/wishlist/list.ajax",
                        global: false,
                        type: "GET",
                        data: null,
                        dataType: "json",
                        success: function(data)
                        {
                            $(thisSelect).find("#externalLoading").remove();
                            if ($(thisSelect).find(".ws-select-options div").length == 0) {
                                if (data.length == 0) {
                                    $("select[name='externalWishList']").next().find(".ws-select-options").append("<div value=\"default\" style=\"padding-left: 0px;\"><div class=\"externalSquare\" style=\"padding: 0px; background-color: rgb(146, 188, 255);\"></div>Default</div>");
                                } else {
                                    for (var i = 0; i < data.length; i++) {
                                        $("select[name='externalWishList']").next().find(".ws-select-options").append("<div value=\""+data[i].id+"\" style=\"padding-left: 0px;\"><div class=\"externalSquare\" style=\"padding: 0px; background-color: "+data[i].colour+";\"></div>"+data[i].name+"</div>");
                                    }
                                }
                            }
                            
                            $(thisSelect).find(".ws-select-options div").click(onSelectableDropElementsClick);
                            
                            //selectDropDown.slideUp("fast", function() {
                            //    $(thisSelect).find("#externalLoading").remove();
                            //    selectDropDown.slideDown("fast");
                            //    for (var i = 0; i < data.length; i++) {
                            //        $("select[name='externalWishList']").next().find(".ws-select-options").append("<div value=\""+data[i].id+"\" style=\"padding-left: 0px;\"><div class=\"externalSquare\" style=\"padding: 0px; background-color: "+data[i].colour+";\"></div>"+data[i].name+"</div>");
                            //    }
                            //});
                        }
                    });
                }

                function checkIfStillHovering()
                {
                    // Hide the menu if the hover events are still there
                    if (!hoveringButton && !hoveringMenu)
                    {
                        selectDropDown.slideUp("fast");

                        // unbind events to prevent leaks
                        $(thisSelect).unbind("hover");
                        $(selectDropDown).unbind("hover");
                        $(selectableDropElements).unbind("click");
                    }
                }

                $(this).hover(
                    function() {
                        hoveringButton = true;
                    },
                    function() {
                        hoveringButton = false;
                        setTimeout(checkIfStillHovering, 100);
                    }
                );

                $(selectDropDown).hover(
                    function() {
                        hoveringMenu = true;
                    },
                    function() {
                        hoveringMenu = false;
                        setTimeout(checkIfStillHovering, 100);
                    }
                );

                $(selectableDropElements).click(onSelectableDropElementsClick);
                
                // Define the method for clicking on a select list entry so it can be used elsewhere
                function onSelectableDropElementsClick()
                {
                    if (thisSelect[0].decoratedSelectArgs.onselect != null && jQuery.isFunction(thisSelect[0].decoratedSelectArgs.onselect))
                                    thisSelect[0].decoratedSelectArgs.onselect(thisSelect[0].decoratedSelectArgs.select,
                                                                                $(this).attr("value"), 
                                                                                $(this).html(), 
                                                                                thisSelect[0].decoratedSelectArgs.userParams);
                }
            }
        });
        if (external == true) {
            buttonElement.next().find(".externalTitle").bind('unclick');
            buttonElement.next().find(".externalTitle").bind('click', function (event) {
                window.location = externalPath;
                event.stopPropagation();
            });
        }
    }
    
    // Functions declared within this JS plugins scope
    function destroy(elements)
    {
        if (elements == null) return;
        
        for (var i=0; i<elements.length; i++)
        {
            // Destroy the args and glow components for this element
            if (elements[i].decoratedSelectArgs != null)
            {
                //$(elements[i]).unbind("click");
                elements[i].decoratedSelectArgs = null;
            }
        }
    }
}

