/*********************************************************************
(c) Copyright Comet Plc 1999-2007. All rights reserved.
	Cookie javascript used across whole site
	Last updated: 2008/02/15 - Stewart Orr
/********************************************************************/

var numRVPProductsToKeep = 5;
var numRVPProductsToShow = 4;

var numCompareProductsToKeep = 4;
var numCompareProductsToShow = 4;

var numCompareCategories = 5;

var cookieLifetime = 30;
var cookiePath = "/";
var prod30 = "http://www.comet.co.uk/comet/dyn_imgs/prods/prod_30/";
var tooManyCompareProductsMessage = "There are already 4 items in your comparison list. Please remove an item before attempting to add another";
var productExistsMessage = "This item is already in your comparison list";

function truncateString(str, maxlength) {
	return (str.length>maxlength) ? str.substring(0, maxlength) + "..." : str ; 
}

// added by stewart for red route mar 2009
function changeCompareLink(category,sku,off) {
	var el = gID("compare_link_" + sku);
	if (el) {
		if (!off) {
			if (gID('product_title_' + sku + "_normal")) {
				var prodname = gID('product_title_' + sku + "_normal").innerHTML;
				var proddesc = gID('product_title_' + sku + "_normal").title.replace(prodname + " - ", "");					
			} else {
				var prodname = gID('product_title_' + sku + "_featured").innerHTML;
				var proddesc = gID('product_title_' + sku + "_featured").title.replace(prodname + " - ", "");						
			}
			el.href="javascript:addToCompareAndDrawBox('" + category + "','" + sku + "', '" + prodname + "', '" + proddesc + "');";
			el.className = el.className.replace(" compared","");
			el.title = "Add this product to my compare list";
			el.innerHTML = "<span>Add to</span> Compare</a>";								 
		} else {
			el.href="javascript:deleteCompareProductAndDrawBox('" + category + "','" + sku + "');";
			if (el.className.indexOf(" compared") == -1) {
				el.className += " compared";				
			}
			el.title = "Remove this product from my compare list";
			el.innerHTML = "Added <span>to compare</span>";								 
		}
	}
}

/*
The functions in this javascript file setup and access the compareproducts and recentlyviewedproducts
cookies.
The compareproducts cookie is of the format:
category1##sku:::name:::description:::image*+*sku:::name:::description:::image*:*category2##sku:::name:::description:::image*+*sku:::name:::description:::image*:*

The recentlyviewedproducts cookie is of the format:
sku:::name:::description:::image:::packageindicator*+*sku:::name:::description:::image:::packageindicator

*/



/*
  name - name of the desired cookie
  return string containing value of specified cookie or null
  if cookie does not exist
*/

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return "nocookie";
  } else {
    begin += 2;
  }
  var end = document.cookie.indexOf(";", begin);
  if (end == -1) {
    end = dc.length;
  }
  return unescape(dc.substring(begin + prefix.length, end));
}


/*
   name - name of the cookie
   value - value of the cookie
   [expires] - expiration date of the cookie
     (defaults to end of current session)
   [path] - path for which the cookie is valid
     (defaults to path of calling document)
   [domain] - domain for which the cookie is valid
     (defaults to domain of calling document)
   [secure] - Boolean value indicating if the cookie transmission requires
     a secure transmission
   * an argument defaults when it is assigned null as a placeholder
   * a null placeholder is not required for trailing omitted arguments
*/

function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}


/*
   name - name of the cookie
   [path] - path of the cookie (must be same as path used to create cookie)
   [domain] - domain of the cookie (must be same as domain used to
     create cookie)
   path and domain default if assigned null or omitted if no explicit
     argument proceeds
*/

function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}


// date - any instance of the Date object
// * hand all instances of the Date object to this function for "repairs"

function fixDate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
    date.setTime(date.getTime() - skew);
}

/*
   sku - sku of the product
   name - name of the product
   description - short description of the product
   image - image name of the product
   category - category this product is in
   package - whether this is a package or not (yes/no)

   returns a string of the format sku:::name:::description:::image:::packageindicator
*/
function buildRVPProductString(sku,name,description,image,package) {
	var returnString = sku + ":::" + name + ":::" + description + ":::" + image + ":::" + package;
	return returnString;

}

/*
   sku - sku of the product
   name - name of the product
   description - short description of the product
   image - image name of the product
   category - category this product is in

   returns a string of the format sku:::name:::description:::image
*/
function buildCompareProductString(sku,name,description) {
	var returnString = sku + ":::" + name + ":::" + description + ":::" + sku + ".jpg";
	return returnString;
}

