/**
 * Library with functions to set up and handle the product refine pages.
 *
 * Version 0.9 (21/03/2009)
 * @requires jQuery v1.2.6 or later
 * Copyright (c) 2008-2009 <GX> Creative Online Development
 *
 * Known issues:
 *  -
 *
 */

var sortRemember = '';
var selectedProducts = new Array();
var from = 0;

//overall labels
var general_refine_tooltip_maxcompare_alert = 'Max is 3.';
var general_refine_tooltip_compare = 'Vergelijk'; //holds the "compare" label
var general_refine_tooltip_compare_show = 'Bekijk vergelijking'; 
var general_total_amount_of_products = ' producten. pagina'; //holds the "total amount" label
var general_refine_tooltip_first_select_products = '';
var compareLink = ''; //link to compare page

var totalCount = 0;
var documentUrl = new QueryStringBuilder();
setUpQueryStringBuilder();
  
function showAmount(amount){
  totalCount = amount;
}

function buildViewAreaSearch(imagePath, numberOfSearchResultsFoundText, showAllFoundProductsText) {
  if (totalCount == 0) {
    totalCount = applicationData.prdproducts.prdproduct.length;
  }

  $("div.products").before('<p><strong>' + applicationData.prdproducts.prdlistinfo[0].numberofproducts +
     '</strong>&nbsp;' +  numberOfSearchResultsFoundText + ':</p>');

  buildViewArea(imagePath, true, true);
  
  if (totalCount == 2 && applicationData.prdproducts.prdproduct.length > totalCount) {
    $("div.products").after('<p><a href="/" onclick="document.location.href = document.location.href + \'&showProd=all\';' +
    ' return false;">' + showAllFoundProductsText + '</a></p>');
  }
}

