﻿// Class to create watermark behavior on a textbox
// Textbox will have a default message when is does not have focus
// and will be blank when the user clicks on it

function TextBoxWatermark(textBox, text, cssClass)
{
    this._text = text;
    this._cssClass = cssClass;
    this._textBox = textBox;
    var me = this;
    AddEventListener(textBox, 'focus', function(e) { me.TextBox_Focus(e) });
    AddEventListener(textBox, 'blur', function(e) { me.TextBox_Blur(e) });
    if(textBox.value == "")
    {
        textBox.value = text;
    }
    if(textBox.value == text)
    {
        this._addCssClass();
    }
}

// Event - textbox has gained focus
TextBoxWatermark.prototype.TextBox_Focus = function(e)
{
    e = FixEvent(e);
    if(!this.TextIsDirty())
    {
        this._textBox.value = '';
        FireEvent(this._textBox, 'change');
        if(this._cssClass && this._textBox.className)
        {
            var regex = new RegExp('(^|\\s)' + this._cssClass);
            this._textBox.className = this._textBox.className.replace(regex, '');
        }
    }
}

// Event - textbox has lost focus
TextBoxWatermark.prototype.TextBox_Blur = function(e)
{
    e = FixEvent(e);
    if(this.TextIsEmpty())
    {
        this._textBox.value = this._text;
        this._addCssClass();
        //FireEvent(this._textBox, 'change');
    }
}

// Add the watermark css class to the textbox's class name
TextBoxWatermark.prototype._addCssClass = function()
{
    if(this._cssClass)
    {
        var regex = new RegExp('(^|\\s)' + this._cssClass);
        if(!this._textBox.className)
        {
            this._textBox.className = this._cssClass;
        }
        else if(!this._textBox.className.match(regex))
        {
            this._textBox.className += ' ' + this._cssClass;
        }
    }
}

// Get whether the textbox's value is empty or contains only whitespace
TextBoxWatermark.prototype.TextIsEmpty = function()
{
   return !this._textBox.value || !this._textBox.value.trim(); 
}

// Get whether the textbox's value is different from the default value
TextBoxWatermark.prototype.TextIsDirty = function()
{
    return this._textBox.value != this._text;
}