/*
	category - category this product is in
	productString - a string of the format sku:::name:::description:::image*+*sku:::name:::description:::image
	for this product

	returns a string of the format category##sku:::name:::description:::image*+*sku:::name:::description:::image*:*

*/
function buildCategoryString(category, productString) {

	//alert("buildCategoryString. category=" + category + "  productString=" + productString);
	var returnString = category + "##" + productString;
	//alert("buildCategoryString. returning=" + returnString);
	return returnString;

}


/*
	category - the category id whose products we want to find in the cookie string
	cookieString - the cookie string we are looking in

	returns the string that corresponds to this category
*/
function getCategoryString(category, cookieString) {

  var categoryString = category + "##";
  var begin = cookieString.indexOf(categoryString);
  if (begin == -1) {
    return "nocategory";
  }
  var end = cookieString.indexOf("*:*", begin);
  if (end == -1) {
    end = cookieString.length;
  }
  //alert("getCategoryString=" + unescape(cookieString.substring(begin, end)));

  return unescape(cookieString.substring(begin, end));
}


/*
	sku - sku of the product we are looking for
	cookieString - the cookie string we are looking in

	Its pretty safe to just search for the existance of the sku in the string. dont think we will
	get a false positive doing this
*/
function getRVPProductExists(sku, cookieString) {
	var begin = cookieString.indexOf(sku);
  if (begin == -1) {
  	return "false";
  }
  else
  {
  	return "true";
  }
}

/*
	sku - sku of the product we are looking for
	categoryString - the category we are looking in

	Its pretty safe to just search for the existance of the sku in the string. dont think we will
	get a false positive doing this
*/
function getCompareProductExists(sku, categoryString) {
	var begin = categoryString.indexOf(sku);
  if (begin == -1) {
  	return "false";
  }
  else
  {
  	return "true";
  }
}


/*
	cookieString - the RVP cookie
*/
function checkTooManyRVPProducts(cookieString) {
	var productArray = cookieString.split("*+*");
	if (productArray.length >= numRVPProductsToKeep) {
		return "true";
	}
	else
	{
		return "false";
	}

}



/*
	categoryString - the string for the category we are looking in
*/
function checkTooManyCompareProducts(categoryString) {
	var productArray = categoryString.split("*+*");
	if (productArray.length >= numCompareProductsToKeep) {
		return "true";
	}
	else
	{
		return "false";
	}

}

/*
*/
function bumpProducts(numProductsToKeep, cookieString) {
	var productArray = cookieString.split("*+*");
	var newCookieString = "";
	var count = 0;
	while ((count < productArray.length - 1) && (count < numProductsToKeep)) {
		var product = productArray[count];
		if (newCookieString == "") {
			newCookieString = product;
		}
		else {
			newCookieString = newCookieString + "*+*" + product;
		}
		count = count + 1;
	}

	return newCookieString;

}


function prependRVPProduct(newProductString, rvpCookie) {
	var newCookie = newProductString + "*+*" + rvpCookie;
	return newCookie;
}


function prependCompareProduct(categoryId, newProductString, categoryString) {

	//alert("prependCompareProduct./n  newProductString=" + newProductString + "/n  categoryString=" + categoryString);

 	// numCompareProductsToKeep holds max array size

	if (categoryString != "nocategory") {
		var categoryStringPieces = categoryString.split("##");

		if (categoryStringPieces.length > 1) {

			var categoryProducts = categoryStringPieces[1];

			// Ketan Patel - Alterations for CR421 - 15/02/2006

			//var newCategoryString = categoryId + "##" + newProductString + "*+*" + categoryProducts;

			var sortedString = sortProductString(categoryProducts, newProductString);
			var newCategoryString = categoryId + "##" + sortedString;

			// Ketan Patel - END OF Alterations for CR421
		}

		//alert("prependCompareProduct. returning=" + newCategoryString);
	}
	else
	{
		var newCategoryString = categoryId + "##" + newProductString;
	}

  return newCategoryString;

}


/*

Ketan Patel for CR421 - 15/02/2006
Created to sort order of Compare Items to improve Akamai URL caching
*/

function sortProductString(categoryProducts, newProductString) {

	var sortedString = "";

	var productList = categoryProducts.split("*+*");	// Hold list of products in current string

	productList[productList.length] = newProductString;	// Add new product to the list

	var sortedArray = productList.sort();		// Javascript function to sort arrays

	sortedString = sortedArray[0];		// Add the first item to the string

	// Loop through remaining items and add to the string

	for(i=1; i < sortedArray.length; i++) {
		sortedString = sortedString + "*+*" + sortedArray[i];
	}

	return sortedString;

}