function buildViewArea(imagePath, isSearchResult, hideCompare, shopLink, buyText, overlayLink, overlayText) {

  var l = applicationData.prdproducts.prdproduct.length;
  var popular = $(".mostpopular div.product").length;
  
  if (popular == 0){//only build popular products once (on load)
	  //Use an array to increase performance(this increases the performance dramatically in IE)
	  var htmlMostPopular = new Array(3);
  }
  if (popular == 0 && l > 3){ //this is only needed when more than 3 products are returned
	  var htmlOtherProducts = new Array(l-3);
  } else {
	  var htmlOtherProducts = new Array(l);
  }

  // Use 'for'-loop instead of the JQuery '$.each'. Should increase performance (However it does
  // not seem to help much)
  for (q=0; q < l; q++) {
    var productDiv = new Array();

    if (!isSearchResult || (isSearchResult && q < totalCount)) {
      productid = applicationData.prdproducts.prdproduct[q]['id'];
      productcode = applicationData.prdproducts.prdproduct[q]['code'];
      productname = applicationData.prdproducts.prdproduct[q]['name'];
      productimage = applicationData.prdproducts.prdproduct[q]['image1'];
      
      if (productimage === undefined) {
          productimage = applicationData.prdproducts.prdproduct[q]['image'];
      }

      if (productimage === undefined) {
          productimage = imagePath + '/globals/no-img.gif';
      }

      productdetaillink= applicationData.prdproducts.prdproduct[q]['detaillink'];
      properties = applicationData.prdproducts.prdproduct[q]['prdproperties'];

      //start product div
      productDiv.push('<div class="product">');
      //detail link only when shoplink is empty
      if (shopLink === undefined) {
          productDiv.push('<a class="imgholder" href="' + getProductDetailLink(productdetaillink) + '">');
      }
      
      //thumb image
      productDiv.push('<img src="' + productimage +'" alt="' + productname + '" />');
      if (shopLink === undefined) {
          productDiv.push('</a>');
      }
      
      productDiv.push('<h3>');
      //product title
      if (shopLink === undefined) {
          productDiv.push('<a href="' + getProductDetailLink(productdetaillink) + '">');
      }
      //productcode
      productDiv.push(productcode);
      //product title
      productDiv.push('<span>' + productname + '</span>');
      if (shopLink === undefined) {
          productDiv.push('</a>');
      }
      productDiv.push('</h3>');
      
      //compare
      //<div class="compare-product"><input id="compare1" type="checkbox" /><label for="compare3">Vergelijken</label></div>
      if (!isSearchResult&&!hideCompare) {
	      productDiv.push('<div class="compare-product">');
	      productDiv.push('<input type="checkbox" id="check_' + productid + '" class="comparecheck check_' + productid + '" name="' + productname.replace("'", "''") + '" />');
	      productDiv.push('<label for="check_' + productid + '">' + general_refine_tooltip_compare_show + '</label>');
	      
	      productDiv.push('<a href="#" style="display:none;" class="btndark">' + general_refine_tooltip_compare_show + '</a>');
	      //close compare div
	      productDiv.push('</div>');
      }

      //dynamic properties
      productDiv.push('<ul>');
      var hasTurn = false;
      var hasTilt = false;
      $.each(properties, function(j,val) {
          if (j<=4) {
            propid = val.id;
            if (propid > 0){ //don't render application property which is id 0
	            propname = val.name;
	            propval = val.value;
            	//check if turn of tilt are present
            	if (val.label == "turn" && propval.split(" ")[0] > 0){
            		//it has turn possibilities
            		hasTurn = true;
            	}
            	if (val.label == "tilt" && propval.split(" ")[0] > 0){
            		//it has tilt possibilities
            		hasTilt = true;
            	}
            	if ((val.label == "maxSize" || val.label == "minSize") && propval.indexOf('"') == -1){
            		propval += ' "';
            	}
            	if ((val.label == "tilt" || val.label == "turn") && propval.indexOf('°') == -1){
            		propval += ' °';
            	}
	            productDiv.push('<li class="sortprop_' + propid + '">');
	            productDiv.push(propname + ':&nbsp;'); 
	            if (propval=='No') {
	              productDiv.push('-');
	            } else {
	              if (propval=='Yes') {
	                productDiv.push('<span class="present">&nbsp;</span>');
	              } else {
	                productDiv.push(propval);
	              }
	            }
	            productDiv.push('</li>');
            }
          };
      });

      // Double loop. Is not needed!
      $.each(properties, function(j,val) {
          if (j>4) {
            if (val && val.label != 'professionalUsp' ) {
              propid = val.id;
              propname = val.name;
              propval = val.value;
              productDiv.push('<li class="sortprop_' + propid + '">');
              productDiv.push(propname + ':&nbsp;'); 
              if (propval=='No') {
                productDiv.push('-');
              } else {
                if (propval=='Yes') {
                  productDiv.push('<span class="present">&nbsp;</span>');
                } else {
                  productDiv.push(propval);
                }
              }
              productDiv.push('</li>'); 
            }
          }
      });
      //close property list
      productDiv.push('</ul>');
      
      //check if turn, tilt or flat applies
      if (applicationData.prdproducts.prdmovable != undefined){ //suppose this category has products which move
    	  if (applicationData.prdproducts.prdmovable.length > 0) {
		      productDiv.push('<ul class="list-movement">');
		      
		      // Determine language labels
		      var turnLabel = "";
		      var tiltLabel = "";
		      var flatLabel = "";
		      
		      for (i = 0; i < applicationData.prdproducts.prdmovable.length; i++) {
		    	  switch (applicationData.prdproducts.prdmovable[i].id) {
		    	  case 0:
		    		  turnLabel = applicationData.prdproducts.prdmovable[i].name;
		    		  break;
		    	  case 1:
		    		  tiltLabel = applicationData.prdproducts.prdmovable[i].name;
		    		  break;
		    	  case 2:
		    		  flatLabel = applicationData.prdproducts.prdmovable[i].name;
		    		  break;
		    	  }
		      }
		      
		      if (hasTurn) {
		    	  productDiv.push('<li class="turn">' + turnLabel + '</li>');
		      } else {
		    	  if (hasTilt) {
		    		  productDiv.push('<li class="tilt">' + tiltLabel + '</li>');
		    	  } else {
		    		  productDiv.push('<li class="flat">' + flatLabel + '</li>');
		    	  }
		      }
		      
		      productDiv.push('</ul>');
    	  }
      }

      // Create links for external shop integrators
      if (shopLink !== undefined) {
        var articleVariables = 'vogelsArticleID=' + escape(productid);
        articleVariables += '&vogelsArticleCode=' + escape(productcode);
        articleVariables += '&vogelsArticleName=' + escape(productname);
        productDiv.push('<dd class="buylink"><em>');
        productDiv.push('<a href="' + shopLink + articleVariables + '">' + buyText + '</a>');
        productDiv.push('</em></dd>');
        
        productDiv.push('<dd class="related_overlay"><em>');
        productDiv.push('<a href="' + overlayLink + '&dbid=' + productid + '" title="' + productname.replace('"', '&quot;') + '">' + overlayText + '</a>');
        productDiv.push('</em></dd>');
      }
      productDiv.push('</dl></div>');
      
      // Put the html in the right list!
      // The logic below is complex because of the 3 popular products that have to display
      // Initially, 11 products are returned, afterwards only 8 per page
      // Once placed, the popular products stay there
      
      if (!from){
    	  from = 0;
      }
      
      if (q < 3 && popular == 0){ //product 1, 2, 3
    	htmlMostPopular[q] = productDiv.join('');
      } else if (popular == 0 && from == 0){
    	htmlOtherProducts[q-3] = productDiv.join('');
      } else {
    	  if (from == 0){
    		  htmlOtherProducts[q-3] = productDiv.join('');
    	  } else {
    		  htmlOtherProducts[q] = productDiv.join('');
    	  }
      }
    }
  };

  // Wrap an extra div around the product divs. Should increase performance.
  if (popular == 0){
	  $(".mostpopular").append('<div>' + htmlMostPopular.join('') + '<div>'); //product 1,2,3
  }
  if (!(htmlOtherProducts === undefined)){
	  $(".moreproducts").append('<div>' + htmlOtherProducts.join('') + '<div>'); //other products
	  
	  //add nomargin to every 4th product item
	  $(".moreproducts div.product").filter(function(index){
		  return (index%4 == 3);
	  }).addClass('nomargin');

	  //add click event to compare button
	  $("div.compare-product a.btndark").click(function(){
		  showCompare(general_refine_tooltip_first_select_products, compareLink);
	  });
  }
  
  //set totalCount to paging
  if (applicationData.prdproducts.prdlistinfo != undefined && !isSearchResult){
	  totalCount = applicationData.prdproducts.prdlistinfo[0].numberofproducts;
	  $(".paging ul li:first span:first").html(totalCount + ' ' + general_total_amount_of_products);
	  $(".bottom ul li:first span:first").html(totalCount + ' ' + general_total_amount_of_products);
  } 
  // PNG fix for IE
  $('img[src$=.png],ul#sub-tabs li a, .home h2, ul#innerfade_list li.current a, ul#random_images li span, #random_images dt, .product-overview h2 a').ifixpng();

  // Bind click event to the compare boxes.
  $(".comparecheck").bind('click', function(e) {
    var added = setSelectedProduct($(this).attr('class'), $(this).attr('name'));
    if (added){
	    $(this).next("label").hide(); //hide the checkbox
	    $(this).parent().find("a.btndark").show(); //show the button
    } else {
	    $(this).next("label").show(); //hide the checkbox
	    $(this).parent().find("a.btndark").hide(); //show the button
    }
  });

  // Bind click to uncheck all checkboxes.
  $(".deselect").bind('click', function(e) {
    $('.comparecheck').attr('checked', false);
    $('dd.selectedproduct').remove();
    // Reset the selected products.
    selectedProducts = new Array();
  });
  
  // Bind external shop links
  $("dd.buylink a").bind('click', function(e) {
    window.opener.location.href = $(this).attr('href');
    window.close();
    e.preventDefault();
  });
  $("dd.related_overlay a").fancybox({
    'hideOnContentClick': false,
    'callbackOnShow': function() {
      $('#fancy_ajax .fragement .buyarticle_link').each(function() {
        var relatedVariables = 'vogelsArticleID=' + escape($(this).children("input[@name='articleid']").attr("value"));
        relatedVariables += '&vogelsArticleCode=' + escape($(this).children("input[@name='articlecode']").attr("value"));
        relatedVariables += '&vogelsArticleName=' + escape($(this).children("input[@name='articlename']").attr("value"));
        var a = $(this).children('a');
        a.text(buyText);
        a.attr('href', shopLink + relatedVariables);
        a.bind('click', function(e) {
          window.opener.location.href = shopLink + relatedVariables;
          window.close();
          e.preventDefault();
        });
      });
    }
  });

  setCheckboxes();
}

