 // CNETComparison.js - as of June 25 2008
 
if(typeof(CNET) == "undefined")
	CNET = {};
CNET.Comparison = Class.create();

Object.extend(CNET.Comparison.prototype,{
    ACROSS_ALL_PRODUCTS : 0,
    AGAINST_REFERENCE_PRODUCT : 1, 
    compareMode : null,
    jsonCompareData: null,

                                    
	initialize: function(container,options){
		this.container = $(container);
		this.options = $H({explainOnFirstUsage  : true,
		                   servletURL           : "../SearchResults/SearchResults.ashx",
		                   language             : null,
		                   compareMode          : null});
		if(options)
			for(o in options)
				this.options[o] = options[o];
    },


    // CUSTOMER specific: store price and availability in cookies for use in the compare table
    // the price/avail as stored in a string as a JSON assoc. The key in the assoc is the product's ID
    
    
   setPriceAvailability: function(_prodID, _price, _avail)
    {
	// check if cookie exists
        var storedPriceAvailInfo = jimAuld.utils.cookies.get('CNETPriceAvail');
        var jsonedPriceAvailInfo = $H();
        if(!(storedPriceAvailInfo==null || storedPriceAvailInfo=="{}")) {
          jsonedPriceAvailInfo = jsonedPriceAvailInfo.merge( eval("jsonedPriceAvailInfo = "+storedPriceAvailInfo));
        } 

        tmpPA = new Object();
        tmpPA[_prodID] = {price: _price, availability: _avail};
        jsonedPriceAvailInfo = jsonedPriceAvailInfo.merge(tmpPA);
       

        var newCookieValue =  jsonedPriceAvailInfo.toJSON();
        jimAuld.utils.cookies.set('CNETPriceAvail', newCookieValue , 0);
        
   },

   // returns price/avail as an assoc :
   // price = getPriceAvail('123').price

   getPriceAvailability: function(_prodID)
   {

      var pa = {price: 'N/A', availability: 'N/A'};
      try {
         var storedPriceAvailInfo = jimAuld.utils.cookies.get('CNETPriceAvail');
         var jsonedPriceAvailInfo= storedPriceAvailInfo.evalJSON(true); 
         if (typeof(jsonedPriceAvailInfo[_prodID]) != 'undefined')
           pa = jsonedPriceAvailInfo[_prodID] 
      } catch (e) {}

      return pa;
   }, 

   addProductWithoutCategoryAndPA: function(_prodID, _price, _availability) 
   {
      this.addProductWithoutCategory(_prodID);
      this.setPriceAvailability(encodeURIComponent(_prodID), _price, _availability);
   },

   addProductWithCategoryAndPA: function(_prodID, _category, _price, _availability) 
   {
      this.addProductWithCategory(_prodID, _category);
      this.setPriceAvailability(encodeURIComponent(_prodID), _price, _availability);
   },


   actOnCategoryChange: function()
   {
      jimAuld.utils.cookies.del('CNETPriceAvail');
      jimAuld.utils.cookies.del('CNETCompareInfo');  
   },  

    // Adds a product to the compare list but only after its category has been retrieved. This behavior is
    // needed to ensure that products in the list are in the same category (CNET or subset of CNET).
    // This method is much slower than addProduct(prodID, categoryID) and should only be used when there is no
    // way to know what the product's category is.
    
    addProductWithoutCategory: function(_prodID, price) {
		var prod=encodeURIComponent(_prodID);
		var URL = "compareCNET/SearchResults/SearchResults.ashx" ; 
 		var a_Request = new Ajax.Request(URL, { 
			method: 'get',
			parameters: "&lang="+this.options.language+"&what=productcategory&format=JSON&prodid="+prod,                    
			onSuccess: (function (req) { this.addProductWithoutCategoryCallback(req.responseText);}).bind(this)
			});
    },
    
    addProductWithoutCategoryCallback: function(response)
    {
          eval("var productCategory = "+response);
          var product = productCategory.product;
          var category = productCategory.category;
          if(category=="BAD_CATEGORY") {
               alert("Beklager, dette produktet har ingen sammenlignbare data");
               $(decodeURIComponent(product)).checked = false;
          } else {
             this.addProductWithCategory(product,category);
        }  
    },
    
    
    addProductWithCategory: function(_prodID, _categoryID) {
        var storedCompareInfo = jimAuld.utils.cookies.get('CNETCompareInfo');
        var jsonedCompareInfo = null;
        if(storedCompareInfo==null) 
        {
           jsonedCompareInfo = {category: _categoryID, products: [_prodID]};
        } else
        {
            try {
              jsonedCompareInfo = storedCompareInfo.evalJSON(true); 
            } catch (e) 
            { jsonedCompareInfo = {category: _categoryID, products: [_prodID]};
            }

            // if a switch to a new category has happened, wipe out the products list and 
            // reset the category:
            
//            if(_categoryID != jsonedCompareInfo.category)
//            {
//            alert("Product must be in the same category.");
//            jsonedCompareInfo.products.each(function(p) { try { $(p).checked = false;} catch (e) {}});
//            jsonedCompareInfo.category = _categoryID;
//            jsonedCompareInfo.products = [ _prodID];
//            this.actOnCategoryChange();
//            } else
//            {        
               if(jsonedCompareInfo.products.indexOf(_prodID) == -1) {
                      jsonedCompareInfo.products[jsonedCompareInfo.products.length] = _prodID;
//                  }
            }
        }
        jimAuld.utils.cookies.set('CNETCompareInfo', Object.toJSON(jsonedCompareInfo), 0);
    },
    
    removeProduct: function(_prodID)
    {
        var storedCompareInfo = jimAuld.utils.cookies.get('CNETCompareInfo');
        var jsonedCompareInfo = null;
        try {
              jsonedCompareInfo = storedCompareInfo.evalJSON(true); 
              if(jsonedCompareInfo.products.indexOf(_prodID) != -1) 
              {
                 jsonedCompareInfo.products = jsonedCompareInfo.products.without(_prodID);
                 jimAuld.utils.cookies.set('CNETCompareInfo', Object.toJSON(jsonedCompareInfo), 0);
              }
            } catch (e) {}    
    },
    
    
    removeProductFromJSON: function(_prodID)
    {
       var productArray = new Array();
       for(i=0;i<this.jsonCompareData.Products.length;i++)
       {
          if(this.jsonCompareData.Products[i].ProdID != _prodID)
            productArray.push(this.jsonCompareData.Products[i]);
       }
       this.jsonCompareData.Products = productArray;
       
    },
    
    removeProductFromDisplayedTable: function(_prodID)
    {
        var unescapedProdID = decodeURIComponent(_prodID);
           try {
              this.removeProduct(unescapedProdID);
              this.removeProductFromJSON(_prodID);
              $(unescapedProdID).checked = false;
              this.redrawTable();
            } catch (e) {}    
    },
    
    getProductList: function()
    {
       var storedCompareInfo = jimAuld.utils.cookies.get('CNETCompareInfo');
       var jsonedCompareInfo = null;
       var result = "";
       
       try {
              jsonedCompareInfo = storedCompareInfo.evalJSON(true); 
              for(i=0;i<jsonedCompareInfo.products.length;i++)
                result += "'"+encodeURIComponent(jsonedCompareInfo.products[i])+"'"+ ((i==jsonedCompareInfo.products.length-1)?"":",");             
            } catch (e) {}   
       return result; 
    },
    
    getSearchComparison: function()
     {
        var xjsonedloggedIn='';
        var productList = this.getProductList();
       
	    if(productList == null || this.options.language == null) 
	    {
	       alert("Compare.js not set-up correctly");
	    } 
	    else 
	    {	    	
	try {	    	
		var xstoredCompareInfo = jimAuld.utils.cookies.get('CNETCompareInfo');
		var xjsonedCompareInfo = null;
		xjsonedCompareInfo = xstoredCompareInfo.evalJSON(true);
		var xjsonedloggedIn=jimAuld.utils.cookies.get('loggedIn');
		if (xjsonedloggedIn==null || xjsonedloggedIn==undefined)
			xjsonedloggedIn=''; 
		var pipes = "'||'";
		var foo = xjsonedCompareInfo.products ;
		var repString = String(foo) ;
		var items = repString.replace(/,/g , pipes);	
	} catch (e) {}
	
	if (items==undefined)
	items='';
	
	$('SearchListing').hide() ;
	$('compareTable').innerHTML="" ;
	var marketingUpdater = new Ajax.Updater(
			'compareTable', 
			"product_compare.asp", 
			{
				method: 'get', evalScripts: true,
				parameters: "products=" + "'" + encodeURIComponent(items) + "'" + "&mscssid=" + xjsonedloggedIn
			});
	$('compareTableBackground').setStyle({opacity: 0.99}).show();

//window.location = "product_compare.asp?products=" + "'" + encodeURIComponent(items) + "'" + "&mscssid=" + xjsonedloggedIn

// NewWin=window.open('/bb/product_compare_local.asp?products=' + "'"+encodeURIComponent(items)+"'" , 'Compare' )

//    	            var ajaxRequest = new Ajax.Request();
//		    ajaxRequest.setOptions (
//		    {method: 'get',
//		          parameters: "&lang="+this.options.language+"&what=searchcomparison&format=JSON&prodids=("+productList+")",                    
//		          onSuccess: (function (req) { this.getSearchComparisonCallback(req.responseText);}).bind(this)
//		          });
//  
//  	        
//  	        ajaxRequest.request(this.options.servletURL);
       }
      },
                
    getSearchComparisonCallback: function(response) 
      {
           eval("this.jsonCompareData = "+response);
           if(this.jsonCompareData.Products.length > 0) 
           {
              $('SearchListing').hide();
              this.redrawTable();
           }
      },
      
    
    redrawTable: function()
     { 
    
        var tableElement= this.buildTable(this.jsonCompareData);
        removeAllChildren($('compareTable'));
        $('compareTable').appendChild(tableElement);
        $('compareTableBackground').setStyle({opacity: 0.99}).show();
     },
   
      
   buildTable: function(data)
   {

    var table = document.createElement('table');
    table.className='sortable';
    table.width='100%';
    
    var tbody = document.createElement('tbody');
    
            
//  START | Create rows, which info do we wish to display
	var arrFields = new Array('Remove','Image','Manufacturer','Title','PartNumber');
	var arrFormat = new Array('chkbox','img','text','text','text');
//  var arrFields = new Array('Remove','Image','Manufacturer','Title','PartNumber','Pris','Lagerstatus','');
//  var arrFormat = new Array('chkbox','img','text','text','text','customerPrice', 'customerAvailability','customerAddToCart');

    //START | HEADER
    for(var j=0; j<arrFields.length; j++)
    {
        //Start a new row.
        var tr = document.createElement('tr');
            
        //start | Header
        for(var i=0; i<data.Products.length; i++ )
        {
           
            //First product display row header
            if (i==0)
            {
                var td = document.createElement('td');
                if (arrFormat[j] != 'img' && arrFormat[j] != 'chkbox')
                {
                    td.innerHTML=unescape(arrFields[j]);
                }
                tr.appendChild(td);
            }
            
            
            var td = document.createElement('td');
    
            switch(arrFormat[j])
            {
            case 'img':
                var tmpimg = document.createElement('img');
                tmpimg.src = data.Products[i][arrFields[j]];
                td.appendChild(tmpimg);
                td.align="center";
                tr.appendChild(td);
                break ;   
            case 'chkbox':
                var tmpchkbox = document.createElement("input");
                tmpchkbox.setAttribute("type","checkbox"); 
                tmpchkbox.setAttribute("id", "chk" + data.Products[i].ProdID); 
                tmpchkbox.setAttribute("value", data.Products[i].ProdID); 
                tmpchkbox.defaultChecked = true; 
                tmpchkbox.disabled = (data.Products.length == 1);
                tmpchkbox.onclick =  new Function("compare.removeProductFromDisplayedTable('" + data.Products[i].ProdID + "');");
                td.appendChild(tmpchkbox);
                td.align="center";
                tr.appendChild(td);
                break;
             case 'customerAddToCart':

                var add2cartA =document.createElement('a');
                add2cartA.href="javascript:SCSearch('"+data.Products[i].ProdID+"',1);";
                var add2cartImg= document.createElement('img');
                add2cartImg.setAttribute('class','compareAddToCart');
                add2cartImg.setAttribute('border','0');
                add2cartImg.src="http://www_customer_com/image/shopping.gif";
                add2cartA.appendChild(add2cartImg);
                td.appendChild(add2cartA);
                td.align="center";
                tr.appendChild(td);
                break ;  
            case 'customerPrice':
                var pa = this.getPriceAvailability(data.Products[i].ProdID);
                td.innerHTML=pa.price+" kr.";
                td.align="center";
                tr.appendChild(td);
                break;
            case 'customerAvailability':
                var pa = this.getPriceAvailability(data.Products[i].ProdID);
                td.innerHTML=((pa.availability=="")?"0":(pa.availability))+" stk.";
                td.align="center";
                tr.appendChild(td);
                break;
            default:
                td.innerHTML=unescape(data.Products[i][arrFields[j]]);
                td.align="left";
                tr.appendChild(td);
                break
            }               
            //set align
            
        }
        if (arrFormat[j] != 'img' && arrFormat[j] != 'chkbox')
        {
            tr.className = "compareHeader";
        }
        tbody.appendChild(tr);
    }
    
       
        
        //Need to work out which Product has the most attributes and start with this one
        var iStartProdPos = 0;
        
        var numberOfAttributes = data.Products[0].Attributes.length;
        var currentSection = null; // name of current section
        var currentSectionID = 0;  // number of sections displayed so far; used to refrain from "differentiating" the first section (Header)
                        
        //Next create array of ProdPosition starting with Prod with Max Attributes
        for(var iAtt=0; iAtt<numberOfAttributes; iAtt++ )
        {
           // if we are in a new attribute section, display a new section row 
           var section_attribute = unescape(data.Products[0].Attributes[iAtt]['AtrName']).split("/");
           
           if(section_attribute[0] != currentSection) 
           {
              currentSection = section_attribute[0];
              currentSectionID++;
              var tr = document.createElement('tr');
              var td = document.createElement('td');
              td.colSpan = data.Products[iStartProdPos].Attributes.length+1;
              td.className = "compareSectionHeader";
              td.innerHTML=currentSection;
              tr.appendChild(td);
              tbody.appendChild(tr);
           }
           
           var differenceHighlightingBitset = this.getDifferenceHighlightingBitset(iAtt, data.Products);
           
           for(var iProd=0; iProd<data.Products.length; iProd++ )
           {
                if (iProd==0)
                {
                   //Start a new row.
                   var tr = document.createElement('tr');
                   var td = document.createElement('th');
                   td.innerHTML=unescape(section_attribute[1]);
                   td.className = "compareAttributeName";
                   tr.appendChild(td);
                }
            
                 var td = document.createElement('td');
                 td.innerHTML=unescape(data.Products[iProd].Attributes[iAtt]['AtrValue']);
                 td.align="center";
                 td.className = differenceHighlightingBitset.pop()?"compareDifferent":"compareIdentical";
                 tr.appendChild(td);
           }
        
           tr.className = (iAtt % 2 == 1)?"compareEvenRow":"compareOddRow";
           tr.height = "30px"
            
           tbody.appendChild(tr);   
            
        }
        
    table.appendChild(tbody);
    table.id="table_" + Math.floor ( Math.random ( ) * 100 );
    
    return table;
 },

 getDifferenceHighlightingBitset: function(iAtt, products)
 {
    var bitset = new Array();
    var seenADifference = false;
    var attributeValue = null;
    if(this.options.compareMode == CNET.Comparison.prototype.ACROSS_ALL_PRODUCTS) 
    {
       for (p=0; p<products.length;p++)
       {
          if(p==0)
          attributeValue = products[p].Attributes[iAtt]['AtrValue'];
          seenADifference = seenADifference?seenADifference:(products[p].Attributes[iAtt]['AtrValue'] != attributeValue);
       }
       
       // set the same bit for all products
       for(p=0;p<products.length;p++)
           bitset.push(seenADifference);
   } else
   {
     for (p=0; p<products.length;p++)
       {
          if(p==0)
          attributeValue = products[p].Attributes[iAtt]['AtrValue'];
          seenADifference = seenADifference?seenADifference:(products[p].Attributes[iAtt]['AtrValue'] != attributeValue);
          bitset.push(seenADifference);
       }
   }

   return bitset.reverse(); // reversed because it will be consumed starting with the first product
}
});