var u='undefined';
var changeFlag=false;
var changeFlagComments=false;
var page='';
var iC=0;
var nnC=0;
var nnIdx=1;
var arrIndexTracker = [];

var ie=(navigator.appName=="Microsoft Internet Explorer")?1:0;
var ie4p=(ie && navigator.appVersion >= "4.0")?1:0;
var ie50=(ie && navigator.appVersion.substring(22,25) == "5.0")?1:0;

function c(bpr) {	
	eval("makeValidQuantity(i"+bpr+")");
	eval("val=document.forms['Products'].quantity[i"+bpr+"].value");
	eval("UpdateWeight(i"+bpr+",bpr,val)");
	eval("setChangeFlag(i"+bpr+")");
}

function cloose(bpr, bold_price) {	
	
	eval("makeValidQuantity(i"+bpr+")");
	eval("val=document.forms['Products'].quantity[i"+bpr+"].value");
	eval("UpdatelooseWeight(i"+bpr+",bpr,val, bold_price)");
	eval("setChangeFlag(i"+bpr+")");
}

function cGiftCards(bpr) {	
	eval("makeValidQuantityGiftCards(i"+bpr+")");
	eval("val=document.forms['Products'].quantity[i"+bpr+"].value");
	eval("UpdateWeight(i"+bpr+",bpr,val)");
	eval("setChangeFlag(i"+bpr+")");
}

function x(){
	iC++;
	if (!ie) {
		if (typeof(document.forms['Products'].weight.length) == u) {
			if (typeof(document.forms['Products'].quantity.length) != u) {nnC=nnIdx;}
		} else {
			nnIdx++;
		}
	}
}
function dec(bpr, bold_price) {eval("DecrementValue(i"+bpr+",bpr, bold_price)");eval("setChangeFlag(i"+bpr+")");}
function inc(bpr, bold_price) {eval("IncrementValue(i"+bpr+",bpr, bold_price)");eval("setChangeFlag(i"+bpr+")");}

function decloose(bpr) {eval("DecrementValueloose(i"+bpr+",bpr)");eval("setChangeFlag(i"+bpr+")");}
function incloose(bpr) {eval("IncrementValueloose(i"+bpr+",bpr)");eval("setChangeFlag(i"+bpr+")");}

function il(bpr){
	price=eval("document.forms['Products'].Price[i"+bpr+"].value");
	subs_cd=eval("document.forms['Products'].subs_cd[i"+bpr+"].value");
	best_sub=eval("document.forms['Products'].best_sub[i"+bpr+"].value");
	ilabel(bpr,price,subs_cd,escape(best_sub));
}

function sWS(sg_code) {eval("seeWholeShelf(sl"+sg_code+",sm"+sg_code+")");}
function sWS2(sg_code) {eval("seeWholeShelf2('"+sg_code+"',sm"+sg_code+")");}

function selectText(o) {o.select();}

function getCommentImageObject(idx){
	if (ie4p) {
		obj=document.forms['Products'].cImg[idx];		
	} else {
		imgidx=0;
		for (i=0;i<document.images.length;i++){
			if (document.images[i].name=="cImg"){
				if (imgidx==idx) {
					obj=document.images[i];
					break;
				}
				imgidx++;
			}
		}
	}
	return obj;
}

function openWindow(url,title,w,h,scrollbar){var scrollbars;
	W=(screen.width-w)/2;
	H=(screen.height-h)/2;
	
	if (typeof scrollbar == 'undefined') {scrollbars='no';}
	else{
	     if (scrollbar=='scrollbars') {scrollbars='yes';} else {scrollbars='no';}
	     };
	return window.open(url,title,'toolbar=no,menubar=no,hotkeys=no,location=no,scrollbars='+scrollbars+',width='+w+',height='+h+',top='+H+',left='+W);
}

function WC(){//weight converter
	newWindow=openWindow("/superstore/p/econverter.htm",'eConverter',400,280);
}

function SetLastOrderQty() {
	for (i=0;i<fQ.length;i++) {
		with (document.forms['Products']) {
			if (quantity[i].type != 'hidden') {
				quantity[i].value=fQ[i];
				if (pT[i]=='looseweight') {
					UpdateWeight(i,bpr_tpn[i].value,fQ[i]);
				}
			}
		}
	}
	setChangeFlag(0);
}

function ToFixed(value,dp){
	if (dp==0) {return Math.round(value);}
	else {
		t=10;
		for (a=1;a<dp;a++){t=t*10;}
		return Math.round(value*t)/t;
	}
}

function UpdateQuantity(idx,bpr,weight){	
	//triggered when a user edits a free-text weight box. The nearest matching quantity to the weight is calculated
	//and then the correct weight for that quantity is selected.
	quantity=Math.round(weight/avg[idx]);
	document.forms['Products'].quantity[idx].value=quantity
	UpdateWeight(idx,bpr,quantity);
	setChangeFlag(idx);
    try{arrIndexTracker.push(idx); }catch(exception){}
}


