//constants:
var animatespeed_AddCompare = 700;
var animatespeed_ResultNrBoxes = 20;
//-----------


//------ vars ------ 
var toggler1Expanded = true;
var toggler2Expanded = false;
 
 var compare1 = "";
 var compare2 = "";
 var compare3 = "";
 var compare4 = "";
 var searchResults = null;
 var searchCriteria = null;
 
 var helper_allFamilies;
 var helper_searchResults;
 
 //**** helpers: ****
 var helper_allPFsLoaded = false;
 var helper_searchResultsLoaded = false;
 var helper_searchCriteriaLoaded = false;
 
 var helper_radiobuttonStatus;
 var helper_pos;
 
 //image loading:
 var bgrds = [];
 var nextToLoadIndex = -1;

 //------ init ------
 $(document).ready(function() {
     addAccordionTogglerListener(); //in umbraco template
     addClearCompareListener();
     addClearCriteriaListener();
     addCompareNowListener();
     addInfoBoxListeners();
     addReadabilityMeasureListener();

     loadSavedData();
     getAllProductFamilies();
     getSearchCriteriaDescriptions();

     //disable enter on capacity:
     $("input#textCapacity").keypress(function(event) {
        if (event.keyCode == '13') {
         if (isNaN($(this).val()))
             $(this).addClass("textboxError");
             else {
                 $(this).removeClass("textboxError");
                 clearCriteriaArea1();
                 clearCriteriaDirect();
                 search();
             }
             return false;
         }
     });

 });