function reAssembleCompareCookie(categoryId, newCategoryString, compareCookie) {

	//alert("reAssembleCompareCookie. newCategoryString=" + newCategoryString + "  compareCookie=" + compareCookie);


	// first split the compareCookie into categoryStrings
	var categoriesArray = compareCookie.split("*:*");
	var categoryStringReplaced = "false";


	var newCompareCookie = "";

	if (categoriesArray.length > 0) {

		for (var i = 0; i < categoriesArray.length; i++)
		{
			var thisCategoryString = categoriesArray[i];
			if (thisCategoryString != "") {

				//alert("reAssembleCompareCookie. thisCategoryString[" + i + "]=" + thisCategoryString);


				// is this the category we are replacing?
				if (thisCategoryString.indexOf(categoryId) != -1) {
					thisCategoryString = newCategoryString;
					categoryStringReplaced = "true";
				}
				if (newCompareCookie != "") {
					newCompareCookie = newCompareCookie + "*:*" + thisCategoryString;
				}
				else
				{
					newCompareCookie = thisCategoryString;
				}
			}
		}

		if (categoryStringReplaced == "false") {
			newCompareCookie = newCategoryString + "*:*" + newCompareCookie;
		}
	}

	//alert("reAssembleCompareCookie. returning=" + newCompareCookie);

	return newCompareCookie;

}



/*
   sku - sku of the product
   name - name of the product
   description - short description of the product
   image - image url of the product
   category - category this product is in
   package - whether this is a package or not

*/

function addToRecentlyViewed(sku,name,description,image,package) {

	// get the recently viewed products cookie
  var rvpCookie = getCookie("recentlyviewedproducts");
  rvpCookie = unescape(rvpCookie);

  //alert("Old cookie: " + rvpCookie);


  // make a cookie expiry date object for 'cookieLifetime' days in the future
  var cookieExpiryDate = new Date();
  cookieExpiryDate.setDate(cookieExpiryDate.getDate() + cookieLifetime);

  // if the cookie exists then parse it for the products

  if (rvpCookie != "nocookie") {

		// check if the product has already been saved
		var productExists = getRVPProductExists(sku, rvpCookie);

		//alert("productExists?: " + productExists);

		// If the product isnt already there then proceed, otherwise dont bother.
		// We dont want to move it to the top or anything
		if(productExists == "false") {

			// check if there are already 'numRVPProductsToKeep' products, if so then bump the last one off
			var tooManyProds = checkTooManyRVPProducts(rvpCookie);
			//alert("tooManyProds?: " + tooManyProds);
			if(tooManyProds == "true") {
				rvpCookie = bumpProducts(numRVPProductsToKeep - 1, rvpCookie);
				//alert("new rvpCookie: " + rvpCookie);
			}
			var newProductString = buildRVPProductString(sku,name,description,image,package);
			//alert("newProductString: " + newProductString);
			var newCookieString = prependRVPProduct(newProductString, rvpCookie);
			//alert("newCookieString: " + newCookieString);
			setCookie("recentlyviewedproducts", escape(newCookieString), cookieExpiryDate, cookiePath, null, null);
		}
  }
  else
  {

  	var newProductString = buildRVPProductString(sku,name,description,image,package);
  	//alert("newProductString: " + newProductString);
  	setCookie("recentlyviewedproducts", escape(newProductString), cookieExpiryDate, cookiePath, null, null);

  }


}

function deleteCompareProductFromCategory(sku, categoryString) {
 	var newCategoryString = "";
	if (categoryString != "nocategory") {
		var categoryStringPieces = categoryString.split("##");

		if (categoryStringPieces.length > 1) {
			newCategoryString = categoryStringPieces[0] + "##";
			var categoryProducts = categoryStringPieces[1];
			var productArray = categoryProducts.split("*+*");
			var productAddedBack = "false";

			for (var i = 0; i < productArray.length; i++) {
				var thisProduct = productArray[i];
				var productInfoArray = thisProduct.split(":::");
				if (productInfoArray[0] != sku) {
					// add it back in
					if (productAddedBack == "true") {
						newCategoryString = newCategoryString + "*+*" + thisProduct;
					} else {
						newCategoryString = newCategoryString + thisProduct;
						productAddedBack = "true";
					}
				}
			}
			if (productAddedBack == "false") {
				newCategoryString = "";
			}

		}
	} else {
		var newCategoryString = categoryString;
	}

  return newCategoryString;

}