function makeValidQuantity(idx){
	var o=document.forms['Products'].quantity[idx];
	if (isNaN(o.value) || o.value<0 || trim(o.value).length==0){
		o.value=0;
	}
}

function makeValidQuantityGiftCards(idx){
	var o=document.forms['Products'].quantity[idx];
	if (isNaN(o.value) || o.value<1 || trim(o.value).length==0){
		o.value=1;
	}
}

function trim(a){
  return a.replace(/^\s+/,'').replace(/\s+$/,'')
}

function UpdateWeight(idx,bpr,quantity){
	destidx=idx-nnC;
	newWeight=ToFixed(quantity*avg[idx],2);
	document.forms['Products'].weight[destidx].value=newWeight;
}

function UpdatelooseWeight(idx,bpr,quantity, bold_price){
	destidx=idx-nnC;
	var wtt = "wt" + bpr;
	var finalprice = showMoney(quantity * bold_price);
	newWeight=ToFixed(quantity*avg[idx],2);
	document.forms['Products'].weight[destidx].value=newWeight;
	
	if (document.all) {
		document.getElementById(wtt).innerHTML = quantity + ' = ' + newWeight + ' lbs = ' + finalprice + ' estimate';
	}
}

function IncrementValue(idx,bpr, bold_price) {	
	var obj=document.forms['Products'].quantity[idx];	
	QIValue=Math.round(obj.value);	
	if (isNaN(QIValue))	{QIValue=1;} else {QIValue++;}
	obj.value=QIValue;
	if (typeof(page)==u || page!='basketConfirm') {
		if (pT[idx]=='looseweight') {			
			UpdatelooseWeight(idx,bpr,obj.value, bold_price);
		}
	}
    try{arrIndexTracker.push(idx); }catch(exception){}    
}

function IncrementValueloose(idx,bpr) {		
	var obj=document.forms['Products'].quantity[idx];	
	QIValue=(obj.value);	
	if (isNaN(QIValue))	{QIValue=1;} else {QIValue++;}
	obj.value=QIValue;
	if (typeof(page)==u || page!='basketConfirm') {
		if (pT[idx]=='looseweight') {
			UpdatelooseWeight(idx,bpr,obj.value);
		}
	}
}

function DecrementValue(idx,bpr, bold_price) {
	obj=document.forms['Products'].quantity[idx]
	QIValue=Math.round(obj.value);
	if (isNaN(QIValue))	{QIValue=0;} else {if (QIValue>0) {QIValue--;}}
	obj.value=QIValue;
	if (typeof(page)==u || page!='basketConfirm') {
		if (pT[idx]=='looseweight') {
			UpdatelooseWeight(idx,bpr,obj.value, bold_price);
		}
	}
    try{arrIndexTracker.push(idx); }catch(exception){}
}

function DecrementValueloose(idx,bpr) {
	obj=document.forms['Products'].quantity[idx]
	QIValue=(obj.value);
	if (isNaN(QIValue))	{QIValue=0;} else {if (QIValue>0) {QIValue--;}}
	if (QIValue < 0){QIValue=0;}
	obj.value=QIValue;
	if (typeof(page)==u || page!='basketConfirm') {
		if (pT[idx]=='looseweight') {
			UpdatelooseWeight(idx,bpr,obj.value);
		}
	}
}

function eC(idx) {
	product=escape(document.forms['Products'].cf_dsc[idx].value);
	comment=escape(document.forms['Products'].comments[idx].value.substr(0,30));

	// PFB 07/14/03 changed as part of Bob6 retrofit
	subcode=escape(document.forms['Products'].subs_cd[idx].value.substr(0,30));
	subtext=escape(document.forms['Products'].subtxt[idx].value.substr(0,30));
	u='/superstore/comments.htm?' + idx + '^' + product + '^' + comment + '^' + subcode + '^' + subtext;
	openWindow(u,"comments",490,330);
	
}

function UpdateComment(idx,comment) {
	changeFlagComments=true;
	
	if (comment.length!=0 && comment!=' ') {
		var quantityObj=document.forms['Products'].quantity[idx];
		if (isNaN(quantityObj.value) || quantityObj.value==0) {
			quantityObj.value=1;
			UpdateWeight(idx,'',1);
		}
	}
	if (comment.length==0) 
		comment=' ';
	document.forms['Products'].comments[idx].value = comment;
	setChangeFlag(idx);
}

function updateCatchweightComment(idx,oSelBox) {	
	var obj=document.forms['Products'];
	var objComImg=getCommentImageObject(idx);
	//set the quantity to 1 if it's zero or NaN
	if (isNaN(obj.quantity[idx].value) || obj.quantity[idx].value==0) {
		obj.quantity[idx].value=1;
	}
	removeAllWeights(idx);
	if (oSelBox.selectedIndex != 0) {
		obj.comments[idx].value+=obj.weight[idx].options[obj.weight[idx].selectedIndex].value;
	}	
	setChangeFlag(idx);
}