//------ addClearCompareListener ------
  function addClearCompareListener() {
      $("a.clear").click(function() {
          clearCompare();
          resetCompare(compare1);
          resetCompare(compare2);
          resetCompare(compare3);
          resetCompare(compare4);
          compare1 = "";
          compare2 = "";
          compare3 = "";
          compare4 = "";
          sessionClearCompare();
          return false;
      });
  }
  function clearCompare() {
      $("div.dropbox img").animate({ opacity: 0 }, 700, function() { $(this).remove() });      
  }
  function resetCompare(compare) {
      if (compare != "") {
          var button = $("div[id$='" + compare + "'] :last-child");
          button.removeClass("subtract");
          button.addClass("add");
      }
  }
  function sessionClearCompare() {
      $.ajax({
          type: "POST",
          url: websService + "/ClearFamiliesToCompare",
          data: '{}',
          contentType: "application/json; charset=utf-8",
          dataType: "json"
      });
  }

  //------ addClearCriteriaListener ------
  function addClearCriteriaListener() {
      $("a#clearCriteria").click(function() {
          sessionClearCriteria();
          searchResults = helper_allFamilies;
          showSearchResults();
          clearSearchResults();
          clearCriteriaArea1();
          clearCriteriaArea2();
          clearCriteriaDirect();
          return false;
      });
  }

  function clearCriteriaArea1() {
      $("div#accordionSectionWrapper1 input:checkbox").removeAttr("checked");
  }
  function clearCriteriaArea2() {
      $("div#accordionSectionWrapper2 input:radio").removeAttr("checked");
      $("input#textCapacity").val("");
      $("select#selectCapacity").val("0");
      $("select#selectReadabilitiesG").val("0");
      $("select#selectReadabilitiesLB").val("0");
      $("select#selectReadabilitiesCT").val("0");
  }
  function clearCriteriaDirect() {
      $("select#productFamilySelect").val("0");
  }
  function sessionClearCriteria() {
      $.ajax({
          type: "POST",
          url: websService + "/ClearCriteria",
          data: '{}',
          contentType: "application/json; charset=utf-8",
          dataType: "json"
      });
  }
  function clearSearchResults() {
      $.ajax({
          type: "POST",
          url: websService + "/ClearSearchResults",
          data: '{}',
          contentType: "application/json; charset=utf-8",
          dataType: "json"
      });
  }
  
  //------ addCompareNowListener ------
  function addCompareNowListener() {
      $("a#compareButton").mouseup(function() {
          var concat = "?";
          var link = productsPageName+"/compare-products.aspx";
          if (compare1 != "") {
              link += concat + "id1=" + compare1;
              concat = "&";
          }
          if (compare2 != "") {
              link += concat + "id2=" + compare2;
              concat = "&";
          }
          if (compare3 != "") {
              link += concat + "id3=" + compare3;
              concat = "&";
          }
          if (compare4 != "") {
              link += concat + "id4=" + compare4;
          }
          $(this).attr("href", link);
      });
  }

  //------ addInfoBoxListeners ------
  function addInfoBoxListeners() {
      $("div#divInfo a.closeBtn").click(function() {
          $("div#divInfo").fadeOut();
          return false;
      });
  }

  //------ addReadabilityMeasureListener -----
  function addReadabilityMeasureListener() {
      $("select#selectReadabilityMeasure").change(function() {
          setActiveReadabilitiesSelect($(this).val());
      });
  }
    

  //------ loadSavedData ------
  function loadSavedData() {
      resultsLoadingText(true);
      $.ajax({
          type: "POST",
          url: websService + "/GetSearchCriteria",
          data: "{}",
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function(json) {
              searchCriteria = eval('(' + json.d + ')');
              loadSearchCriteria();
              helper_searchCriteriaLoaded = true;
              loadResults(); //waits for search results, criteria, and all fammilies to be laoded
          }
      });

      $.ajax({
          type: "POST",
          url: websService + "/GetSearchResults",
          data: "{}",
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function(json) {
              helper_searchResults = eval('(' + json.d + ')');
              helper_searchResultsLoaded = true;
              loadResults(); //waits for search results, criteria, and all fammilies to be laoded
          }
      });
      sessionGetCompare();
  }
  function loadResults() {
      if (helper_allPFsLoaded && helper_searchResultsLoaded && helper_searchCriteriaLoaded) {
          if (searchCriteria.FamilyID != null) {
              $("select#productFamilySelect").val(searchCriteria.FamilyID);
          }
          searchResults = (helper_searchResults.length == 0 && isSearchCriteriaEmpty()) ? helper_allFamilies : helper_searchResults;
          showSearchResults();
          helper_searchResults = null;
          //added: direct search by querystring:
          var directSearchID = $.query.get('directSearch');
          if (directSearchID != null && directSearchID != "") {
              clearCriteriaArea1();
              clearCriteriaArea2();
              $("select#productFamilySelect").val(directSearchID);
              search();
          }
          
      }
  }

  //------ getAllProductFamilies ------
  function getAllProductFamilies() {
      $.ajax({
          type: "POST",
          url: websService + "/GetAllProductFamilies",
          data: "{}",
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function(json) {
              var data = eval('(' + json.d + ')');
              var apendHTML = [];
              $.each(data, function(i, item) {
                  apendHTML.push('<option value="' + item.ID + '">' + item.Name + '</option>');
              });
              $('select#productFamilySelect').append(apendHTML.join(''));
              sortDirectSearchDropdown();
              $('select#productFamilySelect').change(function() {
                  var familyID = $(this).val();
                  if (familyID != "0") {
                      clearCriteriaArea1();
                      clearCriteriaArea2();
                      search();
                      //searchProductFamily(familyID);
                  }
              });
              $("span#resultTotal").html(data.length);

              helper_allFamilies = data;
              helper_allPFsLoaded = true;
              loadResults(); //waits for search results, criteria, and all fammilies to be laoded
          }
      });
  }

  //------ getSearchCriteriaDescriptions ------
  function getSearchCriteriaDescriptions() {
      $.ajax({
          type: "POST",
          url: websService + "/GetSearchCriteriaDescriptions",
          data: "{}",
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function(json) {
              //TODO: need IDs??
              var data = eval('(' + json.d + ')');
              var appendHTML = [];
              $.each(data.PrimaryPurposes, function(i, item) {
                  appendHTML.push('<div><input type="checkbox" id="' + item.Desc + '" value="' + item.ID + '"><label>' + getCriteriaTranslation(item.Desc) + '</label></div>');
              });
              $('div#wrapperPrimaryPurposes').append(appendHTML.join(''));

              appendHTML = [];
              $.each(data.KeyFeatures, function(i, item) {
                  appendHTML.push('<div><input type="checkbox" id="' + item.Desc + '" value="' + item.ID + '"><label>' + getCriteriaTranslation(item.Desc) + '</label></div>');
              });
              $('div#wrapperKeyFeatures').append(appendHTML.join(''));

              appendHTML = [];
              $.each(data.ProductWillBeUseds, function(i, item) {
                  appendHTML.push('<div><input type="checkbox" id="' + item.Desc + '" value="' + item.ID + '"><label>' + getCriteriaTranslation(item.Desc) + '</label></div>');
              });
              $('div#wrapperProductWillBeUseds').append(appendHTML.join(''));

              appendHTML = [];
              $.each(data.Markets, function(i, item) {
                  appendHTML.push('<div><input type="radio" name="groupMarkets" id="' + item.Desc + '" value="' + item.ID + '"><label>' + getCriteriaTranslation(item.Desc) + '</label></div>');
              });
              $('div#wrapperMarkets').append(appendHTML.join(''));

              var appendHTMLG = [];
              var appendHTMLLB = [];
              var appendHTMLCT = [];
              $.each(data.Readabilities, function(i, item) {
                  if (item.Desc.indexOf("lb") != -1)
                      appendHTMLLB.push('<option value="' + item.ID + '">' + item.Desc + '</option>');
                  else if (item.Desc.indexOf("ct") != -1)
                      appendHTMLCT.push('<option value="' + item.ID + '">' + item.Desc + '</option>');
                  else
                      appendHTMLG.push('<option value="' + item.ID + '">' + item.Desc + '</option>');
              });
              getReadabilitiesSelect("g").append(appendHTMLG.join(''));
              getReadabilitiesSelect("lb").append(appendHTMLLB.join(''));
              getReadabilitiesSelect("ct").append(appendHTMLCT.join(''));
              setActiveReadabilitiesSelect($("select#selectReadabilityMeasure").val());

              loadSearchCriteria();
              addSearchListeners();
          }
      });
  }

  //--------------------------------------------------
  //------------------ S E A R C H ------------------
  //--------------------------------------------------
  function addSearchListeners() {
      $("div#accordionSectionWrapper1").find("input").click(function() {
          clearCriteriaArea2();
          clearCriteriaDirect();
          search();
      });
      $("div#accordionSectionWrapper2").find("input:radio").click(function() {
          if (helper_radiobuttonStatus)
              $(this).removeAttr("checked");
          clearCriteriaArea1();
          clearCriteriaDirect();
          search();
      });
      $("div#accordionSectionWrapper2").find("input:text").change(function() {
          if (isNaN($(this).val()))
              $(this).addClass("textboxError");
          else {
              $(this).removeClass("textboxError");
              clearCriteriaArea1();
              clearCriteriaDirect();
              search();
          }
      });
      $("div#accordionSectionWrapper2").find("select").change(function() {
          clearCriteriaArea1();
          clearCriteriaDirect();
          search();
      });
      $("div#accordionSectionWrapper2").find("input:radio").bind('mouseup', 'keyup', function() {
          helper_radiobuttonStatus = $(this).attr("checked");
      });
  }

  function generateSearchCriteria() {
      var primaryPurposes = [];
      $("div#wrapperPrimaryPurposes input:checked").each(function(i, item) {
          primaryPurposes.push(item.value);
      });
      if (primaryPurposes.length == 0)
          primaryPurposes = null;

      var keyFeatures = [];
      $("div#wrapperKeyFeatures input:checked").each(function(i, item) {
          keyFeatures.push(item.value);
      });
      if (keyFeatures.length == 0)
          keyFeatures = null;

      var productWillBeUseds = [];
      $("div#wrapperProductWillBeUseds input:checked").each(function(i, item) {
          productWillBeUseds.push(item.value);
      });
      if (productWillBeUseds.length == 0)
          productWillBeUseds = null;

      var markets = null;
      $("div#wrapperMarkets input:checked").each(function(i, item) {
          markets = item.value;
      });

      var capacity = parseFloat($("input#textCapacity").val());
      if (isNaN(capacity))
          capacity = null;

      var capacityMeasure = $("select#selectCapacity").val();

      var readability = getActiveReadabilitiesSelect().val(); //$("select#selectReadabilities").val();
      if (readability == "0")
          readability = null;

      var familyID = $("select#productFamilySelect").val();
      if (familyID == "0")
          familyID = null;

      searchCriteria =
	{
	    "PrimaryPurposeIDs": primaryPurposes,
	    "KeyFeatureIDs": keyFeatures,
	    "ProductWillBeUsedIDs": productWillBeUseds,
	    "MarketID": markets,
	    "Capacity": capacity,
	    "CapacityMeasure": capacityMeasure,
	    "ReadabilityID": readability,
	    "FamilyID": familyID
	};
      //alert(primaryPurposes+"//"+keyFeatures+"//"+productWillBeUseds+"//"+markets+"//"+capacity+" "+capacityMeasure+"//"+readability);
  }

  function search() {
      generateSearchCriteria();
      resultsLoadingText(true);
      $.ajax({
          type: "POST",
          url: websService + "/Search",
          data: '{"objCriteria":' + JSON.stringify(searchCriteria) + '}',
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function(json) {
              var data = eval('(' + json.d + ')');
              searchResults = data;
              showSearchResults();
          }
      });
  }

  /*function searchProductFamily(familyID) {
      $.ajax({
          type: "POST",
          url: websService + "/GetProductFamily_Small",
          data: '{"familyCode":"' + familyID + '"}',
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function(json) {
              var data = eval('(' + json.d + ')');
              searchResults = [data];
              showSearchResults();
          }
      });
  }*/
  //--------------------------------------------------
  //-------------------------------------------------- 
  

  //--------------------------------------------------
  //------ Load Search Criteria and Show Results ------
  //--------------------------------------------------
  function loadSearchCriteria() {
      var isTab2Criteria = false;
      if (searchCriteria == null)
          return;
      if (searchCriteria.PrimaryPurposeIDs != null)
          $.each(searchCriteria.PrimaryPurposeIDs, function(i, item) {
              $('div#wrapperPrimaryPurposes input[value="' + item + '"]').attr("checked", "checked");
          });
      if (searchCriteria.KeyFeatureIDs != null)
          $.each(searchCriteria.KeyFeatureIDs, function(i, item) {
              $('div#wrapperKeyFeatures input[value="' + item + '"]').attr("checked", "checked");
          });
      if (searchCriteria.ProductWillBeUsedIDs != null)
          $.each(searchCriteria.ProductWillBeUsedIDs, function(i, item) {
              $('div#wrapperProductWillBeUseds input[value="' + item + '"]').attr("checked", "checked");
          });
      if (searchCriteria.MarketID != null) {
          $('div#wrapperMarkets input[value="' + searchCriteria.MarketID + '"]').attr("checked", "checked");
          isTab2Criteria = true;
      }
      if (searchCriteria.Capacity != null) {
          $('input#textCapacity').val(searchCriteria.Capacity);
          isTab2Criteria = true;
      }
      if (searchCriteria.CapacityMeasure != null)
          switch (searchCriteria.CapacityMeasure) {
          case 0:
              $('select#selectCapacity').val("G");
              break;
          case 1:
              $('select#selectCapacity').val("LB");
              break;
          case 2:
              $('select#selectCapacity').val("CT");
              break;
          isTab2Criteria = true;
      }
      if (searchCriteria.ReadabilityID != null) {
          var readabilityName = $('select#selectReadabilitiesG option[value=' + searchCriteria.ReadabilityID + ']').html();
          if (readabilityName == null)
              readabilityName = $('select#selectReadabilitiesLB option[value=' + searchCriteria.ReadabilityID + ']').html();
          if (readabilityName == null)
              readabilityName = $('select#selectReadabilitiesCT option[value=' + searchCriteria.ReadabilityID + ']').html();
          if (readabilityName != null) {
              $("select#selectReadabilityMeasure").val(getReadabilityMeasure(readabilityName));
              setActiveReadabilitiesSelect($("select#selectReadabilityMeasure").val());
              getActiveReadabilitiesSelect().val(searchCriteria.ReadabilityID);
          }
          isTab2Criteria = true;
      }
      if (isTab2Criteria) {
          maximize(2); //from umbraco template
          minimize(1); //from umbraco template
      }
  }

  //NOTE: criteriaTranslations are loaded on the template level
  function getCriteriaTranslation(label) {
      var lookUp = "c" + label;
      var res = "";
      $.each(criteriaTranslations, function(i, item) {
          if (item.key == lookUp)
              res = item.value;          
      });
      if (res == "")
          res = label;
      return res;
  }

  //this is to do everything AFTER the resultboxes have been animated
  function showSearchResults() {
      animateBoxes(searchResults.length);
  }

  function showSearchResultsCallback() {
      /*
      Search Result box:
      <div class="item">
      <a href="#" class="info"></a>
      <img src="/_img/img_dummy_productfinder_item_105x105.png" alt="" width="105" height="105"/>
      <h4>Freedom</h4>
      <div><a href="#" class="add">compare</a></div>
      </div>
      */
      //$('div#searchResults').html("");


      if (searchResults.length == 0) {
          $("div#searchResults").html("");
          showNoResultsFoundMsg(); //NOTE: this method is in the umbraco template
          $("span#resultHits").html(0);
      }
      else {
          var resultsArray = new Array();
          resultsArray.push('<div id="searchResults" class="content">');

          $.each(searchResults, function(i, item) {
              var prodID = item.ID;
              //resultsArray.push('<div class="item" id="' + prodID + '"><a href="#" class="info"></a><a href="products/product-families/'+ prodID +'.aspx"><img src="/_img/img_dummy_productfinder_item_105x105.png" alt="" width="105" height="105"/><h4>' + item.Name + '</h4></a><div><a href="#" class="add">compare</a></div></div>');
              var bgrdImg = "/_img/products/img_" + item.ID + "_ps.jpg"; //"background-image:url(/_img/products/img_" + item.ID + "_ps.jpg);";
              bgrds.push(
              {
                  id: item.ID,
                  bgrd: bgrdImg
              });
              var compareText = $("span#txtCompareNow").html();
              resultsArray.push('<div class="item" id="' + prodID + '"><a href="#" class="info"></a><a href="' + productsPageName + '/product-families/' + prodID + '.aspx" class="imgWrapper"><img src="/_img/_ico/ico_loading_105.gif"></img><h4>' + item.Name + '</h4></a><div><a href="#" class="add">' + compareText + '</a></div></div>'); //<div class="productFamDiv_selector loading"></div>
          });

          resultsArray.push("</div>");

          var htmlFragment = $(resultsArray.join(''));

          //alert(htmlFragment.find("div").length);
          htmlFragment.find("div.item").each(function(i, item) {
              var jQueryItem = $(item);
              var prodID = jQueryItem.attr("ID");

              var infoButton = jQueryItem.find("a.info");
              infoButton.click(function() {
                  var infoBox = $("div#divInfo");
                  var boxPosX = $(this).offset().left - 83 + ($(this).width() / 2);
                  var boxPosY = $(this).offset().top - infoBox.height() + 11;
                  getInfo(prodID, { top: boxPosY, left: boxPosX });
                  return false;
              });
              infoButton.blur(function() {
                  $("div#divInfo").fadeOut();
              });

              setCompareButtonState(jQueryItem);

              var compareButton = jQueryItem.find(":last-child");
              compareButton.click(function() {
                  var isAdding = $(this).hasClass("add");

                  var slot = AddRemoveCompare(prodID, isAdding);
                  if (slot != "") {
                      animateCompare(jQueryItem, slot, isAdding); //$('div[id $= "' + prodID + '"]"')
                      if (isAdding) {
                          $(this).removeClass("add");
                          $(this).addClass("subtract");
                      }
                      else {
                          $(this).removeClass("subtract");
                          $(this).addClass("add");
                      }
                  }
                  return false;
              });
          });

          $('div#searchResults').replaceWith(htmlFragment);
      }
      var hits = searchResults.length;
      $("span#resultHits").html(hits);
      nextToLoadIndex = 0;
      //LoadImages();
      if (hits > 0)
          LoadImagesAccordingToBrowser();
      resultsLoadingText(false);
      //animateBoxes(hits);
  } 
  
  //--------------------------------------------------
  //--------------------------------------------------



  //------ Other Helpers ------ 
  
 function isSearchCriteriaEmpty()
 {
	return (searchCriteria.PrimaryPurposeIDs == null &&
			searchCriteria.KeyFeatureIDs == null &&
			searchCriteria.ProductWillBeUsedIDs == null &&
			searchCriteria.MarketID == null &&
			searchCriteria.Capacity == null &&
			searchCriteria.CapacityMeasure == null &&
			searchCriteria.ReadabilityID == null);
 }
 
 function isBeingCompared(anID)
 {
	return (compare1==anID || compare2==anID || compare3==anID || compare4==anID);
 }
 
 function animateCompare(box,slot,isAdding)
 {
	var slotBox = $("div#"+slot);	
	
	if (isAdding)
	{
	    var balanceImg = box.find("img"); //box.find("div.productFamDiv_selector");
		var slotOffset = slotBox.offset();		
		var imgOffset = balanceImg.offset();

		var clone = balanceImg.clone();
		clone.css("position","absolute");
		clone.css("top", imgOffset.top);
		clone.css("left",imgOffset.left);
		$('div#searchResults').append(clone);
		clone.animate({
		    opacity: 0.2,
		    height: slotBox.height(),
		    width: slotBox.width(),
		    top: slotOffset.top + 1,
		    left: slotOffset.left + 1
		}, animatespeed_AddCompare, function() {
		    clone.attr("style", "");//clear style
		    clone.css("position", "absolute");
		    clone.css("opacity", 1);
		    clone.css("top", 0);
		    clone.css("left", 0);		    
		    clone.attr("width", 59);
		    clone.attr("height", 67);
		    //clone.attr("style", "");
		    clone.attr("src", "/_img/products/img_" + box.attr("id") + "_ps.jpg");
		    /*clone.removeClass("productFamDiv_selector");
		    clone.addClass("productFamDiv_compare");
		    var bgrdImg = "url(/_img/products/img_" + box.attr("id") + "_family_001_small.jpg)";
		    clone.css("background-image", bgrdImg);*/
		    slotBox.append(clone);
		});
	}
	else
	{		
		var balanceImg = slotBox.find("img");
		if (balanceImg != null)		
			balanceImg.animate({opacity: 0},700,function(){balanceImg.remove()});		
	}	
 }
 
 var helper_animationCount;
 var helper_animationStop;
 var helper_resultDiv;
 function animateBoxes(hits) {
     //new animation, clear pending timeouts:
     if (typeof(timer) !== 'undefined')
        clearTimeout(timer);
 
     helper_animationCount = 0;
     var currentBoxesCount = $("div.resultVisualizer div").length;
     helper_animationStop = hits - currentBoxesCount;
	 helper_resultDiv = $("div.resultVisualizer");

	 addBoxAnimation();
 }

 function addBoxAnimation() {
    helper_animationCount += helper_animationStop > 0 ? 1 : -1;
    if (helper_animationStop > 0) {
        var animationDiv = $('<div></div>');
        helper_resultDiv.append(animationDiv);
        //animationDiv.fadeIn(500);
        if (helper_animationCount < helper_animationStop)
            timer = setTimeout("addBoxAnimation()", animatespeed_ResultNrBoxes);
        else
            showSearchResultsCallback();
    }
    if (helper_animationStop < 0) {
        helper_resultDiv.find(":last-child").remove();
        if (helper_animationCount > helper_animationStop)
            timer = setTimeout("addBoxAnimation()", animatespeed_ResultNrBoxes);
        else
            showSearchResultsCallback();
    }
    if (helper_animationStop == 0)
        showSearchResultsCallback();
}
 
 function getInfo(productID, position)
 {
     $.ajax({
         type: "POST",
         url: websService + "/GetProductFamily_Info",
         data: '{"familyCode":"' + productID + '"}',
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function(json) {
             res = eval('(' + json.d + ')');
             $('span#infoName').html(res.Name);
             var capacityFrom = "";
             var capacityTo = "";
             var capacityMeasure = "";
             if (res.CapacityGFrom != null || res.CapacityGTo != null) {
                 capacityMeasure = "g";
                 capacityFrom = res.CapacityGFrom;
                 capacityTo = res.CapacityGTo;
             }
             else if (res.CapacityLBFrom != null || res.CapacityLBTo != null) {
                 capacityMeasure = "lb";
                 capacityFrom = res.CapacityLBFrom;
                 capacityTo = res.CapacityLBTo;
             } else if (res.CapacityCTFrom != null || res.CapacityCTTo != null) {
                 capacityMeasure = "ct";
                 capacityFrom = res.CapacityCTFrom;
                 capacityTo = res.CapacityCTTo;
             }
             var capacityLabel = "";
             if (capacityFrom == "")
                 capacityLabel = capacityTo + " " + capacityMeasure;
             else if (capacityTo == "")
                 capacityLabel = capacityFrom + " " + capacityMeasure;
             else
                 capacityLabel = capacityFrom + " " + capacityMeasure + " - " + capacityTo + " " + capacityMeasure;
             /*$('span#infoCapacityFrom').html(capacityFrom + capacityMeasure);
             $('span#infoCapacityTo').html(capacityTo + capacityMeasure);*/
             $('span#infoCapacity').html(capacityLabel);
             $('span#infoAppModes').html(res.BuiltinApplicationModes);

             $('span#infoReadabilities').html("");
             var separator = "";
             $.each(res.Readabilities, function(i, item) {
                 $('span#infoReadabilities').append(separator + item)
                 separator = ", ";
             });

            //old:
             //$("a#linkDetails").attr('href', 'products/product-families.aspx?id=' + productID);
             //new:
             $("a#linkDetails").attr('href', productsPageName+'/product-families/' + productID+'.aspx');

             var infodiv = $("div#divInfo");

             //note: we use animate instead of setting the css position so it is queued (and the box is moved after the fade out)
             var fllipNecessary = IsInfoBoxFlipNecessary(infodiv, position);
             infodiv.animate({ "top": position.top }, 0);
             infodiv.animate({ "left": position.left }, 0, function() {
                 if (fllipNecessary)
                     infodiv.addClass("flipped");
                 else
                     infodiv.removeClass("flipped");
             });
             infodiv.fadeIn();
         }
     });
 }

 function IsInfoBoxFlipNecessary(infoBox, position) {
     //flip is necessary if the divInfo div's width surpasses the viewport
     if (position.left + infoBox.width() > $(window).width()) {
         position.left -= 124;
         return true;
     }
     else
         return false;
 }
 
 function AddRemoveCompareSlot(dropboxID, productID, isAdding){
	 var res = "";
	 switch(dropboxID)
	  {
		case "dropbox1":
			compare1 = isAdding ? productID : "";
			res = "dropbox1";
			sessionSetCompare(1, compare1);
		  break;
		case "dropbox2":
			compare2 = isAdding ? productID : "";
			res = "dropbox2";
			sessionSetCompare(2, compare2);
		  break;
		  case "dropbox3":
			compare3 = isAdding ? productID : "";
			res = "dropbox3";
			sessionSetCompare(3, compare3);
		  break;
		  case "dropbox4":
			compare4 = isAdding ? productID : "";
			res = "dropbox4";
			sessionSetCompare(4, compare4);
		  break;
	  }
 }
 
 function AddRemoveCompare(productID,isAdding){
	 var slot= "";
	 if (compare1 == (isAdding ? "" : productID))
		 slot= "dropbox1";
	   else if (compare2 == (isAdding ? "" : productID))
		   slot= "dropbox2";
		 else if (compare3 == (isAdding ? "" : productID))
			 slot= "dropbox3";
		   else if (compare4 == (isAdding ? "" : productID))
			 slot= "dropbox4";
	   
	   if(slot!= "")
		   AddRemoveCompareSlot(slot,productID,isAdding);
	   
	   return slot;
 }    
 
