var defaultSort, defaultContentsFormat, contentsFormat, tableWidth, numColumns, numPerPage, numPages, contentsElements, showDefaultSort,
    detailedSortInfo, showPagingModes, viewAll, sortBy, sortHighLow, pageLinkPrefix, rowpad, columnpad, storename, columnSeparatorColor,
    rowSeparatorColor, listModeBG1, listModeBG2, sortLinkSeparator, modeLinkSeparator, pageLinkSeparator, globalPageNum, globalViewallthistime,
    currentItem, currentItemImage, numArrowDivs, showListMode, addToCartImage, showBrandSort, strikePrice, showWrapMode, showQuantity, listModeShowImages,youSaveText,defaultsorttxt;
var pageItems = new Array();
var oldSortBy = "";
function myPaging(id, code, name, img, price, saleprice, options, abstr, orderable, brand, mappricing,psave) {
	if (!window.items) window.items = new Array();
	this.id=id.toLowerCase();
	this.code=code;
	this.name=name;
	this.img=img;
	this.price=round_decimals(price,2);
	this.saleprice=round_decimals(saleprice,2);
	if(saleprice) this.useprice=round_decimals(saleprice,2); else this.useprice=round_decimals(price,2);
	this.options=options;
	this.abstr=abstr;
	this.orderable=orderable;
	this.brand=brand;
	this.mappricing=mappricing;
	this.psave=psave;
	this.sortby="name";
	this.defaultsort=window.items.length;
	window.items[window.items.length] = this;
}
function round_decimals(original_number, decimals) {
    var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    return pad_with_zeros(result3, decimals)
}
function pad_with_zeros(rounded_value, decimal_places) {
    var value_string = rounded_value.toString()
    var decimal_location = value_string.indexOf(".")
    if (decimal_location == -1) {
        decimal_part_length = 0
        value_string += decimal_places > 0 ? "." : ""
    }
    else {
        decimal_part_length = value_string.length - decimal_location - 1
    }
    var pad_total = decimal_places - decimal_part_length
    if (pad_total > 0) {
        for (var counter = 1; counter <= pad_total; counter++) 
            value_string += "0"
        }
    return value_string
}
function FIND(item) {
	if (document.getElementById) return(document.getElementById(item));
	if (document.all) return(document.all[item]);
	return(false);
};
function pagingSegment(theArray,pageNum) {
	var newArray = new Array();
	for(i=(pageNum-1)*numPerPage; i<pageNum*numPerPage; i++) {
		newArray[i - (pageNum-1)*numPerPage] = theArray[i];
	}
	return newArray;
};
function sortArray(theArray, loBound, hiBound){
	var pivot, loSwap, hiSwap, temp;
	if (hiBound - loBound == 1)
	{
		if (theArray[loBound].sortby > theArray[hiBound].sortby)
		{
			temp = theArray[loBound];
			theArray[loBound] = theArray[hiBound];
			theArray[hiBound] = temp;
		}
		return;
	}
	pivot = theArray[parseInt((loBound + hiBound) / 2)];
	theArray[parseInt((loBound + hiBound) / 2)] = theArray[loBound];
	theArray[loBound] = pivot;
	loSwap = loBound + 1;
	hiSwap = hiBound;
	do {
		while (loSwap <= hiSwap && theArray[loSwap].sortby <= pivot.sortby)
			loSwap++;
		while (theArray[hiSwap].sortby > pivot.sortby)
			hiSwap--;
		if (loSwap < hiSwap)
		{
			temp = theArray[loSwap];
			theArray[loSwap] = theArray[hiSwap];
			theArray[hiSwap] = temp;
		}
	} while (loSwap < hiSwap);
	theArray[loBound] = theArray[hiSwap];
	theArray[hiSwap] = pivot;

	if (loBound < hiSwap - 1)
		sortArray(theArray, loBound, hiSwap - 1);
	if (hiSwap + 1 < hiBound)
		sortArray(theArray, hiSwap + 1, hiBound);
};
function changeClass(which,theclass) {
	which.className = theclass;	
}
function writePageLinks( viewallThisTime, pageNum) {
	if(numPages > 1) {
		var pageLinks = "<span id=pagelinks>" + pageLinkPrefix;
		for(i=1; i<=numPages; i++) {
			if(i == pageNum && !viewallThisTime)
				pageLinks += "<span class=chosen>" + i + "</span>";
			else
				pageLinks += "<a href=#top onclick=javascript:writePage(" + i + ",false)>" + i + "</a>";
			if(i % 18 == 0)
				pageLinks += "<br>";
			else
		        	if(i < numPages)
		        		pageLinks += "<span class=sep>" + pageLinkSeparator + "</span>";
		}
		if(viewAll) {
			pageLinks += "<span class=sep>" + pageLinkSeparator + "</span>";
			if(viewallThisTime)
				pageLinks += "<span class=chosen>View All</span>";
			else
				pageLinks += "<a href=#top onclick=javascript:changeSortAndPage(sortBy,false,0,true)>View All</a>";
		}
		pageLinks += "</span>";
		var thePageDiv = FIND("pagelinks");
		if(thePageDiv) thePageDiv.innerHTML = pageLinks;
		thePageDiv = FIND("pagelinks2");
		if(thePageDiv) thePageDiv.innerHTML = pageLinks;
	}
};
function writeItemXofX(viewallthistime,pageNum) {
	var currentItemLow = ((pageNum - 1) * numPerPage + 1);
	var currentItemHigh = pageNum * numPerPage;
	var numItems = window.items.length;
	if((currentItemLow <= numItems) && (numItems <= currentItemHigh)) {
		currentItemHigh = numItems;
	}
	var theString = "<span class=itemof>";
	if(currentItemLow == currentItemHigh) {
		theString += "showing product " + currentItemLow + " of " + numItems ;
	} else if(viewallthistime) {
		theString += "showing products 1-" + numItems + " of " + numItems ;
	} else {
		theString += "showing products " + currentItemLow + "-" + currentItemHigh + " of " + numItems ;
	}
	theString += "</span>";
	var theItemDiv = FIND("itemof");
	if(theItemDiv) theItemDiv.innerHTML = theString;
	theItemDiv = FIND("itemof2");
	if(theItemDiv) theItemDiv.innerHTML = theString;
};
function writePageXofX(viewallthistime,pageNum) {
	var localContent = "<span class=pageof>";
	if(viewallthistime)
		localContent += "Viewing all items";
	else
		localContent += "Displaying Page " + pageNum + " of " + numPages;
	if(detailedSortInfo) {
		if(sortBy == "default")
			localContent += " (default sort)";
		else {
		//	localContent += " <span class=detailedsortinfo>(sorted by " + sortBy;
		//	if(sortHighLow) localContent += " high to low)"; else localContent += " low to high)</span>";
		localContent += "</span>";
		}
	}
	localContent += "</span>";
	var pageofDiv = FIND("pageof");
	if(pageofDiv) pageofDiv.innerHTML = localContent;
	pageofDiv = FIND("pageof2");
	if(pageofDiv) pageofDiv.innerHTML = localContent;
};
function writeUpDownArrow(divname) {
	if(divname) {
		localContent = "";
		if(sortHighLow) localContent += "&nbsp;" + upArrow; else localContent += "&nbsp;" + downArrow;
		divname.innerHTML = localContent;
	}
}

