    var userClick=false;
var fromDetailPage=false;
   	var inited=false;
   		var BrowserClick=false;
    var PaginationClass = new Class({
	initialize: function(el, max) {
		this.element = el;
		this.max = max;
		this.historyKey = this.element;
		this.history = HistoryManager.register(
			this.historyKey,
			[1],
			function(values) {
			    // Back/Forward Clicked
		//this.to(parseInt(values[0]));

var urlHref=document.location.href;
if (urlHref.match('Query,')!=null)
{
 load_content(true);
BrowserClick=true ;
var beginIndex=urlHref.lastIndexOf (',');
var lastIndex=urlHref.lastIndexOf (')');
var stemp=urlHref.substring(beginIndex+1,lastIndex);
//alert ("stemp:"+stemp);
var newQueryId=parseInt(stemp);
LaissezwareWebService.SearchProductByQueryId(newQueryId,searchCompleteCallBack,searchFailedCallback);
}
			}.bind(this),
			function(values) {
			    // Value Stored into History
				return [this.historyKey, '(', values[0], ')'].join('');
			}.bind(this),
			this.historyKey + '\\((\\d+)\\)');
	},

    doSearch: function(pageIdx) {
        // Step 1. Call AJAX back end
        // Record the set of query parameters into the history.
        //var serializedHistory = "pageIdx=" + pageIdx + "&" + queryParameters;
        var serializedHistory = new Array();
        serializedHistory[0]="Query";
        serializedHistory[1] = pageIdx;
        
        if (!BrowserClick&& !fromDetailPage){
        //if (!BrowserClick){
		this.history.setValue(0,  serializedHistory);
		BrowserClick=false ;
        }
    },
    
	by: function(dir) {
		this.to(this.page + dir);
	},

	to: function(page) {
		page = Math.max(Math.min(this.max, page), 1);
		this.page = page;
		this.history.setValue(0, this.page);
	}
});

var pagi;
/*
window.addEvent('domready', function(){
	HistoryManager.initialize();
	pagi = new PaginationClass('products', 10);
	HistoryManager.start();
	});
*/	
function doSearch(pageIdx) {
if(!inited){
//if (!fromDetailPage ){
    HistoryManager.initialize();
    HistoryManager.start();
//    }
	pagi = new PaginationClass('products', 20);
	inited = true;
}
	    pagi.doSearch(pageIdx);   
}


function load_content(myBool)
{
if (myBool){
document.getElementById('loadImage').style.display="inline";
document.getElementById('loadImage').innerHTML = "<img src='../../images/loading.gif' alt=''>";
document.getElementById('galleryvieww').style.display="none";
}else {
document.getElementById('loadImage').style.display="none";

//document.getElementById('loadImage').innerHTML = "";
document.getElementById('galleryvieww').style.display="block";
}
}



function highlightParentLine(subChkBox) {
  var styleVal;
  var checked;
  if (subChkBox.checked) {
    styleVal='bold';
    checked = 'checked';
  }
  else {
    styleVal='normal';
    checked = '';
  }
  //var ele = $(subChkBox).parents("li").find("a");
  //ele.css("font-weight",styleVal);//This is slow
  //ele.siblings("input").attr("checked",checked);//This is slow
  var parentChildSepPos = subChkBox.id.indexOf("_");
  parentChildSepPos = subChkBox.id.indexOf("_",parentChildSepPos+1);
  if (parentChildSepPos>-1) {
      var parentId = subChkBox.id.substring(0,parentChildSepPos);
      var parentChk = document.getElementById(parentId);
      //parentChk.checked = subChkBox.checked;
      jQuery(parentChk).siblings("a").css("font-weight",styleVal);
  }
}
var searchInProgress=false;
var timeInMilliseconds=1000;
var finalIdx ;

