﻿

    
function ControlResults(name, noResultsText, beforeResetLinkText, linkText, afterResetLinkText, variantsHeaderText)
{
    this.name = name;
    this.nameDiv = "ControlResult_"+name+"Div"; 
    this.loaderId = "ControlResult_Loader_"+name; 
    this.loaderImageDivId = "ControlResult_Loader_Image_"+name; 
    this.noResultsText = noResultsText;
    this.beforeResetLinkText = beforeResetLinkText;
    this.linkText = linkText;
    this.afterResetLinkText = afterResetLinkText;
    this.variantsHeaderText = variantsHeaderText;
    var self = this;
   
    
    // ------------------------------------------------------------------------------
    //  Search controller will receive all relevant events from this 
    //  control.
    // ------------------------------------------------------------------------------     
    this.RegisterAsTrigger = function(searchController)
    {
        fc.RegisterTrigger(this.name, searchController);
    }
     
    this.Render = function()
    {    
       var temp=""; 
       
       // Outer div    
        temp += "<div id='"+this.nameDiv+"' class='section-content' >";    
        
        // End outer div.
        temp += "</div>"; 
        temp += "<div id='"+self.loaderId+"' ></div>";
        temp += "<div id='"+self.loaderImageDivId+"' ></div>";
        
        temp += "<div class='product-item-variants'><a href=''><span>" + this.variantsHeaderText + "</span><hr /><span>kuk</span></a></div>";
  
        
        // Write HTML to page. 
        document.write(temp); 
        
      
        $(document).ready(function() {
           // self.ActivateLoader();
		   
        });  
    
       // $jq("#"+self.loaderId).css( {"background": url('ajax-loader.gif')});  
    }
    this.Render();

    this.ActivateLoader = function() {
        var resultsDiv = $jq("#" + self.nameDiv);
        var pos = $jq("#" + self.nameDiv).offset();
        var totalWidth = resultsDiv.outerWidth();
        var totalHeight = $jq("#" + self.nameDiv).outerHeight();

        $jq("#" + self.loaderId).css({ "width": totalWidth + "px", "height": totalHeight + "px" });
        $jq("#" + self.loaderImageDivId).css({ "width": totalWidth + "px" });

        $jq("#" + self.loaderId).show();
        $jq("#" + self.loaderImageDivId).show();
    }
       
    this.DeactivateLoader = function()
    {
        $jq("#"+self.loaderId).hide();
        $jq("#"+self.loaderImageDivId).hide();    
    }
    
    this.SubscribeEvent = function(searchController, eventName, callback)
    {
        fc.SubscribeEvent(this, searchController, eventName, callback);
    }
    
    this.SubscribeEvents = function(searchController)
    {
        fc.SubscribeEvent(self, searchController, "SearchResult", self.OnSearchResult);
        fc.SubscribeEvent(self, searchController, "BeginSearch", self.OnBeginSearch);
    }

    this.OnBeginSearch = function() {
        self.ActivateLoader();
    }

    this.OnSearchResult = function(data, _this, persistedSearch) {
        debug("ControlResults[" + self.name + "].OnSearchResult()");
        DebugAddTab();
        self.DeactivateLoader();

        setTimeout(function() {

            var numPerRow = 3;
            var temp = "";
            var numResults = data.response.docs.length; //numFound;
			if (typeof (d60) != "undefined") {
				d60.pageSuggester("smartguy", d60Controller.userId, sc.freetext, data.response.numFound + "", d60Controller.url, "search");
			}
            var numRows = parseInt(numResults / numPerRow);
            if (numResults % numPerRow != 0)
                numRows++;

            debug("total results = " + data.response.numFound);
            debug("pageresults = " + numResults);
            debug("numRows = " + numRows);

            $("div#" + self.nameDiv).html("");

            for (var row = 0; row < numRows; row++) {
                debug("row=" + row);

                var productsLeft = numResults - (row * numPerRow);
                var productsThisRow = Math.min(productsLeft, numPerRow);

                var product = "";
                for (var j = 0; j < productsThisRow; j++) {
                    var i = (row * numPerRow) + j;
                    var price = data.response.docs[i].p;
                    var sellingPrice = data.response.docs[i].sp;
                    var discountPercentage = price == sellingPrice ? 0 : Math.round((1 - (sellingPrice / price)) * 100);

                    //debug("i="+i+" numResults="+numResults);

                    // ----------------------------------------------------------------------
                    //  Product start !
                    // ----------------------------------------------------------------------
                    product += '<div class="product-item">';

                    // product description
                    product += '<div class="product-item-header">';
                    product += "<a href='" + data.response.docs[i].pu + "'>";
                    product += data.response.docs[i].n; // +"<br/>" + data.response.docs[i].c;
                    product += "</a>";
                    product += "</div>";

                    // picture
                    product += '<div class="product-item-image">';
                    product += "<a href='" + data.response.docs[i].pu + "'>";
                    product += "<img src='" + data.response.docs[i].iu + "' alt='" + data.response.docs[i].d + "' title='" + data.response.docs[i].st + "'/>";
                    product += "</a>";

                    if (discountPercentage >= 25) {
                        product += '<div class="discount-star">-' + discountPercentage + '%</div>'
                    }

                    product += "</div>";

                    // Price
                    product += '<div class="product-item-price">';
                    product += '<a href="' + data.response.docs[i].pu + '">';

                    if (price != sellingPrice)
                        product += '<span class="before-price">' + price + " " + data.response.docs[i].spc + '</span> <span class="current-price">' + sellingPrice + " " + data.response.docs[i].spc + "</span>";
                    else
                        product += '<span class="current-price">' + sellingPrice + " " + data.response.docs[i].spc + "</span>";

                    product += "</a></div></div>";
                    // ----------------------------------------------------------------------
                    //  Product end !
                    // ----------------------------------------------------------------------

                }
                product += "<div class='breaker'></div>";
                $("div#" + self.nameDiv).append(product);
            }

            $("div#" + self.nameDiv).append("<div class='breaker'></div>");

            if (numResults == 0)
                $("div#" + self.nameDiv).html("<div class='NoResultsText'>" + noResultsText + "</div><div class='NoResultsLinkDiv'>" + self.beforeResetLinkText + "<a id='Results_" + self.name + "_Link' href=''>" + self.linkText + "</a>" + self.afterResetLinkText + "</div>");

            $jq("#Results_" + self.name + "_Link").bind("click", self.OnResetLinkClick);

            InitAvailableSizesPopup();
			//if (navigator.appName != 'Microsoft Internet Explorer')
			//{
				var scrollOffset = Persister.pageOffset.get();
				window.scrollTo(0, scrollOffset);
			//}
        }, 10);
        DebugRemoveTab();
        debug("~ControlResults[" + _this.name + "].OnSearchResult()");
		
		
		//var scrollOffset = Persister.pageOffset.get();
		
		//alert('in results onsearch');
    }
   
    this.OnResetLinkClick = function()
    {
        fc.ClearAllCriteria(self.name);
        fc.TriggerSearch(self.name);
        return false;
    }
}