function writeArrows(viewallthistime,pageNum) {
	var localContent;
	var leftArrowString = "", rightArrowString = "";
	var upDownArrowDiv  = FIND(sortBy + "arrowdiv");
	var upDownArrowDiv2 = FIND(sortBy + "arrowdiv2");
	if(viewallthistime) {
		writeUpDownArrow(upDownArrowDiv);
		writeUpDownArrow(upDownArrowDiv2);
		leftArrowString += leftArrowG;
		rightArrowString += rightArrowG;
		for(i=1; i<=numArrowDivs; i++) {
			localDiv = FIND("rightArrowDiv" + i);
			if(localDiv) localDiv.innerHTML = rightArrowString;
			localDiv = FIND("leftArrowDiv" + i);
			if(localDiv) localDiv.innerHTML = leftArrowString;
		}
	} else {
		writeUpDownArrow(upDownArrowDiv);
		writeUpDownArrow(upDownArrowDiv2);
		if(numPages == 1) {
			leftArrowString += leftArrowG;
			rightArrowString += rightArrowG;
		} else if(pageNum == 1) {
			leftArrowString += leftArrowG;
			rightArrowString += "<a href=javascript:writePage(2)>" + rightArrow + "</a>";
		} else if (pageNum == numPages) {
			leftArrowString += "<a href=javascript:writePage(" + (numPages - 1) + ")>" + leftArrow + "</a>";
			rightArrowString += rightArrowG;
		} else {
			leftArrowString += "<a href=javascript:writePage(" + (pageNum - 1) + ")>" + leftArrow + "</a>"
			rightArrowString += "<a href=javascript:writePage(" + (pageNum + 1) + ")>" + rightArrow + "</a>";
		}
		for(i=1; i<=numArrowDivs; i++) {
			localDiv = FIND("rightArrowDiv" + i);
			if(localDiv) localDiv.innerHTML = rightArrowString;
			localDiv = FIND("leftArrowDiv" + i);
			if(localDiv) localDiv.innerHTML = leftArrowString;
		}
	}
};
function pagingPrice(localItem) {
	var onsale = (localItem.saleprice && localItem.saleprice != 0);
	var usemap = localItem.mappricing;
	var localContent = "";
	if(localItem.price != 0) {
	    if(usemap && !onsale)
	    	localContent += mapPricing(localItem);
	    else {
	            localContent += "<span class=price>" + regularPriceText + " ";
	            if(onsale && strikePrice) localContent += "<s>";
	            localContent += "$" + localItem.price;
	            if(onsale && strikePrice) localContent += "</s>";
	            localContent += "</span><br>";
	    }
	}
	if(onsale && usemap) localContent += mapPricing(localItem);
	if(onsale && !usemap) localContent += "<span class=saleprice>" + salePriceText + "</span><span class=currentsaleprice> <b>$" + localItem.saleprice + "</b></span><br>";	
	if(localItem.psave) localContent += "<div class=yousave>" + youSaveText + " $" + localItem.psave + "</div>";	
	return localContent;
}
function pagingQuantity(localItem) {
	var localContent = "";
	if(localItem.useprice != 0)
		if(localItem.orderable) {
			localContent += "<span class=qtytext>Quantity:&nbsp;";
			localContent += "<input type=text name=vwquantity size=2 class=qtybox value=1>";
			localContent += "</span><br>";
		} else 
			localContent += "";	
	return localContent;
}
function writeVerticalInfo(currentRow, numRows) {
          var localContent = "";
          localContent += "<tr valign=top>";
          //VERTICAL - LOOP CELLS
          for(currentCol=0; currentCol<numColumns; currentCol++) {
                    if(pageSegment[currentItem])localContent += "<td width=" + 100 / numColumns + "% height=100% align=center valign=top";//if added by asif
                    if(pageSegment[currentItem]) localContent += " onmouseover=changeClass(this,'vcell-on'); onmouseout=changeClass(this,'vcell'); class=vcell id=vcell" + currentItem;
                    if(pageSegment[currentItem])localContent += ">";//if added by asif
                    if(pageSegment[currentItem]) {
                              localItem = pageSegment[currentItem];
                              if(contentsElements.indexOf("quantity")) showQuantity = true;
                              var elementArray = contentsElements.split("/");
                              for(i=0;i<elementArray.length;i++) {
                                        switch(elementArray[i]) {
                                                  case "name":
                                                            if(localItem.name != "") localContent += "<a class=productname href=" + localItem.id + ".html>" + localItem.name + "</a><br>";
                                                  break
                                                  case "price":
                                                            localContent += pagingPrice(localItem);
                                                  break
                                                  case "brand":
                                                            if(localItem.brand != "") localContent += "<span class=brand>" + localItem.brand + "</span><br>";
                                                  break
                                        }
                              }
                              currentItem++;
                    } else {
                    if(pageSegment[currentItem])localContent += "&nbsp;";//if added by asif
                    }
                   if(pageSegment[currentItem])localContent += "</form></td><td width=10></td>";//if added by asif
                    if(currentCol<numColumns-1 && columnpad > 0) 
                              localContent += writeCellPadding(currentItem);
          }
          localContent += "</tr>";
          if((currentRow < (numRows - 1)) && (rowpad > 0))
                    localContent += writeRowPadding((numColumns + (3 * (numColumns - 1))));
          return localContent;
};