function searchProducts(currentPageIdx) {
  //var categoryId = $.jqURL.get('CategoryId');
   load_content(true);
 if (currentPageIdx=='filterBox') {
       userClick =true ;
    }
    finalIdx=currentPageIdx;
 //alert ("currentPageIdx: "+finalIdx);
 window.setTimeout('searchProductsII(\''+finalIdx+'\''+')', timeInMilliseconds);   
    
//  if (searchInProgress) {
//  searchInProgress=false ;
//  clickTimes++ ;
//  //alert("clickTimes:"+clickTimes);
//  searchProducts(currentPageIdx);
//}



}

function searchProductsII(currentPageIdx)
{
  //alert ("currentPageIdx: "+currentPageIdx);
  var categoryId=productCategoryId;
  //var searchString = jQuery.jqURL.get('SearchString');
  var searchString=null;
  var searchAllString = jQuery.jqURL.get('SearchString');
  var searchSKUString = jQuery.jqURL.get('SearchSKU');
  
  if (searchAllString!=null)searchString=searchAllString;
  if (searchSKUString!=null)searchString=searchSKUString;

  var searchFacets = true;
  
  if (searchString!=null) {
    searchString=unescape(searchString);
  }
  /*
  if (categoryId!=null && categoryId.endsWith("#")) {
    categoryId = categoryId.substring(0,categoryId.length-1);
  }
  */
  var q = new Laissezware.Web.Ajax.ProductSearchQuery();
  q.ProductAttributeValues = new Array();
  
    if (!currentPageIdx || isNaN(currentPageIdx)) {
        //var currentPageEle = document.getElementById("currentProductPageDropdown");  
        //var currentPage = parseInt(currentPageEle.options[currentPageEle.selectedIndex].value);
        //currentPageIdx= currentPage;
        
        currentPageIdx = 1;
    }
    else {

        searchFacets = false; // Only moving between pages, don't redo the facets        
    }

  //v.SearchValues[0] = "recessed";
  //
  //q.ProductAttributeValues[0] = v;  

  
  var optionIds = new Array();
  
  var parentsToHighlight = new Array();
  var parentsToUnhighlight = new Array();
  
  jQuery("input[id^=filter]").each(function (i) { // Find anything with an ID starting with filter
        var idParts = this.id.split('_');
        if (idParts.length==3) {
            //highlightParentLine(this);
                var parentChildSepPos = this.id.indexOf("_");
                parentChildSepPos = this.id.indexOf("_",parentChildSepPos+1);
                if (parentChildSepPos>-1) {
                    var parentId = this.id.substring(0,parentChildSepPos);
                    var parentChk = document.getElementById(parentId);                       
                    if (this.checked) {                   
                        parentsToHighlight[ parentChk.id] = parentChk;
                    }
                    else {
                        parentsToUnhighlight[parentChk.id] = parentChk;
                    }
                }
            ///////
            if (this.checked) {           
              //filter_1_1  (filter<product attribute id>_<product_attribute_option_id>          
              var found=false;
              //optionIds[optionIds.length] = this.id;
              for(var i=0; i < q.ProductAttributeValues.length; i++) {
                var pav = q.ProductAttributeValues[i];
                if (pav.ProductAttributeId == idParts[1]) {
                //if (pav.ProductAttributeId == this.productAttributeId) {
                  pav.SearchValues[pav.SearchValues.length] = this.value;
                  found = true;
                  break;
                }
              }
              if (!found) {
                var v = new Object();
                v.ProductAttributeId = idParts[1];
                v.SearchValues = new Array();  
                v.SearchValues[v.SearchValues.length] = this.value;
                q.ProductAttributeValues[q.ProductAttributeValues.length] = v;
              }
            }
         }
      }
      );
      
      for(var chkId in parentsToUnhighlight) {
        jQuery('#' + chkId).next("a").css("font-weight","normal");
        jQuery('#' + chkId).attr("checked",'');
      }

      for(var chkId in parentsToHighlight) {
        jQuery('#' + chkId).next("a").css("font-weight","bold");  
      }
      doProductSearch(categoryId, searchString, q, currentPageIdx,searchFacets);

}