/**
 * Function to set the appropriate checkboxes for the product compare.
 */
function setCheckboxes() {
  // Reset the layover with the selected products.
  $('dd.selectedproduct').remove();

  // Set all the checkboxes to unchecked.
  $('.comparecheck').attr('checked', false);

  // Determine the number of selected products. The selected products are set in a global variable.
  var numberOfProducts = selectedProducts.length;
  var removeArray = [];

  // Set checkboxes to checked for the selected products. When using a refinement it can happen
  // the selected product is not in the scope anymore. We remove it from the 'selectedProducts'-array,
  // because they are not valid anymore.
  if (numberOfProducts > 0) {
    for (i=0;i<numberOfProducts;i++) {
      // Check whether the product is still in the scope.
      if ($('.check_' + selectedProducts[i]).length>0) {
        $('.check_' + selectedProducts[i]).attr('checked', true);
        $('.selectedproducts').append('<dd class="selectedproduct selectedproduct_' + selectedProducts[i] + '"><a href="#">' + $('.check_' + selectedProducts[i]).attr('name') + '</a></dd>');
      } else {
        // Add product to remove array when it is not in the scope anymore.
        removeArray.push(selectedProducts[i]);
      }
    };
  }

  // Remove selected.
  for (j=0;j<removeArray.length;j++) {
    selectedProducts = $.grep(selectedProducts, function(val) { return val != removeArray[j]});
  }
}