function deleteCompareProduct(category,sku) {
	// get the compare cookie
	var compareCookie = getCookie("compareproducts");
	compareCookie = unescape(compareCookie);
	// make a cookie expiry date object for 'cookieLifetime' days in the future
	var cookieExpiryDate = new Date();
	cookieExpiryDate.setDate(cookieExpiryDate.getDate() + cookieLifetime);
	// if the cookie exists then parse it for the correct category
	if (compareCookie != "nocookie") {
		var categoryString = getCategoryString(category, compareCookie);
		//alert("categoryString=" + categoryString);
		if (categoryString != "nocategory") {
			var newCategoryString = deleteCompareProductFromCategory(sku, categoryString);
			var newCookieString = reAssembleCompareCookie(category, newCategoryString, compareCookie);
			setCookie("compareproducts", escape(newCookieString), cookieExpiryDate, cookiePath, null, null);

			changeCompareLink(category,sku,false);
		}
	}
}



/*
   sku - sku of the product
   name - name of the product
   description - short description of the product
   image - image url of the product
   category - category this product is in
   package - whether this is a package or not

*/

function addToCompare(category,sku,name,description) {
	// get the compare cookie
	var compareCookie = getCookie("compareproducts");
	compareCookie = unescape(compareCookie);
	// make a cookie expiry date object for 'cookieLifetime' days in the future
	var cookieExpiryDate = new Date();
	cookieExpiryDate.setDate(cookieExpiryDate.getDate() + cookieLifetime);

	// if the cookie exists then parse it for the correct category
	if (compareCookie != "nocookie") {

		var categoryString = getCategoryString(category, compareCookie);

		if (categoryString != "nocategory") {
			//alert("categoryString is not null");
			//alert("categoryString=" + categoryString);
			var productExists = getCompareProductExists(sku, categoryString);
			if(productExists == "false") {
				var tooManyProducts = checkTooManyCompareProducts(categoryString);
				if (tooManyProducts == "true") {
					alert(tooManyCompareProductsMessage);
				} else {
					var newProductString = buildCompareProductString(sku,name,description);
					var newCategoryString = prependCompareProduct(category,newProductString, categoryString);
					var newCookieString = reAssembleCompareCookie(category,newCategoryString, compareCookie);
					setCookie("compareproducts", escape(newCookieString), cookieExpiryDate, cookiePath, null, null);
					//var compare_selected_add = "compare_selected_" + sku;
					//var compare_notselected_add = "compare_notselected_" + sku;
					//changeDiv(compare_notselected_add,compare_selected_add);
					changeCompareLink(category,sku,true);

					//var compare_selected_starbuy_add = "compare_selected_starbuy_" + sku;
					//var compare_notselected_starbuy_add = "compare_notselected_starbuy_" + sku;
					//changeDiv(compare_notselected_starbuy_add,compare_selected_starbuy_add);

				}
			} else {
				alert(productExistsMessage);
			}
		} else {
			//alert("categoryString is null");
			var newProductString = buildCompareProductString(sku,name,description);
			var newCategoryString = prependCompareProduct(category, newProductString, "nocategory");
			var newCookieString = reAssembleCompareCookie(category, newCategoryString, compareCookie);
			setCookie("compareproducts", escape(newCookieString), cookieExpiryDate, cookiePath, null, null);
			changeCompareLink(category,sku,true);
		}
	} else {
		var newProductString = buildCompareProductString(sku,name,description);
		var newCategoryString = buildCategoryString(category, newProductString);
		setCookie("compareproducts", escape(newCategoryString), cookieExpiryDate, cookiePath, null, null);
		changeCompareLink(category,sku,true);
	}
}


function drawRecentlyViewedProductsBox(sku) {

	var recentlyViewedProductsHtml = getRecentlyViewedProductsHtml(sku);
	// replace the html in the recentlyviewedproductsbox area with the computed html
	var recentlyViewedProductsBox = document.getElementById("recentlyviewedproductsbox");
	if (recentlyViewedProductsBox && (recentlyViewedProductsHtml != "nohtml") && (recentlyViewedProductsHtml != "")) {
		recentlyViewedProductsBox.innerHTML = recentlyViewedProductsHtml;
	}
}


function drawCompareProductsBox(category) {
	var compareProductsHtml = getCompareProductsHtml(category);
	//alert(compareProductsHtml);
	// replace the html in the compareproductsbox area with the computed html
	var compareProductsBox = document.getElementById("compareproductsbox");
	if (compareProductsBox) {
		if ((compareProductsHtml != "nohtml") && (compareProductsHtml != "")) {
			compareProductsBox.style.display = 'block';
			compareProductsBox.innerHTML = compareProductsHtml;
		} else {
			compareProductsBox.style.display = 'none';
		}
	}
}


