/**
 * XField
 * 
 * Стилизация полей ввода с кнопкой для очистки поля
 * 
 * @author Evgeny Samsonov (bitniks@bitniks.ru)
 * @date 2011/01/31
 * 
 */
$.fn.xField = function(options) {

	// Соединяем опции по умолчанию с переданными
    var options = $.extend({
         clear : true,
         required : false
    }, options);

    this.each(function(){

    	// Поле в html
        $(this).wrap(
            "<div class='xfield'>" +
                "<div class='xfield-border'>" +
                    "<div class='xfield-input'></div>" +
                    "<div class='xfield-clear-button'></div>" +
                "</div>" +
                "<div class='xfield-clearfix'></div>" +
            "</div>"
        );

        var root = $(this).closest('.xfield');

        // Events
        $(this).focus(function(){
            root.addClass('xfield-focus');
        }).blur(function(){
            root.removeClass('xfield-focus');
        });

        // Clear button
        if (options.clear) {
            $(root).addClass('xfield-clear');

            var button = $('.xfield-clear-button', root);

            $(button).mouseenter(function(){
                $(this).addClass('xfield-clear-hover');
            }).mouseleave(function(){
                $(this).removeClass('xfield-clear-hover').removeClass('xfield-clear-active');;
            }).mousedown(function(){
                $(this).addClass('xfield-clear-active');
            }).mouseup(function(){
                $('input', root).val('');
                $('input', root).focus();
                $(this).removeClass('xfield-clear-active');
                $('input', root).trigger('keyup').trigger('keydown').trigger('keypress');
            });

            var showClear = function(input) {
                if ($(input).val()) {
                    $('.xfield-clear-button', root).show();
                }
                else {
                    $('.xfield-clear-button', root).hide();
                }
            }
            $(this).bind('keydown keyup', function(){
                showClear(this);
            });
            showClear(this);
        }

        // Required
        if (options.required) {
            root.addClass('xfield-required');
        }
        return this;
    });
}
