﻿function addLoadEvent(func){
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    };
  }
};
addLoadEvent(matchProductHeight);

$(document).ready(function() {
  //searchSuggest();
  filterSelectSubmit();
});

function searchSuggest() {
  $(".filterSearch").blur(function() {
    $("#filterSearchProducts").hide();
  });
  $(".filterSearch").keyup(function() {
    if ($(this).val().length <= 1) {
      $("#filterSearchProducts").html("").hide();
      return false;
    }
    
    var str = { SearchTerm : $(this).val(),
                CategoryID : ($("#filterCategoryID").val() == null) ? 0 : $("#filterCategoryID").val(),
                SectionID : ($("#filterSectionID").val() == null) ? 0 : $("#filterSectionID").val(),
                GenreID : ($("#filterGenreID").val() == null) ? 0 : $("#filterGenreID").val(),
                VectorID : ($("#filterVectorID").val() == null) ? 0 : $("#filterVectorID").val(),
                ManufacturerID : ($("#filterManufacturerID").val() == null) ? 0 : $("#filterManufacturerID").val() };
    var jsonStr = JSON.stringify(str);
    //alert(jsonStr);
    $.ajax({
      type: "POST",
      contentType: "application/json; charset=utf-8",
      url: "SearchService.asmx/Search",
      data: jsonStr,
      dataType: "json",
      success: function(result) {
        $("#filterSearchProducts").html("");
        $(document.createElement("ul")).attr("id", "filterSearchProductsList").prependTo("#filterSearchProducts");
        $.each(result, function(index, product) {
          $("#filterSearchProducts").show();
          $(document.createElement("li")).append($(document.createElement("a")).attr("href", product.Url).text(product.Name)).appendTo("#filterSearchProductsList");
        });
      },
      error: function(xhr, msg) {
        $("#filterSearchProducts").html("").hide();
        //alert(xhr.responseText);
      }
    });
  });
}

function matchProductHeight() {
  $('.productRow').each(function() {
    var height = 0;
    $('.product',$(this)).each(function(index) {
      if($(this).outerHeight(true) > height) {
        height = $(this).outerHeight(true);
      }
    });
    $('.product',$(this)).height(height);
  });
};

function filterSelectSubmit() {
  $('#resultFilter select').change(function(){
    $('#resultFilter').submit();
  });
};