function drawMyCometLoginLink() {
  // Only process this if the page contains mycometloginlink
  if (document.getElementById("mycometloginlink")!=null) {
    var loginCookie = getCookie("userLoggedIn");
    loginCookie = unescape(loginCookie);
    var loginLinkElement = document.getElementById("mycometloginlink");
    if (loginCookie != "nocookie") {
		loginLinkElement.innerHTML = '<a href="' + secureHost + '/webapp/wcs/stores/servlet/MyCometHomePage" class="myc" title="Visit My Comet home">My Comet home</a> &ndash; <a href="javascript:Logout();" title="Logout of My Comet">logout</a>';
    } else {
      loginLinkElement.innerHTML = '<a href="Javascript:Login();" class="myc">My Comet Login</a>';
    }
  }
}


function getRecentlyViewedProductsHtml(sku) {

  var recentlyViewedProductsHtml = "";

	// get the recently viewed products cookie
  var rvpCookie = getCookie("recentlyviewedproducts");
  rvpCookie = unescape(rvpCookie);

  if (rvpCookie != "" && rvpCookie != "nocookie") {

		var productArray = rvpCookie.split("*+*");

		// check for the obscure condition when there is only one product and its the sku we are
		// currently looking at - in this case we dont want to show the recently viewed box
		if (productArray.length == 1) {
				var oneproduct = productArray[0];

				//sku:::name:::description:::image:::packageindicator
				var oneProductInfoArray = oneproduct.split(":::");
				if (oneProductInfoArray[0] == sku) {
					return "";
				}
		}

		// in all other cases

		if (productArray.length > 0) {



			recentlyViewedProductsHtml =
			"<div id='recentlyviewed'>"
			+"<span class='recentlyviewedproducts'><strong>Recently viewed products</strong></span>"
			+"<table cellpadding='0' cellspacing='0' summary='Recently viewed products'>"
			+"<thead>"
			+"	<tr>"
			+"		<th scope='col'>Product image</th><th scope='col'>Product details</th>"
			+"	</tr>"
			+"</thead>"
			+"<tbody>";

			// we may have 5 prods in the array but only want to show 4
			// so check that both conditions are met
			for (var i = 0; (i < productArray.length && i < numRVPProductsToShow); i++)
			{
				var product = productArray[i];

				//sku:::name:::description:::image:::packageindicator
				var productInfoArray = product.split(":::");

				//alert(product);
				// dont add the current product (the sku passed in) to the recently viewed products box
				if (sku != productInfoArray[0]) {
				recentlyViewedProductsHtml = recentlyViewedProductsHtml
					+"<tr>"
					+"	<td><a href='/shopcomet/product/" + productInfoArray[0] + "/" + formatDescription(productInfoArray[1]) + "'><img alt='" + productInfoArray[1] + "' src='" + prod30 + productInfoArray[3] + "' /></a></td>"
					+"	<td><strong><a href='/shopcomet/product/" + productInfoArray[0] + "/" + formatDescription(productInfoArray[1]) + "'>" + productInfoArray[1] + "</a></strong> " + productInfoArray[2] + "<span><a href='/shopcomet/product/" + productInfoArray[0] + "/" + formatDescription(productInfoArray[1]) + "' class='hideforcic' rel='nofollow'>More info</a></span></td>"
					+"</tr>";
				}



			}

			var recentlyViewedProductsHtml = recentlyViewedProductsHtml
			+"</tbody>"
			+"</table>"
			+""
			+"</div>";

		}
	}

  return recentlyViewedProductsHtml;

}


function addToRVPAndDrawBox(sku,name,description,image,package) {

	drawRecentlyViewedProductsBox(sku) ;
	addToRecentlyViewed(sku,name,description,image,package);

}

