﻿// Initialize/create the JS search box control with the specified client id.
function SearchBox(clientId)
{
    // Get the properties of this search box
    this.searchBox = $(clientId + '_txtSearchBox');
    this.watermark = $(clientId + '_hiddenWatermark').value;
    this.searchButton = $(clientId + '_searchButton');
    // Attach event handlers
    var _this = this;
    this.searchBox.onkeypress = function(event) { return _this.ifEnterThenSearch(event); };
    this.searchButton.onclick = function() { _this.performSearch(); };
    this.searchBox.onblur = function() { _this.showWatermark(); };
    this.searchBox.onfocus = function() { _this.hideWatermark(); };
    
}

// If the textbox currently contains the water mark, then clear the text.
SearchBox.prototype.hideWatermark = function()
{
    if (this.searchBox.value == this.watermark)
    {
        this.searchBox.value = '';
    }
}

// If the textbox is empty, show the watermark.
SearchBox.prototype.showWatermark = function()
{
    if (this.searchBox.value == '')
    {
        this.searchBox.value = this.watermark;    
    }
}

// If the "enter" key was pressed in the search box, then search
SearchBox.prototype.ifEnterThenSearch = function(event)
{
    var e = getEvent(event);
    var key = getKeycode(e);
    // Enter pressed?
    if (key == 13)
    {
        this.performSearch();
        return false;
    }
}

// Redirect to a page that display the search results for the current search term that the user entered.
SearchBox.prototype.performSearch = function()
{
    var searchQuery = this.searchBox.value;
    if (searchQuery != '' && searchQuery != this.watermark)
    {
        var searchPageUrl = (new RoutingObjects.Search(searchQuery)).GetURL();
        window.location = searchPageUrl;
    }
}