function removeAllWeights(idx) {
	//called when we insert a catchweight comment into the comments field
	//removes all previous weight based comments
	var obj=document.forms['Products'];
	var comment=obj.comments[idx].value;
	if (comment != null && comment.length > 0) {
		for (i=1;i<obj.weight[idx].options.length;i++){
			if (comment.indexOf(obj.weight[idx].options[i].value)!=-1) {
				comment=comment.replace(obj.weight[idx].options[i].value,'');
			}
		}
	}
	obj.comments[idx].value=comment;
}

function setChangeFlag(idx){
	if (document.forms['Products'].quantity[idx].value != document.forms['Products'].orig_qty[idx].value) {
		changeFlag=true;
	} else {
		changeFlag=false;
		for (i=0;i<iC;i++){	
			if (document.forms['Products'].quantity[i].value != document.forms['Products'].orig_qty[i].value) {
				changeFlag=true;
				break;
			}
		}		
	}
}

function setDelFavChangeFlag(n){
	if (document.forms['Products'].elements[n].checked) {
		changeFlag=true;
	} else {
		changeFlag=false;
		for (i=0;i<document.forms['Products'].length;i++){
			if (document.forms['Products'].elements[i].checked) {
				changeFlag=true;
				break;
			}
		}
	}
}

function UpdateSubs(idx,subscd,substxt) {
	document.forms['Products'].subs_cd[idx].value = subscd;
	document.forms['Products'].subtxt[idx].value = substxt;
	if (subscd=='NS' || subscd=='MC')
	{	
		var quantityObj=document.forms['Products'].quantity[idx];
		if (isNaN(quantityObj.value) || quantityObj.value==0) {
			quantityObj.value=1;
			UpdateWeight(idx,'',1);
		}
	}
}


function flagChanges(){
	//This branching is a one-off occurrence, any browser specific code
	// has to be pre-approved by the business/system analyst	
	if (ie50) {
		if (changeFlag || changeFlagComments){
		//	alert ('You have not saved the changes to your basket. \nIf you want to update your basket, please \ngo back to the previous page and update your basket.')
			alert ('The items you selected were not added to your cart. \nIf you want to make changes to your cart, please \ngo back to the previous page and update your cart.');
			return true;
		} else {
			return false;
		}
	}
	else{
		if ((changeFlag || changeFlagComments) && confirm ('You have changed the quantities of some products \nor entered a note to your personal shopper.\nClick \'OK\' to update your basket,\nor \'Cancel\' to continue without updating')){			
			document.forms['Products'].submit();
			return true;
		} else {
			return false;
		}
	}
}

function ilabel(bpr,price,subs_cd,best_sub) {
	for (i=1;i<arguments.length;i++) {
		if (arguments[i].length==0) {arguments[i]='\'\'';}
	}
	if (subs_cd=="''") {subs_cd='';}
	if (best_sub=="''") {best_sub='';}
	eval("note=escape(document.forms['Products'].comments[i"+bpr+"].value)")
	var sURL = '/superstore/gen/ilabel/IL'+bpr+'.htm?price='+price+'&note='+note+'&subs_cd='+subs_cd+'&best_sub='+best_sub;
	openWindow(sURL,"ilabel",650,450,'scrollbars');
}


function PromoPopup(bpr,type) {
	var sURL = '/superstore/promo_window.asp?prodId='+bpr;
	if (typeof(type) != u) {sURL += '&ptype='+type;}
	openWindow(sURL,"promotion",650,350,'scrollbars');
}

function getCookieValue(name) {
	//not a very good extractor, but it does the job.
	var c=document.cookie;
	var ia=c.indexOf(name);
	var ib=1+c.indexOf('=',ia);
	var ic=c.indexOf(';',ia);
	return c.substring(ib,ic);	
}

/*
  This is similar getCookieValue but it uses regular expression to address some cases not handled by getCookieValue.
  Note: getCookieValue uses indexOf which returns the first instance of the string to be searched.
        Given the following in document.cookie:
        Cookie1=brandid=1&param1=true&param2=PHX&param3=shop%2Esafeway%2Ecom; Cookie2=shop%2Esafeway%2Ecom; brandid=1;
        getCookieValue("brandid") will return the value "1&param1=true&param2=PHX&param3=shop%2Esafeway%2Ecom"
        getCookieValue("brandid") is expected to get the value of "1", not "1&param1=true&param2=PHX&param3=shop%2Esafeway%2Ecom".
*/
function retrieveCookie(cookieName) {
    var cookieValue = null;
    
    if ( document.cookie.length > 0 ) {
        var extractExp = new RegExp("(?:^|;)\\s*" + cookieName + "=(.*?)(?:$|;)");
        var match = document.cookie.match(extractExp);

        if ( match != null ) {
        	cookieValue = unescape(match[1]);
        }
    }
    
    return cookieValue;
}