function writeVerticalImage(currentRow, numRows) {
          var localContent = "";
          localContent += "<tr valign=bottom>";
          for(currentCol=0; currentCol<numColumns; currentCol++) {
                    if(pageSegment[currentItemImage])localContent += "<td  class=box width=" + 100 / numColumns + "% height=201px align=center valign=middle";//if condition added by asif
                    if(pageSegment[currentItemImage]) localContent += "  onmouseover=changeClass(FIND('vcell" + currentItemImage + "'),'vcell-on'); onmouseout=changeClass(FIND('vcell" + currentItemImage + "'),'vcell');";
                    if(pageSegment[currentItemImage])localContent += ">";//if condition added by asif
                    if(pageSegment[currentItemImage]) {
                              localItem = pageSegment[currentItemImage];
                              localContent += "<table cellspacing=0 cellpadding=0><tr><td id=contents-image><a href=" + localItem.id + ".html>" + localItem.img + "</a></td></tr></table>";
                              currentItemImage++;
                    } else {
                              localContent += "&nbsp;";
                    }
                    if(pageSegment[currentItemImage])localContent += "</td><td width=10></td>";//if condition added by asif
                    if(currentCol<numColumns-1 && columnpad > 0) 
                              localContent += writeCellPadding(currentItemImage);
          }
          localContent += "</tr>";
          return localContent;
};

