﻿jQuery.fn.extend({
    emptyText: function(text) {
        return this.each(function() {
            function setTextBoxValues(input, message, helpStyle, helpColor) {
                input.val(message).css({ color: helpColor, fontStyle: helpStyle });
            }

            var helpColor = "gray";
            
            //initially the flag is false
            var flag = false;

            //set the input value to the message if it is empty or equal to the message
            if (($(this).val() == "") || ($(this).val() == text)) {
                setTextBoxValues($(this), text, "italic", helpColor);
            }
            else {
                // If a valid value is already loaded into the textbox, set the flag to true to prevent overwriting the value.
                flag = true;
            }

            /// BIND EVENTS ///
            //the flag will only be false if the user specifically typed ""
            $(this).bind("keyup", function() {
                flag = ($(this).val() != "")
            })
            //if the flag isn't set, clear the textbox and change the state to input
            .bind("focus", function() {
                if ($(this).val() == text) {
                    setTextBoxValues($(this), "", "", "")
                }
            })
            //if the flag wasn't set, put back into instructions mode
            .bind("blur", function() {
                if (!flag)
                    setTextBoxValues($(this), text, "italic", helpColor);
            })
            .bind("change", function() {
                if ($(this).val() != "")
                    setTextBoxValues($(this), $(this).val(), "", "");
                else
                    setTextBoxValues($(this), text, "italic", helpColor);

            });
        });
    }
});