function TestLoginStatus(){

	if (retrieveCookie("CID") > 0 && retrieveCookie("CID") != '123456789' && retrieveCookie("BranchNumber") > 0 && retrieveCookie("Authentication") > 0 ){
		return true;
	}	
}

/* Copied from functionlib.js. Update this function if the original function is updated. */
function getParameter (queryString, parameterName) {

	// Add '=' to the parameter name (i.e. parameterName=value)
	var parameterName = parameterName + '=';
	if (queryString.length > 0) {
	
		// Find the beginning of the string
		begin = queryString.indexOf(parameterName);
		
		// If the parameter name is not found, skip it, otherwise return the value
		if (begin != -1) {
		
			// Add the length (integer) to the beginning
			begin += parameterName.length;
			
			// Multiple parameters are separated by the "&" sign
			end = queryString.indexOf('&', begin);
			if (end == -1) {
				end = queryString.length;
			}
			// Return the string
			return unescape(queryString.substring(begin, end));
		}
	
	// Return "null" if no parameter has been found
	return "null";
	}
}


function LoadShelf(mainUrl,leftUrl) {
	top.frames['main'].location.href='/superstore/shelf.asp?shelfId='+mainUrl;
	if (arguments.length >1) {
		top.frames['navbar'].location.href=leftUrl;
	}
}

function seeWholeShelf2(leftUrl,mainUrl) {
	if (top.frames.length < 6) {
		top.location = '/superstore/default.asp?page=d&navURL=/Dnet/Shelves.aspx?ID=' + leftUrl.substring(0,leftUrl.length - 2) + '&mainURL=' + mainUrl;
	}	
}

function seeWholeShelf(leftUrl,mainUrl) {

	if (top.frames.length < 6) {
		top.location = '/superstore/default.asp?page=d&navURL=' + leftUrl + '&mainURL=' + mainUrl;
	}
	else {
		if (mainUrl.length>0) {
			top.frames['main'].location.href=mainUrl;
		}
		expressShopper=false;
		f=top.frames['topleft'];
		if (typeof(f)!=u && typeof(f.isExpressShopper!=u) && f.isExpressShopper=='yes'){
			expressShopper=true;
		}
		
		favourites=false;
		if (typeof(isFavourites) != u) {
			favourites=true;
		}

		if (leftUrl=='NOLOAD' || expressShopper || favourites) {
			//do nothing
		} else {
			x=leftUrl.indexOf('//');
			if (x>0) {
				leftUrl=leftUrl.substring(0,x+1)+getCookieValue('BranchNumber')+leftUrl.substring(x+1,leftUrl.length-1);
			}
			if (typeof(top.frames['navbar'])!=u){
				top.frames['navbar'].location.replace(leftUrl);
			}
		}
	}
}

function SubmitPromo()
 { 	
	if( typeof(document.forms['Products']) != 'undefined' )
	{
	    if (changeFlag || changeFlagComments)
	    {	    
		    changeFlag=false;
		    changeFlagComments=false;

            var oProdQty = document.forms['Products'].quantity;
            var oProducts = document.forms['Products'].bpr_tpn;
            var oProdPrice =  document.forms['Products'].Price;
            
            try {
                // Process cart events for SiteCatalyst.
                processCartEvents (oProducts, oProdQty, oProdPrice, true);
           } catch (exception) {
                // Catch and suppress any errors.
           } finally {
                oProdQty = null; oProducts = null; oProdPrice = null;
           }            

		    document.forms['Products'].submit();
	    }
	    else { alert('You did not add any products to your basket.\nClick \'OK\' to proceed'); }
	}
 }

function displayExtProdDetails(productNumber, desc, sPrice, bHasImage, promotion)
{	
	var n = Math.random() + ""; 
	var nr = n * 10000000000000;
	var sASP = "/dnet/RichProductInformation.aspx?promo_window=1&bpn="  + productNumber + "&nr=" + nr ;
	var sWindow = "ExtendedProductInformation"
	document.getElementsByName('nr')[0].value = nr;
	document.getElementsByName('bpn')[0].value = productNumber;
	var newWindow = window.open( sASP, sWindow, 'resizable=yes,toolbar=no,menubar=no,hotkeys=no,location=no,scrollbars=yes,width=700,height=450,left=250,top=210');
	newWindow.focus();

}

function displayProdImage(productNumber, desc, sPrice, bHasImage, promotion)
{
	var n = Math.random() + ""; 
	var nr = n * 10000000000000;
	var sASP = "/dnet/RichProductInformation.aspx?promo_window=1&bpn="  + productNumber + "&nr=" + nr ;
	var sWindow = "ProductImage";
	document.getElementsByName('nr')[0].value = nr;
	document.getElementsByName('bpn')[0].value = productNumber;
	var newWindow = window.open( sASP, sWindow, 'resizable=yes,toolbar=no,menubar=no,hotkeys=no,location=no,scrollbars=yes,width=700,height=500,left=250,top=210');
	newWindow.focus();
}

