'use strict';

/*
* Qusion UI Combo 1.0
*
* Copyright 2011, AUTHORS.txt (http://qusion.net/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://qusion.net/license
*
* http://docs.qusion.net/ui/combo
*
* Depends:
*	jquery.ui.widget.js
*	jquery.ui.menu.js
*	jquery.ui.popover.js
*/

(function($) {
    $.widget("qusion.combo", {
        options: {
            inputWidth: null,
            filter: true,
            menuMaxHeight: 180,
            menuMinWidth: '50px',
            closeOnCommand: false,
            customScroll: true,
            position: {
                my: 'right top',
                at: 'right bottom',
                collision: "flipfit flipfit",
                offset: "0 0"
            },
            commands: []
        },
        _create: function() {
            var self = this, element = this.element, options = this.options;

            self.multiple = element.is('[multiple]');

            self.trigger = $('<a />')
                .addClass('qusion-combo')
                .insertAfter(element);

            self.input = $('<span />')
                .addClass('input')
                .appendTo(self.trigger);

            self.selector = $('<span />')
                .addClass('select')
                .appendTo(self.trigger);

            self.input
                .css({ width: options.inputWidth })
                .html(element.find(":selected").text());

            self.popover = $("<div />")
                .addClass("qusion-combo-popover")
                .css({ position: 'absolute' }) //width: self.trigger.outerWidth()
                .insertAfter(self.trigger);

            self.menu = $('<ul />')
                .addClass('qusion-combo-menu vertical-only')
                .appendTo(self.popover);

            $(self.element).find('option').each(function(i) {
                var that = $(this);
                var item = {
                    value: that.val(),
                    text: that.text() || '&nbsp;'
                };

                var li = $('<li><a><i class="icon-ok" /></a></li>')
                    .attr("data-value", item.value)
                    .data("item", item);

                li.find('a').append(item.text);
                if (item.value == self.element.val())
                    li.addClass("ui-state-active");

                self.menu.append(li);
            });

            // commands
            for (var j = 0; j < options.commands.length; j++) {
                var command = options.commands[j];
                self.addCommand(command);
            }

            // popover
            self.popover
                .popover({
                    trigger: self.trigger,
                    position: options.position
                });

            // catch events
            self._on(self.popover, {
                "popoveropen": function() {
                    // calculate panel to be able to adjust scroll
                    if (options.menuMaxHeight > 0) {
                        var h = self.menu.outerHeight();
                        if (h > options.menuMaxHeight)
                            self.menu.css({ 'height': options.menuMaxHeight });
                    }

                    // if custom scroll is enabled
                    if ($.fn.jScrollPane && options.customScroll === true) {
                        setTimeout(function() {
                            self.menu.jScrollPane();
                        }, 20);
                    }
                },
                "popoverselect": function(e, ui) {
                    var data = ui.item.data("item");
                    self.select(data.value);
                }
            });

            element.hide();

        },
        select: function(value) {
            this.element.val(value);
            this.input.html(this.element.find(":selected").text());

            this.menu.find('.ui-state-active')
                .removeClass('ui-state-active');

            this.menu.find('[data-value="' + value + '"]').addClass('ui-state-active');
        },
        addCommand: function(command) {
            var self = this, options = this.options;
            var a = $('<a />', { text: command.text })
                .data("command", command)
                .addClass('qusion-combo-command qusion-combo-command-' + command.name)
                .click(function(e) {
                    var target = $(e.target).closest(".qusion-combo-command");
                    var command = target.data("command");
                    self._trigger('command', e, { item: target, name: command.name });
                    if (options.closeOnCommand === true)
                        self.popover.popover("close");
                })
                .appendTo(self.popover);

            if (command.icon)
                a.prepend('<i class="' + command.icon + '"></i>');
        }
    });
})(jQuery);