function clearViewArea() {
  //$("ul#criterium").html('');
  $("div.moreproducts div.product").remove();
}

function setupSort(options) {

  $('dl.sort-horizontal dd').each(function() {

    sortMethod = $(this).attr('id');
    $(this).bind('click', {'newMethod': sortMethod}, function(event) {

      var funcName = event.data['newMethod'];
      var funcParam = "";

      if ($(this).attr('class')=='sort-up') {
          funcParam = '\'asc\'';
          $('dl.sort-horizontal dd').removeClass('sort-up');
        $('dl.sort-horizontal dd').removeClass('sort-down');
          $(this).addClass('sort-down');
        } else {
        funcParam = '\'desc\'';
        $('dl.sort-horizontal dd').removeClass('sort-up');
        $('dl.sort-horizontal dd').removeClass('sort-down');
          $(this).addClass('sort-up');
        }

        if (funcName.indexOf('_')>-1) {
          funcNameParam = funcName.split('_');
        funcName = funcNameParam[0];
        funcParam = funcParam + ',' + funcNameParam[1];
      }

      //Create the function call from function name and parameter.
      var funcCall = funcName + "(" + funcParam + ");";

      //Call the function
      var ret = eval(funcCall);
      sortRemember = funcCall;

      // Keep the selected number of pages.
      numPerPages = $('dl.numberofpagesgroup').find('dd').find('a.current').filter(':first').text();

      if (numPerPages=='') {
        numPerPages = 8;
      }
      
      if (options) {
        options.numPerPage = numPerPages;
      } else {
        options = new Object();
  options.numPerPage = numPerPages;
      }
      $('div.moreproducts').divPager(options);
    });
  })
}

function sort() {
  var options = {};

  // Default sort by title.
  if (sortRemember!='') {
    eval(sortRemember);
      // Setup the divPager with the selected number of pages.
      //numPerPages = $('dl.numberofpagesgroup').find('dd').find('a.current').filter(':first').text();
      numPerPages = 8;
    
      if (numPerPages=='') {
        numPerPages = 8;
      }
      options = {numPerPage: + numPerPages};
  } else {
    // Sort is done server side.
    //sortTitle('asc');
  }

  $('div.moreproducts').divPager(options);
}