function sessionSetCompare(slot, familyID)
{
	$.ajax({
		type: "POST",
		url: websService+"/SetFamilyToCompare",
		data: '{"slot":'+slot+', "aFamilyID":"'+familyID+'"}',
		contentType: "application/json; charset=utf-8",
		dataType: "json"
	});
}
function sessionGetCompare()
{
    $.ajax({
        type: "POST",
        url: websService + "/GetFamiliesToCompare",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(json) {
            res = eval('(' + json.d + ')');
            $.each(res, function(i, item) {
                loadComparePic(i, item);
            });
            ///////
        }
    });
}

function loadComparePic(slot, item) {
    if (item != null && item != "") {
        switch (slot) {
            case 0:
                compare1 = item;
                break;
            case 1:
                compare2 = item;
                break;
            case 2:
                compare3 = item;
                break;
            case 3:
                compare4 = item;
                break;
        }
        var dBox = $("div#dropbox" + (slot+1));
        //dBox.append('<img src="/_img/img_dummy_product_140x150.png" alt="" width="' + dBox.width() + '" height="' + dBox.height() + '"  style="position:absolute; top:0; left:0;"></img>');
        //var bgrdImg = "url(/_img/products/img_" + item + "_family_001_small.jpg)";
        var bgrdImg = "/_img/products/img_" + item + "_ps.jpg";
        //dBox.append('<div class="productFamDiv_compare" style="background-image: ' + bgrdImg + '; position:absolute; top:0px; left:0px; width:' + dBox.width() + 'px; height:' + dBox.height() + 'px;"></div>');
        dBox.append('<img src="' + bgrdImg + '" width="' + dBox.width() + '" height="' + +dBox.height() +'" style="position:absolute; top:0px; left:0px;"></img>');        
        $.each($("div#searchResults .item"), function(i, item) {
            setCompareButtonState($(this));
        });
    }
}