function getCompareProductsHtmlFromProductArray(category,productsArray) {

	var compareLink = "categoryId=" + category;
	var compareProductsHtml = "";
	
	//for (var i = 0; i < productsArray.length; i++) {
	for (var i = 0; i < 4; i++) {
		if (productsArray[i]) {
			var product = productsArray[i];
			//sku:::name:::description:::image
			var productInfoArray = product.split(":::");
			compareProductsHtml = compareProductsHtml
			+"<td class='cmpprd' width='25%' valign='top'>"
			+"	<div>"
			+"		<a href='/shopcomet/product/" + productInfoArray[0] + "/" + formatDescription(productInfoArray[1]) + "' title='View the " + productInfoArray[1] + " in a new window'><img alt='" + productInfoArray[1] + "' src='" + prod30 + productInfoArray[3] + "' title='" + productInfoArray[1] + " - " + productInfoArray[2] + "' /><strong>" + truncateString(productInfoArray[1],16)  + "</strong> <span class='cmpdesc'>" + truncateString(productInfoArray[2],18) + "</span></a>"
			+"		<a class='cmpremove' title='Remove the " + productInfoArray[1] + " from my compare list' href='javascript:deleteCompareProductAndDrawBox(\"" + category + "\",\"" + productInfoArray[0] + "\")'><strong>X</strong></a>"
			+"<div></td>";
			
			compareLink = compareLink + "&sku=" + productInfoArray[0];
	
			//var compare_selected_temp = "compare_selected_" + productInfoArray[0];
			//var compare_notselected_temp = "compare_notselected_" + productInfoArray[0];
	
			//var compare_selected_starbuy_temp = "compare_selected_starbuy_" + productInfoArray[0];
			//var compare_notselected_starbuy_temp = "compare_notselected_starbuy_" + productInfoArray[0];
	
			//changeDiv(compare_notselected_temp,compare_selected_temp);
			//changeDiv(compare_notselected_starbuy_temp,compare_selected_starbuy_temp);
			changeCompareLink(category,productInfoArray[0],true);
		} else {
			compareProductsHtml += "<td width='25%' width='25%' valign='middle' class='cmpempty'>select another product</td>";
		}
	}

	var compareHeader =
	"<div class='comparison' id='compareproducts'>"
	+"	<h3><span>Compare products</span></h3>"
	+"	<div class='comparisonbody'>"
	+"		<table cellpadding='0' cellspacing='5' summary='List of products to compare' border='0' width='100%'>"
	+"			<tbody>";
				compareProductsHtml = compareProductsHtml +
	"			</tbody>"
	+"		</table>"
	+"		<p class='btncompare'>You can compare up to 4 products and when you're ready, click <a href='/shopcomet/compare.do?" + compareLink + "'><strong>Compare</strong></a> Click the <strong>X</strong> to remove.</p>"
	+"  </div>";
	+"</div>";
	return (compareHeader + compareProductsHtml);

}



function getCompareProductsHtml(category) {

	// get the compare cookie
  var compareCookie = getCookie("compareproducts");
  compareCookie = unescape(compareCookie);

  // if the cookie exists then parse it for the correct category

  if (compareCookie != "nocookie") {

		var categoryString = getCategoryString(category, compareCookie);
		//alert("categoryString=" + categoryString);

		if (categoryString != "nocategory") {
			var categoryStringPieces = categoryString.split("##");

			if (categoryStringPieces.length > 1) {

				var categoryProducts = categoryStringPieces[1];
				var productsArray = categoryProducts.split("*+*");
				return getCompareProductsHtmlFromProductArray(category,productsArray);

			}
			else
			{
				return "";
			}
		}
		else
		{
			return "";
		}
	}
	else
	{
		return "";
	}

}


function addToCompareAndDrawBox(category,sku,name,description) {
	addToCompare(category,sku,name,description);
	drawCompareProductsBox(category);
}


function drawRecentlyViewedAndCompareProductsBox(category) {
	drawRecentlyViewedProductsBox('');
	drawCompareProductsBox(category);
}
function deleteCompareProductAndDrawBox(category,sku) {
	deleteCompareProduct(category,sku);
	drawCompareProductsBox(category);
}

function formatDescription(prodDesc) {
	var description = new String(prodDesc);
	description = description.replace(" ", "-");
	return description;
	
}


/**
 * The following objects represent products selected for comparison. In this
 * incarnation we have objects that can serialise to a string format for
 * storage in a cookie and can repopulate themselves from a string fragment
 * obtained fronm a cookie. The objects are easier to work with in
 * Javascript.
 *
 * @author Mark Meany
 * @version $Id: cookie.js,v 1.81 2009/11/06 15:10:42 stewart Exp $
 */

/**
 * ****************************************************************************
 *                        CompareProduct Object
 * Instances of this object represent a single product selected for comparison.
 *
 * Instances of this object can serialies themselves into a string notation that
 * is consistent with the existing cookie encoding syntax. The serialised string
 * should be escaped prior to writing to a cookie and unescaped when reading back
 * and passing to deserialise.
 * ****************************************************************************
 */

/** Simple object to hold information about a product selected for comparison. */
function CompareProduct(tSku, tName, tDescription, tImage) {
	this.sku = tSku;
	this.prodName = tName;
	this.desc = tDescription;
	this.image = tImage;
}

