﻿
function Search(textBoxID, watermarkText, watermarkCssClass, errorMessageID, submitFunc)
{
    this._textBoxID = textBoxID;
    var tb = document.getElementById(this._textBoxID);
    this._watermark = new TextBoxWatermark(tb, watermarkText, watermarkCssClass);
    this._errorMessageID = errorMessageID;
    this._searchRegex = /^[\*\?\~\+\-]?[\w\. ]+[\w\W]+$/;
    this._submitFunc = submitFunc;
    var me = this;
    AddEventListener(tb, 'blur', function(e) { me.TextBox_Blur(e) });
    this._fncTextBoxFocus = function(e) { me.TextBox_Focus(e) };
    AddEventListener(tb, 'focus', this._fncTextBoxFocus);
    AddEventListener(tb, 'keyup', function(e) { me.TextBox_KeyUp(e) });
}

Search.prototype.TextBox_Blur = function(e)
{
    if(!this._watermark.TextIsEmpty())
    {
        this._validateSearchText();
    }
}

Search.prototype.TextBox_Focus = function()
{
    this._clearErrors();
}

Search.prototype.TextBox_KeyUp = function(e)
{
    e = FixEvent(e);
    if(e.keyCode != 13)
    {
        return;
    }
    e.preventDefault();
    e.stopPropagation();
    var tb = document.getElementById(this._textBoxID);
    if(!this._watermark.TextIsEmpty() && this._watermark.TextIsDirty() && this._validateSearchText())
    {
        this._submitFunc();
    }
}

Search.prototype._clearErrors = function()
{
    document.getElementById(this._errorMessageID).style.display = 'none';
}

Search.prototype._validateSearchText = function()
{
    var txtBox = document.getElementById(this._textBoxID);
    if(!txtBox.value || !txtBox.value.match(this._searchRegex))
    {
        document.getElementById(this._errorMessageID).style.display = 'inline';
        return false;
    }
    this._clearErrors();
    return true;
}

Search.btnDoNothing_Click = function(e)
{
    e = FixEvent(e);
    e.stopPropagation();
    e.preventDefault();
}