function pageBinder(options) {
  //numPerPages = $('dl.numberofpagesgroup').find('dd').find('a.current').filter(':first').text();
  numPerPages = 8;

  options.numPerPage = numPerPages;
  $('div.moreproducts').divPager(options);
}

function sortTitle(order) {
  options = {order: + order};
  $("div.sort-column").tsort("h2>a",{order:order});
}

function sortProp(order, propid) {
  // 'dl>dd.sortprop_' + propid
  selector = '.sortprop_' + propid;
  $("div.sort-column").tsort(selector,{order:order});
}

function showCompare(message, baseUrl) {
  if (selectedProducts.length>0) {

    var params;
    params = setupServletRequest();

    var serial = [];
    for (var name in params) {
      // Filter out the typeofpage and dbid.
      if (name != 'typeofpage' && name != 'dbid') {
        serial.push(encodeURIComponent(name) + '=' + encodeURIComponent(params[name]));
      }
    }
    serial.push('selectprods=' + selectedProducts.join(','));
    if (baseUrl.indexOf('?') >-1) {
      baseUrl = baseUrl + '&' + serial.join('&');
    } else {
      baseUrl = baseUrl + '?' + serial.join('&');
    }
    document.location = baseUrl;
  } else {
    alert(message);
  }
}

function setSelectedProduct(productValue, productName) {
  var productId = productValue.replace('comparecheck ', '').replace('check_', '');

  if ($.inArray(productId, selectedProducts) >-1) {
    var valueToRemove = productId;
    selectedProducts = $.grep(selectedProducts, function(val) { return val != valueToRemove; });
    $('.selectedproduct_' + productId).remove();
  } else {
    if (selectedProducts.length>=3) {
      alert(general_refine_tooltip_maxcompare_alert + '.');
      $('.check_' + productId).attr('checked', false);
      return false;
    } else {
      selectedProducts.push(productId);
      $('.selectedproducts').append('<dd class="selectedproduct selectedproduct_' + productId + '"><a href="#">' + productName + '</a></dd>');
      return true;
    }
  }
}