function setCompareButtonState(jQueryItem) {
    var compareButton = jQueryItem.find(":last-child"); //$('div[id $= "' + prodID + '"] :last-child');
    if (isBeingCompared(jQueryItem.attr("id"))) {
        compareButton.removeClass("add");
        compareButton.addClass("subtract");
    }
}

function sortDirectSearchDropdown() {
    // get the select
    var $dd = $('select#productFamilySelect');
    if ($dd.length > 0) { // make sure we found the select we were looking for

        // save the selected value
        var selectedVal = $dd.val();

        // get the options and loop through them
        var $options = $('option', $dd);
        var arrVals = [];
        $options.each(function() {
            // push each option value and text into an array
            arrVals.push({
                val: $(this).val(),
                text: $(this).text()
            });
        });

        // sort the array by the value (change val to text to sort by text instead)
        arrVals.sort(function(a, b) {
            var compA = a.text.toUpperCase();
            var compB = b.text.toUpperCase();
            //edit (rei): addded soval 0 goes first
            if (a.val == 0)
                return -1;
            else if (b.val == 0)
                return 1;
            else
                return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;

        });

        // loop through the sorted array and set the text/values to the options
        for (var i = 0, l = arrVals.length; i < l; i++) {
            $($options[i]).val(arrVals[i].val).text(arrVals[i].text);
        }

        // set the selected value back
        $dd.val(selectedVal);
    }
}

