﻿$(function ()
{
  doWatermark('#SearchInput', "Keyword or Item #");
  doWatermark('.newsletterEmail', "enter email address here");

  $('#SearchButton').click(function () { doSearch() });

  $('#SearchInput').keypress(function (e)
  {
    if (e.which == 13)
    {
      doSearch();
      return false;
    }
  });

  $('.newsletterEmailBtn').click(function () { doNewsletter() });

  $('.newsletterEmail').keypress(function (e)
  {
    if (e.which == 13)
      doNewsletter();
  });

  setupSearchAutoComplete();
});

function doSearch()
{
  location.href = baseUrl + 'search/' + $('#SearchInput').val();
}

function setupSearchAutoComplete()
{
  $("#SearchInput").autocomplete(
  {
    source: function (request, response)
    {
      $.ajax({
        type: "POST",
        url: baseUrl + "webservices/Product.asmx/Search",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: " { 'q': '" + request.term + "' }",
        dataFilter: function (data) { return data; },
        success: function (data)
        {
          response($.map(data.d, function (item)
          {
            return {
              label: formatSearchResult(request.term, item.ItemNo) + ' - ' + formatSearchResult(request.term, item.Name),
              value: request.term,
              data: item,
              term: request.term
            }
          }))
        },
        error: function (xhr, status, error)
        {
          // Display a generic error for now.
          //alert("AJAX Error!");
        }
      })
    },
    minLength: 2,
    select: function (event, ui)
    {
      location.href = baseUrl + 'search.aspx?q=' + ui.item.data.ProductId;
    },
    open: function ()
    {
      $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
    },
    close: function ()
    {
      $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
    }
  });
}

function formatSearchResult(term, value)
{
  return value.replace( new RegExp(term, "gi"), '<b>' + term + '</b>');
}

function doWatermark(id, defaultVal)
{
  // watermark
  var watermark = defaultVal;
  var searchItem = $(id);

  if (searchItem.val() == "")
  {
    searchItem.val(watermark);
  }

  searchItem.focus(function ()
  {
    if (this.value == watermark)
    {
      this.value = "";
    }
  }).blur(function ()
  {
    if (this.value == "")
    {
      this.value = watermark;
    }
  });
}