function DeferredRender(pageNumber,startIndex,endIndex)
{
  pList.RenderInnerDivs(pageNumber,startIndex,endIndex);
}
function RenderPage(pageNumber)
{
    if ((changeFlag || changeFlagComments) && confirm ('You have changed the quantities of some products \nor entered a note to your personal shopper.\nClick \'OK\' to update your basket,\nor \'Cancel\' to continue without updating')){			
			document.forms['Products'].submit();
			changeFlag = false;
			changeFlagComments = false;
			return true;
	} else 
	{
       
       var maxRendered = (pList.MaxPageRendered + 1) * pList.pageSize;
       if (pList.mode == "search")
       {      
         wipeQuantityBox(0,maxRendered);
       }
       changeFlag = false;
       changeFlagComments = false;
       pList.Navigate(pageNumber - 1);
       
    }
}

function GenerateAnchor(href,target,text,formattingtext)
{
  var doubleQuote = '"';
  var openTag = '<a href='  + doubleQuote + href + doubleQuote + ' class=' + doubleQuote+ 'searchLinkUnderlineBold' + doubleQuote+ ' target=' + doubleQuote + target + doubleQuote  +">";
  return openTag + formattingtext+" \""+text + "\".</a>";
}
function Redirect(lframe,mframe,target,suggestion,formattingtext)
{
   return "<a href='#' " +  "onclick=\"javascript:loadFrames('" + mframe + "','" + lframe + "')\"" + ">" + formattingtext+" \""+ suggestion+"\"?"+"</a>";

}
function ShowSuggestedTerm(action,suggestion,maskText,list,frameName)
{
   var divSuggestion = new getObj("divsuggestion");
   divSuggestion.obj.className = "boldtext";
   var mframe ="/superstore/search.asp?search="+escape(suggestion);
   var lframe =  '/Dnet/Search.aspx?search=' + escape(suggestion);
   switch(action)
   {
      case "1":
          lframe = lframe +'&list=' +escape(list);
	      divSuggestion.obj.innerHTML = Redirect(lframe,mframe,frameName,suggestion,"Did you mean");
          break;
      case "2":
         lframe = lframe +'&list=' +escape(list);
         divSuggestion.obj.innerHTML =  Redirect(lframe,mframe,frameName,suggestion,"Would you like to see");
         break;
      case "3":
          divSuggestion.obj.innerHTML = GenerateAnchor(suggestion,frameName,maskText,"Click here for");
          break;  
      case "4":
          divSuggestion.obj.innerHTML = GenerateAnchor(suggestion,frameName,maskText,"Click here for");
          break;
      default:
             divSuggestion.style.className = "hide";       
      
   }
}
/* Product Rendering logic */
function getObj(name)
{
    if (document.getElementById)
    {
        this.obj = document.getElementById(name);
        this.style = document.getElementById(name).style;
    }
    else if (document.all)
    {
        this.obj = document.all[name];
        this.style = document.all[name].style;
    }
    else if (document.layers)
    {
        this.obj = document.layers[name];
        this.style = document.layers[name];
    }
}
function wipeQuantityBox(startIndex,endIndex)
{
   for(ind=startIndex;ind<endIndex; ind++)
	  {
		if(typeof(document.forms['Products'].quantity[ind])!='undefined')
		{
			document.forms['Products'].quantity[ind].value = "0";
		}		
	  }
      
}
function ProductList(productCount, size, paginationFlag,mode)
{
    //Private members
    var currentPage = 0;
    // public methods  
    var enablePagination = paginationFlag;
    this.Navigate = ShowPage;

    this.Render = Render;
    this.First = RenderFirstPage;
    this.Concat = Concat;
    this.Add = Add;
    this.PreRender = PreRender;
    this.RenderProducts = RenderProducts;
    this.PostRender = PostRender;
    // public properties
    this.ProductDivPrefix = "DivProducts-";
    this.products = new Array(productCount);
    this.pageSize = size;
    this.mode = mode;
    this.Count = productCount;
    this.PageCount =  - 1;
    this.MaxPageRendered = 0;
    this.InnerDivCount = 10;
    //compositions and references
    // this.ProductsDivId = "DivProducts";
   
    this.reset = resetLinks;
    this.RenderProductsWithoutPagination =  RenderProductsWithoutPagination;
    this.RenderProductsPage = RenderProductsPage;
    
    this.GetInnerHtml = GetInnerHtml;
    this.RenderInnerDivs = RenderInnerDivs;
    this.ShowAll = ShowAllPages;
 
    // The function RenderInnerDivs is called from the settime method
    // It renders the product in the second innerDiv.
    // the index is 1
    function RenderInnerDivs(pageNumber,startIndex,endIndex)
    {     
       var html = this.GetInnerHtml(startIndex,endIndex)
       var innerProductdiv = new getObj(this.ProductDivPrefix + pageNumber + "-" + "1");
       innerProductdiv.obj.innerHTML = html;   
       AddHiddenField();
         
    }
    
    function ShowAllPages()
    {
      //this.MaxPageRendered
      
      var pageCount = Math.ceil(productCount / size);      
      for (iCount = this.MaxPageRendered; iCount<pageCount; iCount++)
      {
           this.RenderProductsPage(iCount,true);
      }
      // Enable All divs
      for (iCount=0; iCount<pageCount; iCount++)
      {
          var productdiv = new getObj(this.ProductDivPrefix + iCount);
          productdiv.obj.className = "show";
      }
    }
    function resetLinks(pageNumber)
    {
        if (enablePagination == false)
        {
            return ;
        }
        var maxPages = Math.ceil(this.products.length / this.pageSize);
        for (i = 1; i <= maxPages; i++)
        {
            var cName = 'clickable';
            var href = "Javascript:RenderPage('" + i + "')";
            var disabledFlag = false;
            if (i == pageNumber)
            {
                cName = 'notclickable';
                href = '#';
                disabledFlag = true;
            }
            var topNav = new getObj("TopPage-" + i);
            topNav.obj.className = cName;
            topNav.obj.onclick = href;
            topNav.obj.disabled = disabledFlag;
            topNav.obj.href = href;
            var BottomNav = new getObj("BottomPage-" + i);
            BottomNav.obj.className = cName;
            BottomNav.obj.onclick = href;
            BottomNav.obj.href = href;
            BottomNav.obj.disabled = disabledFlag;
        }

    }
    function ShowPage(pageNumber)
    {
        currentPage = pageNumber;
        this.Render();

    }
    function Add(value)
    {
        this.products[this.Count] = value;
        this.Count = this.Count + 1;
    }
    function Concat(index, value)
    {

        if (typeof(this.products[index]) == "undefined")
        {
            this.products[index] = value;
        }
        else
        {
            var currentValue = this.products[index];
            this.products[index] = currentValue.concat(value);
        }

    }
    function Render()
    {
        
        this.PreRender();
        this.RenderProducts();
        this.PostRender();
    }
    ///The function prerender hides all the outer Product divs.
    function PreRender()
    {
       for (i = 0; i <= this.MaxPageRendered; i++)
        {
            var productdiv = new getObj(this.ProductDivPrefix + i);
            productdiv.obj.className = "hide";
        }
    }
    // The function RenderProducts is the main function that has the logic to either render the products or just 
    // show an outer Div. In the case when the enablePagination is false it calls the RenderProductsWithoutPagination to render the 
    // products.
    
    // if the page to be shown in less than the maxPage rendered, then it just shows the page to render.
    
    //When the user skips pages, it renders the inbetween pages
    
    
    function RenderProducts()
    {  
        var isFirstTime = false;
        if (enablePagination == false)
        {
            var endIndex = this.products.length;
            this.RenderProductsWithoutPagination(endIndex);
            AddHiddenField();
            return ;
        }
        if (currentPage == 0 && this.MaxPageRendered == 0)
        {
            isFirstTime = true;
        }

        //Check to see if the page is already rendered    
        if ((currentPage <= this.MaxPageRendered) && (!isFirstTime))
        {
            for (i = 0; i <= this.MaxPageRendered; i++)
            {
                var productdiv = new getObj(this.ProductDivPrefix + i);
                productdiv.obj.className = "hide";
            }
            var productdiv = new getObj(this.ProductDivPrefix + currentPage);
            productdiv.obj.className = "show";
        }
        else
        {   // Is the user skipping the pages?
            var pageToRender = currentPage;
            if (pageToRender > (this.MaxPageRendered + 1)) 
            {   
                // The user is skipping pages
                for (page = this.MaxPageRendered + 1; page <= currentPage; page++)
                {
                  this.RenderProductsPage(page,true);
                }
                AddHiddenField();
            }
            else 
            {
                this.RenderProductsPage(currentPage,false);
            }
        }


    }
    // The function RenderProductsPage will render all the products (in each page)
    // on the current page in oneshot when RenderAll is true and
    // will defer the rendering of products when RenderAll is false
    
    // If the # of products on the current page is < 10.. it renders it in one shot
    
    function RenderProductsPage(pageNumber,RenderAll)
    {
        var startIndex = pageNumber * this.pageSize;
        var tempIndex = parseInt(startIndex) + parseInt(this.pageSize);
        var len = this.products.length;
        var endIndex = (tempIndex > len ? len : tempIndex);
        var productsRendered = endIndex;
        var producthtml = '';
        var count = 0;
        var firstDivCount = ( this.InnerDivCount > endIndex ? endIndex : this.InnerDivCount);
        if (endIndex < startIndex + 2) 
        {
           var html = this.GetInnerHtml(startIndex,endIndex)
           var innerProductdiv = new getObj(this.ProductDivPrefix + pageNumber + "-" + 0);
           count = count + 1;
           innerProductdiv.obj.innerHTML = html;
           AddHiddenField();
          
        }
        else
        {  
           
            if (RenderAll)
            {
				var html = this.GetInnerHtml(startIndex,endIndex)
				var innerProductdiv = new getObj(this.ProductDivPrefix + pageNumber + "-" + 0);
				innerProductdiv.obj.innerHTML = html;
            } 
            else
            {
				var html = this.GetInnerHtml(startIndex,startIndex+2)
				var innerProductdiv = new getObj(this.ProductDivPrefix + pageNumber + "-" + 0);
				innerProductdiv.obj.innerHTML = html;
				var innerDivIndex = startIndex+2;
				setTimeout('DeferredRender('+ pageNumber + ',' + innerDivIndex +',' + endIndex + ')',1);	            
            }
        }
        
    }
    /// function GetInnerHtml take the startInd, end Index as parameters and 
    //  return the productHTML
    function GetInnerHtml(startIndex,endIndex)
    {
		var producthtml = '';
		for (index = startIndex; index < endIndex; index++)
        {
            var toEval = this.products[index];
            var evalArray = toEval.split("/**/");
            for (i = 0; i < evalArray.length; i++)
            {
                producthtml = producthtml.concat(eval(evalArray[i]));
            }
        }
        return producthtml;
    
    }
    /// The function PostRender Shows the current product div
    /// sets the max page rendered, if the current page is the 
    /// highest page rendered
    function PostRender()
    {
        // Show the selected div
        var productdiv = new getObj(this.ProductDivPrefix + currentPage);
        productdiv.obj.className = "show";
        if (parseInt(this.MaxPageRendered) < parseInt(currentPage))
        {
            this.MaxPageRendered = currentPage;
        }

        this.reset((currentPage + 1));      
    }
    // The function RenderProductsWithoutPagination renders the first 10
    // products in the first innerdiv and then differs the rendering of the 
    // remaining products. 
    
    function RenderProductsWithoutPagination(endIndex)
    {
        var productdiv = new getObj(this.ProductDivPrefix + currentPage);
        productdiv.obj.className = "show";
        var producthtml = '';
        var firstDivProductCount = ( endIndex > 10 ? 10 : endIndex);
        for (index = 0; index < firstDivProductCount; index++)
        {

            var toEval = this.products[index];
            var evalArray = toEval.split("/**/");
            for (i = 0; i < evalArray.length; i++)
            {
                producthtml = producthtml.concat(eval(evalArray[i]));
            }
        }
      
        var innerProductdiv = new getObj(this.ProductDivPrefix + 0+"-" + 0);
            innerProductdiv.obj.innerHTML = producthtml;
            producthtml = '';
            setTimeout('DeferredRender('+ 0 + ',' + 10 +',' + endIndex +  ')',1);
		
    }
    // AddHiddenField is Helper function to fix the index bug in Firefox.
    // in our case the index in firefox is offset by 1. Add 15th product and the 
    // 14 product gets added.
    function AddHiddenField()
    {
        var ref = document.getElementById("HiddenFields");
        var temp = ref.innerHTML;
        ref.innerHTML = "";
        ref.innerHTML = temp;
    }
 
    function RenderFirstPage()
    {
        currentPage = 0;
        if (this.Count > 0)
        {
            this.Render();
        }
	    var bottomDivRef = new getObj("DivBottomNavigation");
        bottomDivRef.obj.className = "show";
    }
}