function writeVertical(pageNum, viewallthistime) {
          var localContent = "";
          var numRows = Math.ceil(pageSegment.length / numColumns);
          currentItem=0; currentItemImage = 0;
          for(currentRow=0; currentRow<numRows; currentRow++) {
                    if(pageSegment[currentItem]) {
                              if(contentsElements.indexOf("image") != -1) 
                                        localContent += writeVerticalImage(currentRow, numRows);
                              localContent += writeVerticalInfo(currentRow, numRows);
                    }
          }
          return localContent;
};
/* writePage, changeSortAndPage */
function writePage(pageNum, viewallthistime) {
	if(tempstoreid != storename)
	      alert("Please contact SATISNET");
	else {
		var localContent = "";
		if((numPerPage > -1) && !(viewallthistime)) pageSegment = pagingSegment(window.items,pageNum); else pageSegment = window.items;
		writePageLinks(viewallthistime,pageNum);
		writeItemXofX(viewallthistime,pageNum);
		writePageXofX(viewallthistime,pageNum);
		writeSortLinks("",viewallthistime);
		writeSortLinks("2",viewallthistime);
		writePagingModesLinks();
		writeArrows(viewallthistime,pageNum);
	
		var numRows = Math.ceil(pageSegment.length / numColumns);
		switch(contentsFormat) {
			case "VERTICAL":
				localContent += "<table cellspacing=0 cellpadding=0 width=" + tableWidth + " border=0>";
				localContent += writeVertical(pageNum, viewallthistime);
				localContent += "</table>";
			break
			default:
				writeAsList(viewallthistime,pageNum);
		}	
	
		var theDiv = FIND("contents");
		theDiv.innerHTML = localContent;
		temp = document.location.href.split(".");
		temp2 = temp[temp.length - 2].split("/");
		var currentPageHTML = temp2[temp2.length - 1] + ".html";
		SetCookie('thePage', pageNum, exp);
		SetCookie('theSort', sortBy, exp);
		SetCookie('thePageName', currentPageHTML, exp);
		if(sortHighLow) SetCookie('highlow', "1", exp); else SetCookie('highlow', "0", exp);
		SetCookie('contentsformat', contentsFormat, exp);
		if(viewallthistime) SetCookie('viewall', "1", exp); else SetCookie('viewall', "0", exp);
		
		globalPageNum = pageNum;
		globalViewallthistime = viewallthistime;
	}//passed security test
};

function changeSortAndPage(newSortBy, newHighLow, pageNum, viewallthistime) {

	sortBy = newSortBy;
	sortHighLow = newHighLow;

	updateSortBy(window.items, sortBy);
	sortArray(window.items,0,window.items.length-1);
	if(sortHighLow) window.items.reverse();

	if(viewallthistime)
		writePage(pageNum, true);
	else
		writePage(pageNum, false);
};