/** Method to serialise this CompareProduct into a string which can be stored in a cookie. */
CompareProduct.prototype.serialise = function () {
    return this.sku + ":::" + this.prodName + ":::" + this.desc + ":::" + this.image;

}

/** Method to reform a CompareProduct object from its serialised string representation as found in cookie. */
CompareProduct.prototype.deserialise = function (serialised) {
    var parts = serialised.split(":::");
    if(parts.length == 4) {
    	this.sku = parts[0];
    	this.prodName = parts[1];
    	this.desc = parts[2];
    	this.image = parts[3];
    }
}

/** Human readable form of this object. */
CompareProduct.prototype.readable = function (pad) {
    if(pad == null) {
        pad = "";
    }
    return pad + "sku   = " + this.sku      + "\n" +
           pad + "name  = " + this.prodName + "\n" +
           pad + "desc  = " + this.desc     + "\n" +
           pad + "image = " + this.image    + "\n";
}

/*
 * ****************************************************************************
 *                        CompareCategory Object
 * A category instance will hold one or more products that appear in that category.
 * As such the category has an identifier and an array of products. There are
 * utility methods for adding and removing products. The same product cannot be
 * added more than once and attempting to remove a product that is not present
 * has no ill effect.
 *
 * Instances of this object can serialies themselves into a string notation that
 * is consistent with the existing cookie encoding syntax. The serialised string
 * should be escaped prior to writing to a cookie and unescaped when reading back
 * and passing to deserialise.
 *
 * The serialisation/deserialisation delegates to product to serialise itself.
 * ****************************************************************************
 */

/** Object that represents a Category and holds all products in that category that have been selected for compare. */
function CompareCategory(tCategoryId) {
	this.categoryId = tCategoryId;
	this.products   = [];
	this.skuList    = "";
}

/** Callback method used during sort operations, compares two products. */
CompareCategory.prototype.productCompare = function (productA, productB) {
    if( productA.sku == productB.sku) {
        return 0;
    } else if (productA.sku < productB.sku) {
        return -1;
    } else {
        return 1;
    }
}

/** Method that checks to see if a particular products has already been selected. */
CompareCategory.prototype.containsProduct = function (product) {
    return (this.skuList.indexOf("," + product.sku + ",") != -1);
}

/** Method that checks to see if a particular sku has already been selected. */
CompareCategory.prototype.containsSku = function (sku) {
    return (this.skuList.indexOf("," + sku + ",") != -1);
}

/** Add a product to this category. Not added if already present or maximum exceeded. */
CompareCategory.prototype.addProduct = function (product) {
    if( !this.containsProduct(product) ) {
        if(this.products.length < numCompareProductsToKeep) {
            this.products[this.products.length] = product;
            this.products.sort(this.productCompare);
            this.skuList += "," + product.sku + ",";
            return true;
        } else {
            alert(tooManyCompareProductsMessage);
        }
    } else {
    	alert(productExistsMessage);
    }
    return false;
}

/** Remove a product from this category. */
CompareCategory.prototype.removeProduct = function (product) {
	var removed = false;
    if(this.containsProduct(product)) {
        var newProducts = [];
        var newSkuList  = "";
        for(var i=0; i<this.products.length;  i++) {
            if(this.products[i].sku != product.sku) {
                newProducts[newProducts.length] = this.products[i];
                newSkuList += "," + this.products[i].sku + ",";
                removed = true;
            }
        }
        this.products = newProducts;
        this.skuList  = newSkuList;
    }
    return removed;
}

/** Method to serialise this CompareCategory into a string which can be stored in a cookie. */
CompareCategory.prototype.serialise = function () {
    var serialised = this.categoryId + "##";
    var sep = "";
    for(var i=0; i<this.products.length; i++) {
        serialised += sep + this.products[i].serialise();
        sep = "*+*";
    }
    return serialised;
}

/** Method to reform a CompareCategory object from its serialised string representation as found in cookie. */
CompareCategory.prototype.deserialise = function (serialised) {
    var parts = serialised.split("##");
    if(parts.length == 2) {
        var catId = unescape(parts[0]);
        this.categoryId = catId;
        var prods = parts[1].split("*+*");
        for(var j=0; j<prods.length; j++) {
            var prod = new CompareProduct();
            prod.deserialise(prods[j]);
            if(prod.sku != null) {
                this.addProduct(prod);
            }
        }
    }
}

/** Human readable form of this object. */
CompareCategory.prototype.readable = function (pad) {
    if(pad == null) {
        pad = "";
    }
    var msg = pad + "Category: " + this.categoryId + "\n";
    for(var i=0; i<this.products.length; i++) {
        msg += this.products[i].readable(pad+" ");
    }
    return msg;
}