/*-----------------------------------------------------------------------------------------------
*   Compare old and new values of  product quantities.
*   Trigger scOpen, scAdd, and scRemove  based on quantity change.
*-----------------------------------------------------------------------------------------------
*/
function processCartEvents(oProductID, oProdQuantity, oProdPrice, isMultiple) {
    var iSize;
    var fProdPrice;    
    var iDefaultValue, iCurrInputValue, iQuantity, iPriceIdx;
    var iIncCount = 0, iDecCount = 0;
    var arrIncProdQty = [], arrDecProdQty = [];
    var arrProductID = [], arrProdQuantity = [], arrProdPrice = [];

    try {
        if (isMultiple) {
            arrProductID = oProductID; arrProdQuantity = oProdQuantity; arrProdPrice = oProdPrice;
            arrIndexTracker = arrIndexTracker.removeDuplicates();
        } else {
            arrProductID[0] = oProductID; arrProdQuantity[0] = oProdQuantity; arrProdPrice[0] = oProdPrice;
            arrIndexTracker = []; arrIndexTracker.push(0);
        }

        iSize  = arrIndexTracker.length;

        for(var iCount = 0, iIdx = 0; iCount<iSize; iCount++) {
            iIdx = arrIndexTracker[iCount];
            iCurrInputValue = arrProdQuantity[iIdx].value;
            iDefaultValue = arrProdQuantity[iIdx].defaultValue;        

            if (iCurrInputValue != iDefaultValue) {
                if (iCurrInputValue > iDefaultValue) {
                    // Remove $ sign from the price if there is one.
                    (arrProdPrice[iIdx].value.indexOf("$")>=0) ? iPriceIdx = 1 : iPriceIdx = 0;
                    fProdPrice = arrProdPrice[iIdx].value.substring(iPriceIdx, arrProdPrice[iIdx].value.length);
                    iQuantity = iCurrInputValue-iDefaultValue;

                    // Track higher quantity.
                    arrIncProdQty[iIncCount] = ";" + arrProductID[iIdx].value + ";;;event15=" + iQuantity + "|event16=" + (fProdPrice*iQuantity);
                    iIncCount++;
                } else {
                    // Track lower quantity.
                    arrDecProdQty[iDecCount] = arrProductID[iIdx].value;  
                    iDecCount++;
                }
            }
        } 

        arrIndexTracker = [];

        if (iIncCount > 0) {
            s.channel = "homegrocerydelivery"; 
            s.prop3 = "shoppingcart";
            s.linkTrackVars = "products,events"; 

            // Track Cart Opens and/or Cart Additions, Potential Revenue and Potential Units for items added to the cart.
            s.linkTrackEvents = "scAdd,event15,event16"; 
            //(iIncCount > 1) ? s.pageName = "additems" : s.pageName = "additem";
			s.pageName = "additem";
            s.products = arrIncProdQty.join(',');   // comma delimited

            if (getParameter(retrieveCookie('GWCK'), 'bkct') == 0) {
                // Track only the first Cart Open using serialization code.
                s.events = "scOpen:" + createSCSerialCode() + ",scAdd,event15,event16";
            } else {
                s.events = "scAdd,event15,event16";
            }

            var s_code =s.t();
            if (s_code) document.write(s_code);
            s.pageName = "";
        }

        if (iDecCount > 0) {
            s.channel = "homegrocerydelivery"; 
            s.prop3 = "shoppingcart"; 
            s.linkTrackVars = "products,events"; 

            // Track Cart Removals for items removed from the cart.
            s.linkTrackEvents = "scRemove"; 
            s.events="scRemove";
            //(iDecCount > 1) ? s.pageName = "removeitems" : s.pageName = "removeitem";
			s.pageName = "removeitem";
            s.products = ";" + arrDecProdQty.join(';');

            var s_code =s.t();
            if (s_code) document.write(s_code);
        }     
    } catch (exception) {
        // Catch and suppress errors.
    }
}