function writeCellPadding(num) {
	if(num) localnum = num; else localnum = currentItem;
	if(pageSegment[localnum]) {
		var localContent = "<th><img src=/lib/" + storename + "/pspacer.gif height=1 width="
		                 +  round_decimals(columnpad / 2,0) + "></th>"
		                 +  "<th width=1 bgcolor=\"" + columnSeparatorColor + "\"><img src=/lib/" + storename + "/pspacer.gif"
		                 +  " height=1 width=1></th>"
		                 +  "<th><img src=/lib/" + storename + "/pspacer.gif height=1 width="
		                 +  round_decimals(columnpad / 2,0) + "></th>";
		return localContent;
	} else {
		var localContent = "<th><img src=/lib/" + storename + "/pspacer.gif height=1 width="
		                 +  round_decimals(columnpad / 2,0) + "></th>"
		                 +  "<th width=1><img src=/lib/" + storename + "/pspacer.gif"
		                 +  " height=1 width=1></th>"
		                 +  "<th><img src=/lib/" + storename + "/pspacer.gif height=1 width="
		                 +  round_decimals(columnpad / 2,0) + "></th>";
		return localContent;
	}
}

function writeRowPadding(colspan) {
	if(pageSegment[currentItem]) {
		var localContent = "<tr><th><img src=/lib/" + storename + "/pspacer.gif width=1 height="
		                 +  round_decimals(rowpad / 2,0) + "></th></tr>"
		                 +  "<tr><th bgcolor=\"" + rowSeparatorColor +  "\" colspan=" + colspan + "><img src=/lib/"
		                 +  storename + "/pspacer.gif width=1 height=4></th></tr>"
		                 +  "<tr><th><img src=/lib/" + storename + "/pspacer.gif width=1 height="
		                 +  round_decimals(rowpad / 2,0) + "></th></tr>";
		return localContent;
	} else
		return "";
}
function initPaging() {
	var pageNum, viewallthistime = false, highlowthistime = false;
	var readName = GetCookie('thePageName');
	var readPage = GetCookie('thePage');
	var readSort = GetCookie('theSort');
	var readHighLow = GetCookie('highlow');
	var readContentsFormat = GetCookie('contentsformat');
	var readViewAll = GetCookie('viewall');
	if(readViewAll == "1") viewallthistime = true;
	if(readName || readSort || readContentsFormat) {
		temp = document.location.href.split(".");
		temp2 = temp[temp.length - 2].split("/");
		currentPageHTML = temp2[temp2.length - 1] + ".html";
		if(readName == currentPageHTML)
			(readPage == 0) ? pageNum = 1 : pageNum = parseInt(readPage);
		else
			pageNum = 1;
		readSort ? sortBy = readSort : sortBy = defaultSort;
		(readHighLow == 1 && readSort) ? highlowthistime = true : highlowthistime = false;
		(readContentsFormat == null) ? contentsFormat = defaultContentsFormat : contentsFormat = readContentsFormat;
	} else {
		pageNum = 1;
		sortBy = defaultSort;
		contentsFormat = defaultContentsFormat;
	}
	if(sortBy == "default")
		writePage(pageNum,viewallthistime);
	else
		changeSortAndPage(sortBy,highlowthistime,pageNum,viewallthistime);
};
function updateSortBy(array, sortby) {
	for(i=0; i<array.length; i++) {
		switch(sortby) {
			case "default" :
				array[i].sortby = array[i].defaultsort;
			break
			case "name" :
				array[i].sortby = array[i].name;
			break
			case "price" :
				array[i].sortby = parseInt(array[i].useprice);
			break
			default : array[i].sortby = array[i].defaultsort;
		}
	}
};
function writeOneSortLink(linkid,linkname,sep,chosen,bot,viewallthistime) {
	var localContent = "";
	if(chosen) {
		localContent += "<a class=chosen href=#top onclick=javascript:changeSortAndPage(\"" + linkid + "\",";
		if(sortHighLow) localContent += "false"; else localContent += "true";
		localContent += ",1," + viewallthistime + ");>";
		localContent += linkname;
		localContent += "</a>";
	} else {
		localContent += "<a href=#top onclick=javascript:changeSortAndPage(\"" + linkid + "\",false,1," + viewallthistime + ");>";
		localContent += linkname;
		localContent += "</a>";
	}
	localContent += "<span id=" + linkid + "arrowdiv" + bot + "></span>";
	if(sep) localContent += sortLinkSeparator;
	return localContent;
}