function gotoNextProductPage() {
    userClick=true ;
    fromDetailPage=false ;
    var currentPageEle = document.getElementById("currentProductPageDropdown");  
    var currentPage = parseInt(currentPageEle.options[currentPageEle.selectedIndex].value);
    currentPageEle.selectedIndex = currentPage;
    searchProducts(currentPage+1);

}





function gotoPreviousProductPage() {
userClick=true ;
fromDetailPage=false ;
    var currentPageEle = document.getElementById("currentProductPageDropdown");  
    var currentPage = parseInt(currentPageEle.options[currentPageEle.selectedIndex].value)-1;
    currentPageEle.selectedIndex = currentPage;
    searchProducts(currentPage);
}

function gotoSelectedProductPage() {
userClick=true ;
fromDetailPage=false ;
    var currentPageEle = document.getElementById("currentProductPageDropdown");  
    searchProducts(currentPageEle.selectedIndex+1);
}

function gotoFirstProductPage() {
userClick=true ;
fromDetailPage=false ;
    var currentPageEle = document.getElementById("currentProductPageDropdown");  
    currentPageEle.selectedIndex = 0;
    searchProducts(currentPageEle.selectedIndex+1);
}

function gotoLastProductPage() {
userClick=true ;
fromDetailPage=false ;
    var currentPageEle = document.getElementById("currentProductPageDropdown");  
    currentPageEle.selectedIndex = currentPageEle.length-1;
   
    searchProducts(currentPageEle.selectedIndex+1);
    
}



function doProductSearch(categoryId, searchString, q, currentPageIdx, searchFacets) {
if (searchInProgress) {
    return;
}
/*
  var products = new Array();
  products[0] = new Product(1,'Cool Product');
  products[1] = new Product(1,'Ice Cold Product');
  products[2] = new Product(1,'Hot Product');
  */
  //var products = 
  //var pageDD = document.getElementById("currentProductPageDropdown");    
  var itemsPerPageEle = document.getElementById("productPageItemPerPage");    
  
  
  var currentPage = currentPageIdx; //parseInt(pageDD.options[pageDD.selectedIndex].value);
//  alert('currentPage ' + currentPage);
  var itemsPerPage = parseInt(itemsPerPageEle.options[itemsPerPageEle.selectedIndex].value);
//  alert('itemsPerPage ' + itemsPerPage);
  

 //alert('categoryId1:' + categoryId);
  q.CategoryIds = new Array();
  if (categoryId!=null && categoryId!='0') {
   //alert('categoryId2:' + categoryId);
    q.CategoryIds[0] = categoryId;
  }
  var searchSKUString = jQuery.jqURL.get('SearchSKU');
  if (searchSKUString==null){
    q.Keywords = searchString;
  }else 
  {
  q.SKU=searchString;
  }
  searchInProgress=true;
//alert ("userClick: "+userClick);

//alert (document.location.href);
var urlHref=document.location.href;


//if return from detail page.
if (urlHref.match('Query,')!=null && !userClick )
{
var beginIndex=urlHref.lastIndexOf (',');
var lastIndex=urlHref.lastIndexOf (')');
var stemp=urlHref.substring(beginIndex+1,lastIndex);
//alert ("stemp:"+stemp);

var newQueryId=parseInt(stemp);
fromDetailPage=true ;


LaissezwareWebService.SearchProductByQueryId(newQueryId,searchCompleteCallBack,searchFailedCallback);


}else {

 LaissezwareWebService.SearchProducts(currentPage, itemsPerPage, searchFacets, q, searchCompleteCallBack, searchFailedCallback );


}
userClick =false ;
//alert("result.QueryId:"+result.QueryId);

//   if (mySearchResults!=null ) {
//    alert('mySearchResultsINside:' + mySearchResults);
//   LaissezwareWebService.SearchProductByQueryId(mySearchResults.QueryId);
//   }
//LaissezwareWebService.SearchProductByQueryId(11);
  //return products;
}