/*----------------------------------------------------------------------------------------------------------------------------
*   Returns a serialization code (max of 20 characters). E.g. 21474836477232599976
*   Serialization code is customer ID concat with customer's last order date (in milliseconds).
*-----------------------------------------------------------------------------------------------------------------------------
*/
function createSCSerialCode() {
    var dtLastOrderDate;
    var strCustID;
    var strSerialCode = new String;

    // Retrieve customer's ID. Zero pad Cust ID to fix length to 10 characters.
    strCustID = padString(retrieveCookie('CID'), "0", 10, 1);

    // Retrieve customer's last order date. Remove "+" from the string. No padding needed.
    dtLastOrderDate = new Date(getParameter(retrieveCookie('GWCK'), 'LastOrderDate').replace(/\+/g," "));    

    if (strCustID != null && dtLastOrderDate != null) {
        strSerialCode = strCustID + dtLastOrderDate.getTime();

        if (strSerialCode.length > 20) {
            //  Remove last millisecond digit(s) if more than 20 chars.
            strSerialCode = strSerialCode.substring(0,20);
        }        
        return strSerialCode;
    } else {
        return "";
    }
}

/*------------------------------------------------------------------------------------------------------
*   Returns the string with a substring padded on the left, right or both sides.
*-------------------------------------------------------------------------------------------------------
*/
function padString(strInput, strPad, iLen, iType) {
    var PAD_LEFT = 1;
    var PAD_RIGHT = 2;
    var PAD_BOTH = 3;

    if (typeof(iLen) == "undefined") { var iLen = 0; }
    if (typeof(strPad) == "undefined") { var strPad = ' '; }
    if (typeof(iType) == "undefined") { var iType = PAD_RIGHT; }

    if (iLen + 1 >= strInput.length) {
        switch (iType) {
            case PAD_LEFT:
                strInput = Array(iLen + 1 - strInput.length).join(strPad) + strInput;
                break;
            case PAD_BOTH:
                var right = Math.ceil((padlen = iLen- strInput.length) / 2);
                var left = padlen - right;
                strInput = Array(left+1).join(strPad) + strInput + Array(right+1).join(strPad);
                break;
            default:
                strInput = strInput + Array(iLen + 1 - strInput.length).join(strPad);
            break;
        }
    }

    return strInput;
}

// Makes the array unique by removing duplicates.
Array.prototype.removeDuplicates = function () {
	var r = new Array();
	o:for(var i = 0, n = this.length; i < n; i++)
	{
		for(var x = 0, y = r.length; x < y; x++)
		{
			if(r[x]==this[i])
			{
				continue o;
			}
		}
		r[r.length] = this[i];
	}
	return r;
}

