﻿(function($) {
    $.fn.DDAutoWidth = function(options) {

        var defaults = {
            defaultWidth: $(this).width(),
            expandWidth: "auto",
            expand: true,
            fadeClasses: null
        };

        if ($.browser.msie) {

            var isFocused = false;

            var options = $.extend(defaults, options);

            if ($(this).css("width") != "auto") {
                options.defaultWidth = parseInt(options.defaultWidth) + 2;

               // $(this).css("width", options.defaultWidth + 'px')
            }
            //else
            //$(this).css("width", options.defaultWidth + 'px')

                function AutoWidth(sender) {

                $(sender).fadeTo(0, 1);
                
                if (options.expand) {

                    $(sender).css("width", options.expandWidth);
                    var actualWidth = parseInt($(sender).width()); // + 10);
                    if (actualWidth > options.defaultWidth) {


                        $(sender).animate({ width: actualWidth + 4 + 'px' }, "fast");
                        //$(sender).css("left", "250px");
                        $(sender).css("z-index", 1000);
                    }
                    else {

                        $(sender).css("width", options.defaultWidth);
                    }
                }

                $(sender).focus();
                isFocused = true;
            }

            function ResetWidth(sender) {

                if (options.fadeClasses != null) {
                    var fadeAll = false;
                    var anyFocus = $(".focused");

                    if (anyFocus[0] == null || anyFocus[0] == 'undefined')
                        fadeAll = true;

                    $(options.fadeClasses).each(function() {

                        if ($("'" + this + "'").hasClass("focused") || fadeAll == true) {
                            $("'" + this + "'").fadeTo(0, 1);
                        }
                    });
                }
                if (options.expand) {
                    $(sender).animate({ width: options.defaultWidth + 'px' }, "fast");
                }

                isFocused = false;
                $(sender).css("z-index", "0");
            }

            $(this).hover(function() { if (!isFocused) AutoWidth(this); });

            $(this).blur(function() { $(this).removeClass("focused"); ResetWidth(this); });

            $(this).change(function() { $(this).blur(); });

            $(this).focus(function() {
                $(this).addClass("focused");
                if (options.fadeClasses != null) {
                    $(options.fadeClasses).each(function() {
                        $("'" + this + "'").fadeTo("fast", 0.3);
                    });
                }
            });
        }
    };
})(jQuery);