function writeSortLinks(bot,viewallthistime) {
	var sortLinksDiv = FIND("sortlinks" + bot);
	if(sortLinksDiv) {
		var localContent = "<span id=sortlinkshead><b>Sort By :</b></span><span id=sortlinks> ";
		if(showBrandSort) var priceSep = true; else var priceSep = false;
		switch(sortBy) {
			case "name":
					if(showDefaultSort) localContent += writeOneSortLink("default",defaultsorttxt,true,false,bot,viewallthistime);
					localContent += writeOneSortLink("name","Name",true,true,bot,viewallthistime);
					localContent += writeOneSortLink("price","Price",priceSep,false,bot,viewallthistime);
					if(showBrandSort) localContent += writeOneSortLink("brand","Manufacturer",false,false,bot,viewallthistime);
			break
			case "price":
					if(showDefaultSort) localContent += writeOneSortLink("default",defaultsorttxt,true,false,bot,viewallthistime);
					localContent += writeOneSortLink("name","Name",true,false,bot,viewallthistime);
					localContent += writeOneSortLink("price","Price",priceSep,true,bot,viewallthistime);
					if(showBrandSort) localContent += writeOneSortLink("brand","Manufacturer",false,false,bot,viewallthistime);
			break
			default:
					if(showDefaultSort) {
						localContent += "<span class=chosen>";
						localContent += defaultsorttxt;
						localContent += "</span>";
						localContent += sortLinkSeparator;
					}
					localContent += writeOneSortLink("name","Name",true,false,bot,viewallthistime);
					localContent += writeOneSortLink("price","Price",priceSep,false,bot,viewallthistime);
					if(showBrandSort) localContent += writeOneSortLink("brand","Manufacturer",false,false,bot,viewallthistime);
		}
		localContent += "</span>";
		sortLinksDiv.innerHTML = localContent;
	}
};

function changeFormat(newFormat) {
	contentsFormat = newFormat;
	writePage(globalPageNum, globalViewallthistime);
}
function writePagingModesLinks() {
	if(showPagingModes) {
		var localContent  = "<div id=modes>";
		(contentsFormat != "VERTICAL") ? localContent += "<a href=#top onclick=\"javascript:changeFormat('VERTICAL');\">" : localContent += "<span class=chosen>";
		localContent += "Style 1";
		(contentsFormat != "VERTICAL") ? localContent += "</a>" : localContent += "</span>";
		localContent += "<span class=sep>" + modeLinkSeparator + "</span>";

		(contentsFormat != "ELL") ? localContent += "<a href=#top onclick=\"javascript:changeFormat('ELL');\">" : localContent += "<span class=chosen>";
		localContent += "Style 2";
		(contentsFormat != "ELL") ? localContent += "</a>" : localContent += "</span>";

		if(showWrapMode) {
			localContent += "<span class=sep>" + modeLinkSeparator + "</span>";
			(contentsFormat != "WRAP") ? localContent += "<a href=#top onclick=\"javascript:changeFormat('WRAP');\">" : localContent += "<span class=chosen>";
			localContent += "Style 3";
			(contentsFormat != "WRAP") ? localContent += "</a>" : localContent += "</span>";
		}

		if(showListMode) {
			localContent += "<span class=sep>" + modeLinkSeparator + "</span>";

			(contentsFormat != "LIST") ? localContent += "<a href=#top onclick=\"javascript:changeFormat('LIST');\">" : localContent += "<span class=chosen>";
			localContent += "List Mode";
			(contentsFormat != "LIST") ? localContent += "</a>" : localContent += "</span>";
		}

		localContent += "</div>";

		var listModeDiv = FIND("pagingmodes");
		if(listModeDiv) listModeDiv.innerHTML = localContent;
		listModeDiv = FIND("pagingmodes2");
		if(listModeDiv) listModeDiv.innerHTML = localContent;
	}
}