/*global jQuery, window, alert, console */
 (function($) {
    function showMessage(message, isError) {
        var messageClass = "ui-state-highlight";
        if (isError) {
            messageClass = "ui-state-error";
        }
        var html =
        $('<div class="ui-widget ui-helper-hidden">' +
        '<div class="' + messageClass + ' ui-corner-all" style="padding: 0 .7em;">' +
        '<p><span class="ui-icon ' + (isError ? 'ui-icon-alert': 'ui-icon-info') + ' style="float: left; margin-right: .3em;"></span>' +
        (isError ? '<strong>Error: </strong>': '') + message + '</p>' +
        '</div>' +
        '</div>');

        html.click(function() {
            $('#message').slideUp('slow',
            function() { 
                $('#message').empty();
            });
        });
        $("#message").append(html);
        html.slideDown('slow');
    }



    $.freemix = {
        log: function(message) {
            if (window.console && console.log) {
                console.log(message);
            } else if (window.dump) {
                dump(message);
            }
        },
        getTemplates: function() {
            if (!this._templates) {
                this._templates = $("#templates");
            }
            return this._templates;
        },
        getTemplate: function(template) {
            return $("div#" + template, this.getTemplates()).clone();
        },
        template: function(url, success, cacheLabel) {

            if (cacheLabel) {
                var cache = $("div#" + cacheLabel, $.freemix.getTemplates());
                if (cache.size() === 0) {
                    cache = $("<div id='" + cacheLabel + "'></div>");
                    $.freemix.getTemplates().append(cache);
                    $.ajax({
                        url: url,
                        dataType: "html",
                        success: function(data, status) {
                            // Test the cache again to look for simultaneous loads
                            cache.append($(data));
                            success(data, status);
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown) {
                            $.freemix.error(textStatus, true);
                            $.freemix.log("Status: " + textStatus + "\nError: " + errorThrown);
                        }
                    });
                } else {
                    success(cache.children().clone(), "");
                }
            } else {
                $.ajax({
                    url: url,
                    dataType: "html",
                    cache: true,
                    success: success,
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        $.freemix.error(textStatus, true);
                        $.freemix.log("Status: " + textStatus + "\nError: " + errorThrown);
                    }
                });
            }

        },
        info: function(message) {
            showMessage(message, false);
        },
        error: function(message) {
            showMessage(message, true);
        },
        renderExhibitProperty: function(metadata) {
            var property = $.freemix.property.propertyList[metadata.property];
            if (property.enabled()) {
                return property.getExhibitHtml($.freemix.deriveType(metadata));
            } else {
                return "";
            }
        },
        deriveType: function(metadata) {
            var type = metadata.defaultType || $.freemix.property.propertyList[metadata.property].defaultType();
            return type;

        },
        prototypes: {
            container: {
                id: "",
                getPopupButton: function() {
                    return this.findWidget().find(".popup-button");
                },
                setPopupContent: function(content) {
                    var api = this.popupApi();
                    api.updateContent("<div style='display:none;'></div>");
                    api.updateContent(content);
                },
                popupApi: function() {
                    return this.getPopupButton().qtip("api");
                },
                hidePopup: function() {
                    this.getPopupButton().qtip("hide");
                }
            },
            widget: {
                config: {
                    id: "",
                    name: ""
                },
                findWidget: function() {
                    if (!this._selector) {
                        this._selector = this.generateWidget();
                    }
                    return this._selector;
                },
                getConfig: function() {
                    return this.config;
                },
                remove: function() {
                    this.findWidget().remove();
                },
                rename: function(name) {
                    this.config.name = name;
                    this.findWidget().find("span.label").text(name);
                },
                hidePopup: function() {
                    this.findWidget().find(".popup-button").qtip("hide");
                },
                setPopupContent: function(content) {
                    var api = this.popupApi();
                    api.updateContent("<div style='display:none;'></div>");
                    api.updateContent(content);
                },
                popupApi: function() {
                    return this.findWidget().find(".popup-button").qtip("api");
                },
                getPopupContent: function() {
                    var w = this;
                    return $("<span><a href='#' class='rename'>Rename</a> | <a href='#' class='delete'>Delete</a></span>")
                    .find(".rename").click(function() {
                        var dialog = $("<span><input type='text' value='" + w.config.name +
                            "' id='rename-component' /><div class='rename-component-buttons'>" +
                            "<span class='button ui-state-default ui-corner-all'>OK</span>" +
                            "<span class='button ui-state-default ui-corner-all'>Cancel</span></div></span>");
                        dialog.keydown(function(e) {
                            var code = (e.keyCode ? e.keyCode: e.which);
                            if (code == $.ui.keyCode.ENTER) {
                                var value = $('input#rename-component', w.popupApi().elements.content).val();
                                w.rename(value);
                                w.hidePopup();
                            } else if (code == $.ui.keyCode.ESCAPE) {
                                w.hidePopup();
                            }
                        });
                        dialog.find('span.button:eq(0)').bind('click',function() {
                            var value = $('input#rename-component', w.popupApi().elements.content).val();
                            w.rename(value);
                            w.hidePopup();
                        });
                        dialog.find('span.button:eq(1)').bind('click',function() {
                            w.hidePopup();
                        });
                        w.setPopupContent(dialog);
                        w.popupApi().elements.content.find("input#rename-component").focus();
                        return false;
                    }).end()
                    .find(".delete").click(function() {
                        w.hidePopup();
                        w.remove();
                    }).end();
                }
            }
        }
    };

    $.fn.freemixButton = function(prop) {
        return this.each(function() {
            if (prop === "remove") {
                $(this).unbind();
            } else {
                $(this).hover(
                    function() {
                        $(this).addClass('ui-state-hover');
                    },
                    function() {
                        $(this).removeClass('ui-state-hover');
                    }
                )
                .click(prop)
                .mousedown(function() {$(this).addClass("ui-state-active");})
                .mouseup(function() {$(this).removeClass("ui-state-active");});
            }
        });

    };

    $.fn.freemixPopupButton = function(title, contentFunction, config) {
        return this.each(function() {
            var $this = $(this);
            $this.qtip($.extend(true, {
                content: {
                    text: "<div style='display:none;'></div>",
                    title: {
                        text: title,
                        button: "<span class='ui-icon ui-icon-closethick'/>"
                    }
                },
                position: {
                    adjust: {
                        screen: true
                    }
                },
                show: 'click',
                hide: 'unfocus',
                style: {
                    name: 'themeroller'
                }
            },
            config));

            var api = $this.qtip("api");
            api.beforeShow = function(event) {
                api.updateContent("<div style='display:none;'></div>");
                api.updateContent(contentFunction());
            };

        });
    };

    $.fn.freemixThumbnails = function(tags, items, clickHandler) {
        return this.each(function() {
            var list = $("<ul></ul");
            $.each(tags,function(key, tag) {
                var item = items[tag];
                item.id = key;
                $("<a href='' title='" + item.label + "'><img src='" + item.thumbnail +
                    "' alt='" + item.label + "' title='" + item.label + "'/><span class='chooser-item-name'>" +
                    item.label + "</span></a>")
                .click(function() {
                    clickHandler(item);
                    return false;
                })
                .appendTo(list)
                .wrap("<li></li>");
            });
            list.appendTo($(this));
        });
    };

    $.fn.createChildCheck = function(config) {
        return this.each(function() {
            var $this = $(this);
            var type = 'checkbox';

            if (config.name) {
                name = config.name;
            } else {
                name = $.uuid();
            }
            if (config.radio) {
                type = 'radio';

            }
            disabled = "";
            if (config.enabled) {
                if (!config.enabled()) {
                    disabled = " disabled='true'";
                }
            }
            var check = $("<input type='" + type + "' name='" + name + "'" + disabled + "/>");
            $this.append(check);
            if (config.checked) {
                check.attr("checked", "checked");
            }
            if (config.change) {
                check.click(config.change);
            }
        });
    };

    
    $.fn.freemixStepTabs = function(option, selector) {
        
        return this.each(function() {
            if (option === "select") {
                $(this).find("a[href='" + selector + "']").trigger("tab-select");
            } else if (option == "incomplete") {
                $(this).find("a[href='" + selector + "']").parent("li").nextAll().find("a").addClass("step-disabled");                
            } else if (option == "complete") {
                $(this).find(".step-disabled").removeClass("step-disabled");
            } else {
                var tabset = $(this);
                var callbacks = option||{};
                tabset.find("li>a").each(function() {
                    var a = $(this);
                    var sel = a.attr("href"); 
                    $(sel).addClass("tab-contents");                   
                    var callback = callbacks[sel.substring(1)]||function(){};
                    a.bind("tab-select", function() {
                        if (!a.hasClass("tab-selected")) {
                            $(".tab-contents")
                            .hide()
                            .removeClass(".tab-selected");
                            
                            callback();
                            tabset.find("a").removeClass("step-completed step-selected");
                            a.addClass("step-selected")
                                .parent("li").prevAll().find("a").addClass("step-completed");
                            
                            $(sel).addClass(".tab-selected").show();
                            
                        }
                    }).click(function() {
                        a.trigger("tab-select");
                    });
                    
                });
            }
        });
    };


    // UUID extension found at http://plugins.jquery.com/node/4131
    /*
    Usage 1: define the default prefix by using an object with the property prefix as a parameter which contains a string value; {prefix: 'id'}
    Usage 2: call the function jQuery.uuid() with a string parameter p to be used as a prefix to generate a random uuid;
    Usage 3: call the function jQuery.uuid() with no parameters to generate a uuid with the default prefix; defaul prefix: '' (empty string)
    */

    /*
    Generate fragment of random numbers
    */
    jQuery._uuid_default_prefix = '';
    jQuery._uuidlet = function() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    };
    /*
    Generates random uuid
    */
    jQuery.uuid = function(p) {
        if (typeof(p) == 'object' && typeof(p.prefix) == 'string') {
            jQuery._uuid_default_prefix = p.prefix;
        } else {
            p = p || jQuery._uuid_default_prefix || '';
            return (p + jQuery._uuidlet() + jQuery._uuidlet() + "-" + jQuery._uuidlet() + "-" + jQuery._uuidlet() + "-" + jQuery._uuidlet() + "-" + jQuery._uuidlet() + jQuery._uuidlet() + jQuery._uuidlet());
        }
    };

})(jQuery);