/*
 * ****************************************************************************
 *                        ComparePromotion Object
 * A promotion can span more than one category, hence instances of this object
 * have an array of categories that in turn have an array of products selected
 * for compare. There are convenience methods for adding and removing products
 * at the promotion level, these will create/remove categories as required.
 *
 * Instances of this object can serialies themselves into a string notation that
 * is consistent with the existing cookie encoding syntax. The serialised string
 * should be escaped prior to writing to a cookie and unescaped when reading back
 * and passing to deserialise.
 *
 * The serialisation/deserialisation delegates to category to serialise itself.
 *
 * At any time the contents can be viewed using javascript:alert(var.readable());
 * where var is name of variable holding the ComparePromotion object. Simply enter
 * the fragment into IE Addess bar.
 * ****************************************************************************
 */

/** Container for all products selected for comparison from a particular promotion. This is object that is serialised/deserialised to cookie. */
function ComparePromotion(tPromotionId) {
	this.promotionId = tPromotionId;
	this.categories  = [];
}

/** Find a category in this promotion. If not present then create and add it. */
ComparePromotion.prototype.findCategory = function (categoryId) {
    for(var i=0; i < this.categories.length; i++) {
        if( this.categories[i].categoryId == categoryId ) {
            return this.categories[i];
        }
    }
    var cat = new CompareCategory(categoryId);
    this.categories[this.categories.length] = cat;
    return cat;
}

/** Check if a specific product is present. */
ComparePromotion.prototype.productExists = function (promotionId, categoryId, sku) {
	if(promotionId == this.promotionId) {
	    for(var i=0; i < this.categories.length; i++) {
	        if( this.categories[i].categoryId == categoryId ) {
	            return this.categories[i].containsSku(sku);
	        }
	    }
	}
	return false;
}

/** Add a new product for comparison. If the promotion id has changed then remove all previous products and categories. */
ComparePromotion.prototype.addProduct = function (promotionId, categoryId, sku, prodName, prodDesc, prodImage) {
    if(this.promotionId != promotionId) {
        this.categories = [];
        this.promotionId = promotionId;
    }
    var product = new CompareProduct(sku, prodName, prodDesc, prodImage);
    var cat = this.findCategory(categoryId);
    return cat.addProduct(product);
}

/** Remove a product from comparison list. If the containing category ends up with no products it is also removed. */
ComparePromotion.prototype.removeProduct = function (promotionId, categoryId, sku) {
    if(this.promotionId != promotionId) {
        this.categories = [];
        this.promotionId = promotionId;
    }
    var removed = false;
    var product = new CompareProduct(sku, null, null, null);
    var cat = this.findCategory(categoryId);
    if(cat != null) {
        removed = cat.removeProduct(product);
        if(cat.products.length == 0) {
            // All products removed for this category so remove the category
            var newCategories = [];
            for(var i=0; i<this.categories.length; i++) {
                if(this.categories[i].categoryId != cat.categoryId) {
                    newCategories[newCategories.length] = this.categories[i];
                }
            }
            this.categories = newCategories;
        }
    }
    return removed;
}

/** Takes this object and builds an escaped string representation suitable for writing into a cookie. */
ComparePromotion.prototype.toString = function () {
    return escape(this.serialise());
}

/** Method to serialise this ComparePromotion into a string which can be stored in a cookie. */
ComparePromotion.prototype.serialise = function () {
    var serialised = this.promotionId + "|";
    var sep = "";
    for(var i=0; i<this.categories.length; i++) {
        serialised += sep + this.categories[i].serialise();
        sep = "*:*";
    }
    return serialised;
}

/** Method to reform a ComparePromotion object from its serialised string representation as found in cookie. */
ComparePromotion.prototype.deserialise = function (serialised) {
    var parts = serialised.split("|");
    if(parts.length == 2) {
        var promoId = parts[0];
        this.promotionId = promoId;
        this.categories  = [];
        var cats = parts[1].split("*:*");
        for(var i=0; i < cats.length; i++ ) {
            var cat = new CompareCategory();
            cat.deserialise(cats[i]);
            if(cat.categoryId != null) {
                this.categories[this.categories.length] = cat;
            }
        }
    }
}

/** Human readable form of this object. */
ComparePromotion.prototype.readable = function (pad) {
    if(pad == null) {
        pad = "";
    }
    var msg = pad + "Promotion: " + this.promotionId + "\n";
    for(var i=0; i<this.categories.length; i++) {
        msg += this.categories[i].readable(pad + " ");
    }
    return msg;
}


