/**
 * @package		bums
 * @subpackage	widget
 * @since      06.11.2007 20:30:00
 * @author     Davojan
 */
(function($){

	$.bums = $.bums || {};
	var bums = $.bums, btn;

//{{{ $.bums.btn
/**
 * Класс-кнопка
 */
bums.btn = $.sdf.extend({

//{{{ __construct
/**
 * Конструктор
 * @param Element el элемент-таблица-кнопка
 * @param protect bool включать ли защиту от двойного нажатия? по умолчанию - да
 */
	__construct: function( el, protect )
	{
		if ( this.parentCall( 'constructor', arguments ) === false ) return false;
		this.focused = false;
		this.disabled = false;
		this.multiClickProtection = protect || true;
		this.$el.sdfHandle( 'click', 'mousedown', 'hover' );
		this.bindElement( 'input', 'input', this.$el ).sdfHandle( 'focus', 'blur', 'click' );
		
		this.type = this.$input.attr( 'type' ).toLowerCase();
		
		if ( this.type == 'submit' ) {
			this.initOwnForm();
		}
		btn.all.push( this );
	},
//===========================================================================}}}
//{{{ initOwnForm
/**
 * Инициализация формы, в которой кнопка
 * @since  02.04.2009 13:42:42
 * @author jikk
 */
	initOwnForm: function()
	{
	// Во избежание повторной инициализации формы
		if ( ! this.$form )
		{
			this.$form = this.$input.parents( 'form' );
			this.$form.sdfHandle( ['submit', {obj:this}] );
		}
	// На случай, если кнопка проиницализировалась раньше, чем форма, этот метод может быть вызыван повторно из конструктора формы	
		if ( ! this.form )
		{
			this.form = $sdf( this.$form );
			if ( this.form ) 
			{
				this.form.bindObj( 'fail', this, 'formFail' );
				this.form.bindObj( 'disable', this, 'formDisable' );
				this.form.bindObj( 'enable', this, 'formEnable' );
			}
		}
	},
//===========================================================================}}}
//{{{ onFormFail
/**
 * Обработка отлупа ajax-формы
 * Это автоматически работает только для сабмит-кнопки в составе ajax-формы
 */
	onFormFail: function()
	{
		if ( this.multiClickProtection )
		{
			var x = this;
			window.setTimeout( function() { x.endProgress() }, 200 );
		}
	},
//===========================================================================}}}
//{{{ onFormDisable
/**
 * Обработка дизабления формы
 */
	onFormDisable: function()
	{
		this.disable();
	},
//===========================================================================}}}
//{{{ onFormEnable
/**
 * Обработка енабления формы
 */
	onFormEnable: function()
	{
		this.enable();
	},
//===========================================================================}}}
//{{{ onClick
/**
 * Обработчик клика по кнопке
 */
	onClick: function( evt, el )
	{
	// попытка обойти глюк незакрывающихся менюшек из-за stopPropagation()
		$(document).click();

		if ( ! this.disabled )
		{
		  	if ( el !== this.input ) {
		  		this.$input.click();
		  	}
		  	else
			{
	  			this.trigger('click');
	  			if ( 'submit' == this.type  )
				{
	  				evt.preventDefault();
	  				this.$input.parents('form').submit();
		  		}
	  			else
				{
			  		if ( this.multiClickProtection ) {
		  				this.startProgress();
		  			}
	  			}
		  	}
		  	evt.stopPropagation();
		}
	},
//===========================================================================}}}
//{{{ onSubmit
/**
 * Обработчик сабмита формы (если это сабмит-кнопка)
 */
	onSubmit: function( Evt )
	{
		if ( this.multiClickProtection )
		{
			if ( this.disabled )
			{
				if ( ! this.form ) 
				{
					Evt.preventDefault();
					return false;
				}
			}
			else {
				this.startProgress();
			}
		}
	},
//===========================================================================}}}
//{{{ onMousedown
/**
 * Обработчик нажатия левой кнопки мыши
 */
	onMousedown: function( evt )
	{
		var i;
		for ( i = 0; i < bums.btn.all.length; i++ )
		{
			if ( bums.btn.all[i].focused )
			{
				bums.btn.all[i].onBlur();
				break;
			}
		}
		if ( ! this.disabled )
		{
			this.onFocus();
			$(document).one( 'mouseup', {obj: this}, $.sdf.handle );
		}
		if ( this.focused ) {
			this.preventBlur = true;
		}
		evt.stopPropagation();
		evt.preventDefault();
	},
//===========================================================================}}}
//{{{ onMouseup
/**
 * Обработчик отпускания левой кнопки мыши после нажатия над кнопкой
 */
	onMouseup: function()
	{
		this.preventBlur = false;
		this.focus();
	},
//===========================================================================}}}
//{{{ onFocus
/**
 * Обработчик попадания фокуса на кнопку
 */
	onFocus: function()
	{
		this.focused = true;
		this.$el.find('tr').addClass('focused');
	},
//===========================================================================}}}
//{{{ onBlur
/**
 * Обработчик ухода фокуса с кнопки
 */
	onBlur: function()
	{
		if ( ! this.preventBlur )
		{
			this.focused = false;
			this.$el.find('tr').removeClass('focused');
		}
		else {
			this.preventBlur = false;
		}
	},
//===========================================================================}}}
//{{{ onMouseover
/**
 * Наведение мышки
 */
	onMouseover: function()
	{
		this.$el.find('tr').addClass('hover');
	},
//===========================================================================}}}
//{{{ onMouseout
/**
 * Уведение мышки
 */
	onMouseout: function()
	{
		this.$el.find('tr').removeClass('hover');
	},
//===========================================================================}}}
//{{{ focus
/**
 * Фокусировка на кнопке
 */
	focus: function()
	{
		try {
			this.$input.focus();
			this.onFocus();
		}
		catch( e ) {}
	},
//===========================================================================}}}
//{{{ disable
/**
 * Делает кнопку неактивной
 */
	disable: function()
	{
		this.disabled = true;
		this.$input.attr('disabled', 'true');
		this.preventBlur = false;
		this.onBlur();
		this.$el.find('tr').addClass('disabled');
	},
//===========================================================================}}}
//{{{ enable
/**
 * Делает кнопку активной
 */
	enable: function()
	{
		this.$el.find('tr').removeClass('disabled');
		this.$input.removeAttr('disabled');
		this.disabled = false;
	},
//===========================================================================}}}
//{{{ startProgress
/**
 * Переход в активный режим - типа что-то делаем
 */
	startProgress: function()
	{
		this.disable();
		this.$el.find('tbody').addClass('progress');
	},
//===========================================================================}}}
//{{{ endProgress
/**
 * Переход в режим ожидания, типа закончили
 */
	endProgress: function()
	{
		this.$el.find('tbody').removeClass('progress');
		this.enable();
	}
//===========================================================================}}}
		
},
{
	all:[],

//{{{ cleanLeacks
/**
 * Борьба с утечками памяти в осле
 */
	cleanLeacks: function()
	{
		var i;
		for ( i = 0; i < btn.all.length; i++ ) {
			btn.all[i] = null;
		}
		btn.all = null;
	}
//===========================================================================}}}

});
	btn = bums.btn;
	if ( $.browser.msie && $.browser.version.indexOf('6.') !== -1 ) {
		$(window).bind("unload", btn.cleanLeacks );
	}
//===========================================================================}}}

	$(document).ready(function(){
		$('.bums-btn').sdf( btn );
	});

})(jQuery);
/*============================================================================*
 * vim: set expandtab tabstop=3 shiftwidth=3 foldmethod=marker:               *
 *   END OF FILE                                                              *
 *============================================================================*/