// selectedValueName : name of the global variable we store the selected in.
function buildRefineBlock(selectedValueName, dlId, allId, prefix, jsonPath, allLinkText, removeCriteriaText, noOptionsText, valueToShow, idIsValue, checkForDoubleValues) {
  // Only rebuild when the type is not yet selected or it was not build before(passed on from qs).
 // if (eval(selectedValueName)=='' || ($('ul#' + dlId).find('li').not('.title').length==0)) {
    $('ul#' + dlId).find('li').not('.title').remove();

    // NOTE: does not need to be rebuild. Could find out other way for performance reasons.
    $('#' + allId).children().remove();
    
    $('ul#' + dlId).append('<li><a href="#" class="selected' + dlId + 'Placeholder" style="display:none"></a></li>');
    
    j = 0;
    e = 0;
    more = false;
    uniqueItemArray = new Array();
    var overlayArr = new Array();
      
    if (!eval(jsonPath) || eval(jsonPath)=='') {
      $('ul#' + dlId).append('<li><span class="txt">' + noOptionsText + '</span></li>');
    } else {
      $.each(eval(jsonPath),function(i,val) {
    	// Get the id of the JSON object.
        objectid = val.id;

        // Determine which property to show from the JSON object. It defaults to 'name'.
        if (valueToShow != '') {
          objectvalue = eval('val.' + valueToShow);
        } else {
          objectvalue = val.name;
        }

        // Only show unique items in the refine boxes.
        addItem = true;
        if (checkForDoubleValues) {
           if (contains(uniqueItemArray, objectvalue, 'value')) {
            addItem = false;
           }
         }

        if (addItem) {
          // Create an object to store a 'id'/'value' combination.
          var idValue = new Object();
          idValue.value = objectvalue;

          // Check whether we need the value as identifier(for example used for 'size'-refinements
          // which do not have a separate id.)
          if (idIsValue) {
            idValue.id = objectvalue;
          } else {
            idValue.id = objectid;
          }
          uniqueItemArray[e] = idValue;
          e++;
        }
      });

      // Sort the items.
      uniqueItemArray.sort(compareObjects);
          
      var numberOfUniqueItems = uniqueItemArray.length;
      var numberInVisibleList = 6;
      var numberOfColumnsInOverlay = 5;
      var numberOfMoreItems = numberOfUniqueItems - numberInVisibleList;
      var numberOfItemsPerColumn = 0;
      
      if (numberOfMoreItems > 0) {
        numberOfItemsPerColumn = Math.round(numberOfMoreItems / numberOfColumnsInOverlay);  
        var overlayArr = new Array(numberOfMoreItems);
        if ((numberOfMoreItems % numberOfColumnsInOverlay) != 0) {
          numberOfItemsPerColumn++;
        }        
      }
      
      var itemInColumnCounter = 0;
      var opened = false;
      var liClass = "";
            
      for (j=0;j<numberOfUniqueItems;j++) {
        if (dlId == 'movable'){
    	  //exception for "movable" category
          var valueId = uniqueItemArray[j]['id'];
          if (valueId == 0){
        	liClass = " class='turn'";
          } else if (valueId == 1){
        	  liClass = " class='tilt'";
          } else {
        	  liClass = " class='flat'";
          }
        }
    	  
        if (j < numberInVisibleList) {
          $('ul#' + dlId).append('<li' + liClass + '><a href="#" class="' + dlId + 'click" id="'+ prefix+ '_' + (uniqueItemArray[j]['id']+'') + '">' + uniqueItemArray[j]['value'] + '</a></li>');
        } else {
	      // Set the remaining ones.
	      more = true;
	    
	      if (itemInColumnCounter == 0) {
	        overlayArr.push('<ul class="alphabetic">');
	        var opened = true;      
          }
          
	      overlayArr.push('<li' + liClass + '><a href="#" class="' + dlId + 'click" id="' + prefix + '_' + (uniqueItemArray[j]['id']+'') + '">' + uniqueItemArray[j]['value'] + '</a></li>');
	      itemInColumnCounter++;
	
  	      if (itemInColumnCounter == numberOfItemsPerColumn) {
	        itemInColumnCounter = 0;
	        var opened = false; 
	        overlayArr.push('</ul>');
	      }
	    }
	  }
	  if (opened) {
	    overlayArr.push('</ul>');
	  }
	  $('#' + allId).append(overlayArr.join(''));  
    }
        

    // Setup the more link when needed.
    if (more) {
      $('ul#' + dlId).append('<li class="bullet-refine"><a href="#TB_inline?keepThis=true&amp;&inlineId=overlay' + allId + '&amp;height=430&amp;width=960" class="thickbox" id="' + allId + 'link">' + allLinkText + '</a></li>');
      tb_init('a.thickbox, area.thickbox, input.thickbox');
    }

    $('.' + dlId + 'click').bind("click", function() {
      // Remove the lightbox when needed.
      tb_remove();
      var selValue = $(this).attr('id').split('_')[1];
      // Add the selected value to the querystring.   
      buildQuery(dlId, selValue);
     
      $(this).attr('href', documentUrl.GetFullString());

    });

    // When a value is selected it should be added to the criteria area.
    var selectedValue = eval(selectedValueName);
    
    if (selectedValue != '' ) {
      setCriteria(selectedValueName, dlId, selectedValue, removeCriteriaText, prefix);
    }
 // }
}

function getDocumentBaseUrl() {
  var locationBase = document.location + '';
  if (locationBase) {
    locationBase = locationBase.replace("#","");
  }
  return locationBase;
}

