/**
 * Expand Button 0.1
 * 
 * Стилизация кнопки
 * 
 * @author Evgeny Samsonov (bitniks@bitniks.ru)
 * @date 2011/01/11
 * 
 */

$(function(){

	/**
	 * @param <object> options.disabled		 по умолчанию false 	 		 
	 * 
	 * @example 
	 * 	$('#active_button').expandbutton();		активная кнопка		
	 * 	$('#deactive_button').expandbutton({disabled : true});		неактивная кнопка 
	 */
    $.fn.expandButton = function(options) {

        if (typeof options === 'object' || ! options) {
        	// Передан объект с конфигурацией, либо ничего не передано. => Инициализация
            return expandButton.init.apply( this, arguments );
        }
        else {
        	// Передано название внутренней функции. Вызываем ее 
            return expandButton[ options ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        }
    }

    var expandButton = {
    	
    	// Инициализация
        init : function (options) {
    		
    		// Соединяем настройки по умолчанию с переданными настройками
            var options = $.extend({
                disabled : false
            }, options);

            this.each(function(){
            	// Исходник
                var $source = $(this);

                // На какой тег подвешен?
                var tag = $source.get(0).tagName;
                var value = (tag == 'INPUT') ? $source.val() : $source.text() ;
                var name = $source.attr('name');

                // Маркап для кнопки
                var $button = $("<div class='expandbutton'>" +
                                "<div class='expandbutton-text'>" + value + "</div>" +
                                "<div class='expandbutton-icon'></div>" +
                                 "<div class='expandbutton-round'></div>" +
                             "</div>");

                // Эмулируем передачу параметров
                if (name) {
                    $button.append("<input type='hidden' name='" + name + "' value='" + value + "'>");
                }

                // Задаем tabindex
                $($button).attr("tabindex", $($source).attr("tabindex") || "0");

                $source.hide();
                $source.after($button);

                // Данные для методов
                $(this).data(
                    "expandButton",
                    {
                        "$source" : $source,
                        "$button" : $button,
                        "tag" : tag
                    }
                );
                
                if (options.disabled || $(this).attr('disabled')) {
                	// Кнопка деактивирована
                    $button.addClass('expandbutton-disabled');
                }
                else {
                	// Включаем кнопку
                    expandButton._initEvent.apply(this);
                }
            });
        },
        // Инициализирует события
        _initEvent : function() {
        	// просто eb
            var eb = $(this).data("expandButton");
            if ( ! eb) return false;
            eb.$button.bind("mouseenter.expandButton", function(){
                $(this).addClass("expandbutton-hover");
            });
            eb.$button.bind("mouseleave.expandButton", function(){
                $(this).removeClass("expandbutton-hover");
            });
            // Нажатие на кнопку
            eb.$button.bind("mousedown.expandButton", function() {
                $(this).addClass("expandbutton-active");
            });
            eb.$button.bind("mouseup.expandButton, mouseleave.expandButton", function() {
                $(this).removeClass("expandbutton-active");
            });
            eb.$button.bind("click.expandButton", function() {
                if (eb.$source.attr("type") == "submit") {
                    eb.$source.closest('form').submit();
                }
            });
        },
        // Отключает кнопку
        disable : function(color) {
            var eb = $(this).data("expandButton");
            if (!eb) return false;
            if (eb.$button.hasClass('expandbutton-disabled')) return false;
            eb.$button.addClass('expandbutton-disabled');
            eb.$button.unbind(".expandButton");
        },
        // Включает кнопку
        enable : function() {
            var eb = $(this).data("expandButton");
            if (!eb) return false;
            if (!eb.$button.hasClass('expandbutton-disabled')) return false;
            eb.$button.removeClass('expandbutton-disabled');
            expandButton._initEvent.apply(this);
        },
        // Уничтожает кнопку
        destroy : function() {
            var eb = $(this).data("expandButton");
            if ( ! eb) return false;
            eb.$source.show();
            eb.$button.remove();
            eb.$button.unbind(".expandButton");
        },
        // Изменяет текст в кнопке
        // @param <string> value 	Новое значение
        value : function(value) {
            var eb = $(this).data("expandButton");
            if ( ! eb) return false;
            $('.expandbutton-text', eb.$button).text(value);
        },
        // Вешает любое событие на кнопку
        // @param <string> event 	Название события
        // @param <string> fun 		Функция
        bind : function(event, fun) {
            var eb = $(this).data("expandButton");
            if ( ! eb) return false;
            eb.$button.bind(event, fun);
        },
        // Уничтожает любое событие
        // @param <string> event	Название события
        unbind : function(event) {
            var eb = $(this).data("expandButton");
            if ( ! eb) return false;
            eb.$button.unbind(event);
        },
        // Возвращает активность кнопки 
        // @return <boolean> true активна, иначе false
        isDisabled : function() {
            var eb = $(this).data("expandButton");
            if ( ! eb) return false;
            return eb.$button.hasClass('expandbutton-disabled');
        }
    };
});