function resultsLoadingText(show) {
    if (show) {
        $("span#loadingText").show();
        $("div#resultsTextInnerDiv").hide();
    }
    else {
        $("span#loadingText").hide();
        $("div#resultsTextInnerDiv").show();
     }
 }

 function getReadabilitiesSelect(measure) {
     switch (measure.toLowerCase()) {
         case "g":
             return $("select#selectReadabilitiesG");
             break;
         case "lb":
             return $("select#selectReadabilitiesLB");
             break;
         case "ct":
             return $("select#selectReadabilitiesCT");
             break;            
     }
 }

 function getActiveReadabilitiesSelect() {
     return getReadabilitiesSelect($("select#selectReadabilityMeasure").val());
 }

 function setActiveReadabilitiesSelect(measure) {
     $("select#selectReadabilitiesG").val("0");
     $("select#selectReadabilitiesLB").val("0");
     $("select#selectReadabilitiesCT").val("0");
     switch (measure.toLowerCase()) {
         case "g":
             $("select#selectReadabilitiesG").show();
             $("select#selectReadabilitiesLB").hide();
             $("select#selectReadabilitiesCT").hide();
             break;
         case "lb":
             $("select#selectReadabilitiesG").hide();
             $("select#selectReadabilitiesLB").show();
             $("select#selectReadabilitiesCT").hide();
             break;
         case "ct":
             $("select#selectReadabilitiesG").hide();
             $("select#selectReadabilitiesLB").hide();
             $("select#selectReadabilitiesCT").show();
             break;
     }
 }

 function getReadabilityMeasure(text) {
     if (text.indexOf("lb") != -1)
         return "LB";
     else if (text.indexOf("ct") != -1)
         return "CT";
     else
         return "G";
 }

 function LoadImagesAccordingToBrowser() {
     if ($.browser.msie || $.browser.opera)
         LoadImagesIE();
     else 
         LoadImages();     
 }

 function LoadImagesIE() {
     if (nextToLoadIndex >= 0) {
         var loadedSomething = false;
         var curr = bgrds[nextToLoadIndex];
         var newImg = new Image();
         newImg.src = curr.bgrd;
         newImg.width = "105";
         newImg.height = "105";
         if (newImg.complete) {
             //same code as below... do nicer?
             loadedSomething = true;
             var oldDiv = $("DIV#" + curr.id + " img");
             oldDiv.replaceWith(newImg);
             nextToLoadIndex++;
             if (nextToLoadIndex < bgrds.length)
                 LoadImagesIE();
         }
         else {
             $(newImg).load(function() {
                 loadedSomething = true;
                 var oldDiv = $("DIV#" + curr.id + " img");
                 oldDiv.replaceWith(newImg);
                 nextToLoadIndex++;
                 if (nextToLoadIndex < bgrds.length)
                     LoadImagesIE();
             })
             .error(function() {
                 loadedSomething = true;
                 $("DIV#" + curr.id + " img").attr("src", "/_img/img_missing_ps.png");
                 nextToLoadIndex++;
                 if (nextToLoadIndex < bgrds.length)
                     LoadImagesIE();
             });
         }
         if (!loadedSomething) {
             $("DIV#" + curr.id + " img").attr("src", "/_img/img_missing_ps.png");
             nextToLoadIndex++;
             if (nextToLoadIndex < bgrds.length)
                 LoadImagesIE();
         }
     }
 }

 function LoadImages() {
     if (nextToLoadIndex >= 0) {
         var loadedSomething = false;
         var curr = bgrds[nextToLoadIndex];
         var newImg = new Image();
         newImg.src = curr.bgrd;
         newImg.width = "105";
         newImg.height = "105";

        $(newImg).load(function() {
             loadedSomething = true;
             var oldDiv = $("DIV#" + curr.id + " img");
             oldDiv.replaceWith(newImg);
             nextToLoadIndex++;
             if (nextToLoadIndex < bgrds.length)
             LoadImages();
        })
        .error(function() {
             loadedSomething = true;
             $("DIV#" + curr.id + " img").attr("src", "/_img/img_missing_ps.png");
             nextToLoadIndex++;
             if (nextToLoadIndex < bgrds.length)
             LoadImages();
        });
        }     
 }


 /*function LoadImages() { 
     if (nextToLoadIndex >= 0) {
         var loadedSomething = false;
         var curr = bgrds[nextToLoadIndex];
         var newImg = new Image();
         newImg.src = curr.bgrd;
         newImg.width = "105";
         newImg.height = "105";
         if (newImg.complete) {
             //same code as below... do nicer?
             loadedSomething = true;
             var oldDiv = $("DIV#" + curr.id + " img");
             oldDiv.replaceWith(newImg);
             nextToLoadIndex++;
             if (nextToLoadIndex < bgrds.length)
                 LoadImages();
         }
         else {
             $(newImg).load(function() {
                 loadedSomething = true;
                 var oldDiv = $("DIV#" + curr.id + " img");
                 oldDiv.replaceWith(newImg);
                 nextToLoadIndex++;
                 if (nextToLoadIndex < bgrds.length)
                     LoadImages();
             })
             .error(function() {
                 loadedSomething = true;
                 $("DIV#" + curr.id + " img").attr("src", "/_img/img_missing_ps.png");
                 nextToLoadIndex++;
                 if (nextToLoadIndex < bgrds.length)
                     LoadImages();
             });
         }
         if (!loadedSomething) {
             $("DIV#" + curr.id + " img").attr("src", "/_img/img_missing_ps.png");          
             nextToLoadIndex++;
             if (nextToLoadIndex < bgrds.length)
                 LoadImages();
         }
     }
 }*/
 
 
 