function searchFailedCallback(error) {
    var stackTrace = error.get_stackTrace();
    var message = error.get_message();
    var statusCode = error.get_statusCode();
    var exceptionType = error.get_exceptionType();
    var timedout = error.get_timedOut();
   
    // Display the error.    

    var errorMsg = 
        "Stack Trace: " +  stackTrace + "<br/>" +
        "Service Error: " + message + "<br/>" +
        "Status Code: " + statusCode + "<br/>" +
        "Exception Type: " + exceptionType + "<br/>" +
        "Timedout: " + timedout;
//alert("Stack Trace: " +  stackTrace);        
//alert("Service Error: " + message);
//alert("Status Code: " + statusCode);
//alert("Exception Type: " + exceptionType);
//alert("Timedout: " + timedout);
        
searchInProgress=false;
}

function searchCompleteCallBack(result) {

      var products = result.Products;
      var itemsPerPageEle = document.getElementById("productPageItemPerPage");    
      var itemsPerPage = parseInt(itemsPerPageEle.options[itemsPerPageEle.selectedIndex].value);
      
      //-----------------------
      //store queryId
        var Qid=result.QueryId;
       doSearch (Qid);
   //alert("result.QueryId:"+Qid);
      
      //-----------------------
//Items 1-16 of 18
var endItemCount = ((result.CurrentPage * itemsPerPage));
if (endItemCount > result.TotalMatches) {
    endItemCount=result.TotalMatches;
}

    jQuery("#productItemIndicator").text('Items ' + (((result.CurrentPage-1) * itemsPerPage)+1) + '-' + endItemCount + ' of ' + result.TotalMatches);
    
    jQuery("#productItemIndicatorTop").text('Displaying Items ' + (((result.CurrentPage-1) * itemsPerPage)+1) + '-' + endItemCount + ' of ' + result.TotalMatches);

    
        //$("#myselect option:selected").text();
    var pageDD = document.getElementById("currentProductPageDropdown");    
    clearList(pageDD);
    
  
  jQuery(".previousProductLink").each(function (i) { 
          if (result.CurrentPage > 1) {            
            this.style.visibility = 'visible';
        }
        else {
            this.style.visibility = 'hidden';
        }
        });
        
        if (result.QuerySummary!=null && result.QuerySummary.length > 0) {
            jQuery(".resultheader").text('RESULTS for ' + result.QuerySummary);
        }
        else {
            jQuery(".resultheader").text('RESULTS');
        }


  jQuery(".nextProductLink").each(function (i) { 
  //alert('next next');
          if (result.CurrentPage < result.TotalPages) {            
            this.style.visibility = 'visible';
        }
        else {
            this.style.visibility = 'hidden';
        }
        });  
            
    for(pageIdx=1; pageIdx <= result.TotalPages; pageIdx++) {
        //var opt = document.createElement('option');
        var opt = new Option(pageIdx.toString(), pageIdx.toString());
        //opt.text = pageIdx;
        //opt.value = pageIdx;
        if (jQuery.browser.msie) {
            pageDD.add(opt);
        } 
        else {
            pageDD.add(opt,null);
        }
    }
//    alert(result.CurrentPage);
    if (result.CurrentPage>0) {
        pageDD.options.selectedIndex = (result.CurrentPage-1);
    }
    
    // Display the List View
    
  jQuery(".specs").find("tr:gt(0)").each(function (i) {
        if (i < products.length) {
          var prod = products[i]; 
          var prodUrl = prod.Url; //BaseUrl + "products/product-detail.aspx?ProductId=" + prod.ProductId;
          //alert(prod.Title);
          var skuEle = jQuery(this).find(".sku").eq(0);
          skuEle.text(prod.Sku);
          var listItemLink = skuEle.get(0);
          if (listItemLink!=null) {
            listItemLink.href = prodUrl;
          }
          
          var productAttributeCols = jQuery(this).find("[class^=productAttribute]");
          //$("input[id^=filter]").each(function (i) {          
          //});
          //alert($productAttributeCols);
          productAttributeCols.each(function (x) {  
                var parts = this.className.split('_');
                var prodAttributeId = parts[1];
                jQuery(this).text(' ');
                  for(var prodAttribIdx = 0; prodAttribIdx<prod.Attributes.length;prodAttribIdx++) {
                    var prodAttrib = prod.Attributes[prodAttribIdx];
                    if (prodAttrib.Key == prodAttributeId) {
                        jQuery(this).text(prodAttrib.Value);
                        break;
                    }
                  }
            });
            this.style.display = '';
        }        
        else {
            this.style.display = 'none';
        }
    });
    
    // Display the Gallery View
  jQuery(".listresult").each(function (i) {
        if (i < products.length) {
          var prod = products[i];
          //var prodUrl = BaseUrl + "products/product-detail.aspx?ProductId=" + prod.ProductId;
		   var stringTitle=prod.Title.replace(/\//g,"%252f");
          var prodUrl = prod.Url; //BaseUrl + "products/"+stringTitle+".html";
   
          var titleEle = jQuery(this).find('div h3 a').eq(0);
          titleEle.text(prod.Title);
          titleEle.get(0).href = prodUrl;
          //var $shopDescEle = $(this).find('div h4').eq(0);
          //$shopDescEle.text(prod.ShortDescription);
          
          //alert(prodUrl);
          
          var shopDescEleLink = jQuery(this).find('div h4 a').eq(0);
          shopDescEleLink.get(0).href = prodUrl;
          shopDescEleLink.text(prod.ShortDescription);
          
          var prodImgEle = jQuery(this).find('img').eq(0);
          var prodImg = prodImgEle.get(0);
//          alert(prodImg.src);
          prodImg.src = prod.ImageUrl;
          //alert(prodImg.parent);
          
          var testEle = jQuery(this).find('div h2 a').eq(0);
          testEle.get(0).href = prodUrl;
          //$prodImgEle.wrap("<a href='" + prodUrl + "'></a>");
          
            this.style.display = 'inline';
          this.style.visibility = 'visible';
        }
        else { // Hide it
          this.style.display = 'none';
            this.style.visibility = 'hidden';
        }
      }
      );
      
      // Setup the Facet Counts
      //Set all to zero
      if (result.FacetGroups.length > 0) { // If facet counts where calculated
        jQuery(".facetCount").text("0");

              //   <li><input name="filter_1" id="filter_1_129" value='129'
              // type="checkbox" value="" onclick="searchProducts('filterBox');" />surface & ecessed (45)</li>
          jQuery("input[id^=filter]").each(function (i) { // Find anything with an ID starting with filter
                var idParts = this.id.split('_');
                var productAttributeId = idParts[1];
                var productAttributeOptionId = idParts[2];
                
                for (var fgIdx=0; fgIdx < result.FacetGroups.length; fgIdx++) {        
                    var fg = result.FacetGroups[fgIdx];
                    if (fg.Title.startsWith("ProductAttribute_")) {
                        var fgProductAttributeId = fg.Title.substring("ProductAttribute_".length);
                        if (productAttributeId == fgProductAttributeId) {
                            for(var fgOptionIdx=0; fgOptionIdx < fg.Values.length; fgOptionIdx++) {
                                var facetOption = fg.Values[fgOptionIdx];
                                if (facetOption.Key == productAttributeOptionId) {
                                    jQuery(this).siblings(".facetCount").eq(0).text(facetOption.Value);
                                }
                            }
                        }
                    }
                }
            } );
       }
      
      searchInProgress=false;
     load_content(false );
      
//      if (callBackTimes==clickTimes ){
//      load_content(false );
//      callBackTimes=0;
//      clickTimes=0;
//      }else{
//      callBackTimes++;
//      }
      
}

function clearList(elSel)
{
  elSel.options.length = 0;
  
  //while(elSel.options.length > 0)
  //{
    //elSel.options[0]=null;
  //}
}