function setCriteria(selectedValueName, dlId, selectedValue, removeCriteriaText, prefix) {

      $('ul#' + dlId).find('li').children().not('.selected' + dlId + 'Placeholder').hide();

      // Set the selected in the placeholder.
      showSelector = 'a[id=' + prefix + '_' + selectedValue + ']';
      selectedText = $(showSelector).html();

      $('.selected' + dlId + 'Placeholder').html(selectedText);
      $('.selected' + dlId + 'Placeholder').show();
      
      // when its movable
      if (dlId == 'movable'){
    	 var movableClass = $('ul#' + dlId).find(showSelector).parent("li").attr("class");
    	 $('.selected' + dlId + 'Placeholder').parent("li").addClass(movableClass);
      }

      // Add to the criteria area. (only when not present yet)
      if ($('a.remove' + dlId).length == 0){
    	  $('#criterium').append('<li id="producttypecriteria"><a href="#">' + selectedText + '</a><span class="remove"><a href="#" class="remove' + dlId + '" title="' + removeCriteriaText + '">' + removeCriteriaText + '</a></span></li>');
      }

      // Add remove event on the criteria.
      $('.remove' + dlId).bind('click', function(e) {
          // Reset the global variable.
          eval(selectedValueName + ' = \'\'');

          deleteFromQuery(dlId);
          $(this).attr('href', documentUrl.GetFullString());
      });
}

// Some helper functions. move to the global package.
/**
 * Function to check an array for the existence of an object. An 'expr' is passed to
 * indicate the property which will be used to check the objects.
 *
 * @param a     Array with objects.
 * @param value The value that needs to be checked.
 * @param expr  Property of the objects that leeds to the value we need to compare with the 'value' parameter.
 *
 * @returns true or false. True when the array already contains the object. False when the array does not
 *            contain the object.
 */
function contains(a, value, expr) {
  var i = a.length;
  while (i--) {
    if (eval('a[i][\'' + expr + '\']') == value) {
      return true;
    }
  }
  return false;
}

/**
 * Function to compare two objects. It can be used to sort an array of objects. The
 * comparing is done on the 'value' property of the objects in the array.
 *
 * @param a Object 1 (must have a property 'value').
 * @param b Object 2 (must have a property 'value').
 *
 * @returns -1, 0 or 1.
 */
function compareObjects(a, b) {
  if (a['value'] < b['value']) {return -1};
  if (a['value'] > b['value']) {return 1};
  return 0;
}

/**
 *
 */
function QueryStringBuilder() {
  this.Url = '';
  this.Pairs = new Array();

  QueryStringBuilder.prototype.GetFullString = function() {
    var queryString = (this.Url.length > 0) ? this.Url + "?" : '';
    
    for(var key in this.Pairs) {
      if (escape(this.Pairs[key]) != '') {
          queryString += escape(key) + "=" + escape(this.Pairs[key]) + "&";
        }
    }
    
    return queryString.substring(0, queryString.length - 1);
  }
}

/**
 * Add value to the querystring object.
 */
function buildQuery(name,value) {
  documentUrl.Pairs[name] = value;
}

/**
 * Reset a value in the querystring object.
 */
function deleteFromQuery(name) {
  documentUrl.Pairs[name] = '';
}

/**
 * setUp the QueryStringBuilder with the initial values. (should be private)
 */
function setUpQueryStringBuilder() {
  
  var startUrl = getDocumentBaseUrl() + '';
  // Check whether the startUrl has already querystring parameters. If so add them to the
  // QueryStringBuilder.
  documentUrl.Url = startUrl.split('?')[0];

  if(typeof(startUrl.split( "?" )[1]) != "undefined"){
  qs = startUrl.split( "?" )[1].replace(/\+/g, ' ').split('&');
  $.each(qs, function(i){
    var currentArg = this.split('=');
    if(currentArg.length == 2) {
      buildQuery(unescape(currentArg[0]),unescape(currentArg[1]));
    }

  });
  }
}

function getProductDetailLink(detailLink) {
  var link = detailLink.replace("'", "''")
  
  if (documentUrl.Pairs['channel'] && documentUrl.Pairs['channel'] == 'iframe') {
    // Pass on the channel to the detaillink.
    if (link.indexOf('?') >-1) {
      link = link + '&channel=iframe';
    } else {
      link = link + '?channel=iframe';
    }   
  }
  return link;
}

