var expDays = 30;
var exp = new Date(); 
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));

// Version 2.0
//some of these global variables are set from the calling page (i.e. defaultContentsFormat = "VERTICAL")
var defaultSort, defaultContentsFormat, contentsFormat, tableWidth, numColumns, numPerPage, numPages, contentsElements, 
    viewAll, pageLinkPrefix, columnpad, pageLinkSeparator, globalPageNum, 
    globalViewallthistime, currentItem, addToCartImage, showQuantity, pageSegment;
var pageItems = new Array();
var oldSortBy = "";
var SORT_ASC = 1,
		SORT_DESC = -1;
var addToCartImage = '<input class=order-button valign=absmiddle type=submit value="Add to cart">'; 
var _pagingState;
var pr_style_sheet="http://cdn.powerreviews.com/aux/12403/2158/css/express.css";

var _filterCallbacks = {
	'onsale' : function(it, attr, value) { return isSaleItem(it); },
	'eventtype' : function(it, attr, value) { return filterEvent(it, value); },
	'color' : function(it, attr, value) { return filterColor(it,value); },
	'theme' : function(it, attr, value) { return filterMultiAttr(attr,it,value,'|'); },
	'printMethod' : function(it, attr, value) { return filterMultiAttr(attr,it,value,'|'); }
}

numPerPage = 32; 
numColumns = 4; 
defaultContentsFormat = "VERTICAL"; 
viewAll = true; 
defaultSort = "default"; 
columnpad = "14"; 
pageLinkPrefix = "<font class='pagingBlueText'>Page</font>&nbsp;&nbsp;"; 
pageLinkSeparator = "&nbsp;&nbsp;|&nbsp;&nbsp;"; 
tableWidth = "100%"; 

contentsElements = "image/name/price/papercolor/quickview";
loadjscssfile("http://site.invitationbox.com/js/swfobject.js", "js");

$(document).ready( function() {
	initPaging();

	$(".filterClose").hide();
 
	$(".filterExpander").live('click', function(){
		$(this).toggleClass("expandClosed").next('.filterContainer').slideToggle("slow");
		
		if ($(this).hasClass("expandClosed")) {
			$(this).children('.expander').attr('src', 'http://static.invitationbox.com/images/icoLN_Plus.png');
		} else {
			$(this).children('.expander').attr('src', 'http://static.invitationbox.com/images/icoLN_Minus.png');
		}
	});
	
	$(".filterExpander").each( function() {
		if ($(this).hasClass("expandClosed")) {
			$(this).next('.filterContainer').slideToggle("slow");
			$(this).children('.expander').attr('src', 'http://static.invitationbox.com/images/icoLN_Plus.png');
		} else {
			$(this).children('.expander').attr('src', 'http://static.invitationbox.com/images/icoLN_Minus.png');
		}
	});
	
	$(".hoverChange").live( 'mouseover', 
		function() {
			if (this.src.indexOf('_on') > -1) {
				$(this).addClass("wasOn");
				this.src = this.src.replace("_on", "_over");
			} else {
				this.src = this.src.replace("_off", "_over");
			}
		}
	);
	
	$(".hoverChange").live('mouseout',
		function() {
			if ($(this).hasClass("wasOn")) {
				this.src = this.src.replace("_over", "_on");
				$(this).removeClass("wasOn");
			} else {
				this.src = this.src.replace("_over", "_off");
			}
		}
	);
});

function isSaleItem(it) { return it['showsalepricing']; }

function filterEvent(it, value) {
	_pagingState.filters['eventtype-'+value] = value;
	return (it['eventtype'].indexOf(value) != -1);	
}

function filterMultiAttr(attr, it, value, sepChar) {
	_pagingState.filters[attr +'-'+value] = value;
	var separatedValues = it[attr].split(sepChar);
	
	for (var idx = 0; idx < separatedValues.length; idx++) {
		if (separatedValues[idx] == value) {
			return true;
		}
	}	
	
	return false;
}

function filterColor(it, value) {
	return (it['primarycolor'].indexOf(value) != -1 || it['secondarycolor'].indexOf(value) != -1 || it['thirdcolor'].indexOf(value) != -1);
}

function pagingItem(id, code, name, img, listimg, price, saleprice, options, abstr, orderable, brand, theme, pricerange, newitem, papercolor, fullname, attributes) {
	if (!window.items) window.items = new Array();
		
	this.id         = id.toLowerCase();
	this.code       = code;
	this.name       = name;
	this.img        = img;
	this.listimg    = listimg;
	this.price      = price;
	this.saleprice  = saleprice;
	this.options    = options;
	this.abstr      = abstr;
	this.orderable  = orderable;
	this.brand      = brand;
	this.theme      = theme;
	this.pricerange = pricerange;
	this.newitem    = newitem;
	this.papercolor = papercolor;
	this.fullname   = fullname;
	this.sortby     = "name";
	
	for (attr in attributes)
		this[attr] = attributes[attr];

	this.defaultsort=window.items.length;
	window.items[window.items.length] = this;
}

function getDefaultPagingState() {	
	var ps = {
		pageName : '',
		pageNum : 1,		
		sortBy : 'defaultsort',
		sortDirection : SORT_ASC,
		contentsFormat : defaultContentsFormat, 
		viewAll : false,		
		filters : new Array() 
	};
	return ps;
}

function loadPagingState() {	
	var ps = getDefaultPagingState();
	var readName = GetCookie('thePageName');	
	
	ps.pageName = getCurrentPageHTML();
		
	if (readName) {		
		ps.viewAll = (GetCookie('viewall') == 1);		
		
		var readContentsFormat = GetCookie('contentsformat');		
		if (readContentsFormat)
			ps.contentsFormat = GetCookie('contentsformat');
	
		var readSortBy = GetCookie('theSort');
		if (readSortBy)
			ps.sortBy = readSortBy;
		
		var readSortDir = GetCookie('sortDirection')
			ps.sortDirection = readSortDir; 
		
		if (readName == ps.pageName) {
			var readPage = parseInt(GetCookie('thePage'));					
			ps.pageNum = (readPage == 0 || ps.viewAll) ? 1 : readPage;
			
			var readFilters = GetCookie('filters');
			if (readFilters)
				ps.filters = deserializeFilterData(readFilters);
		}
	}
	
	var filterType = getParameterByName("ft");
	var filterVal = unescape(getParameterByName("fv"));
		
	if (filterType != '') {
		if (filterVal != '') {
			try {
				if (filterVal == 'true') {
					$("#cb"+filterType).attr('checked',true);
					ps.filters[filterType] = true;
				} else {
					ps.filters[filterType] = filterVal;
					$("#cb"+filterType+filterVal).attr('checked',true);
				}
			} catch (e) { alert(e); }
		}
	}	
	
	return ps;
}

function savePagingState(ps) {	
	SetCookie('thePageName', ps.pageName, exp); 		
	SetCookie('thePage', ps.pageNum, exp); 
	SetCookie('theSort', ps.sortBy, exp); 
	SetCookie('sortDirection', ps.sortDirection, exp); 
	SetCookie('contentsformat', ps.contentsFormat, exp); 
	SetCookie('viewall', (ps.viewAll ? 1 : 0), exp); 
	SetCookie('filters', serializeFilterData(ps.filters), exp);
}

function deserializeFilterData(data) {
	var ret = new Array();
	var filters = data.split("|");
	if (filters.length) {
		for (var i = 0; i < filters.length; i++) {
			var filter = filters[i].split("::");
			if (filter.length == 2) {
				var val = filter[1];

				if (val == "true") 				
					val = true;
				else if (val == "false")
					val = false;						
					
				ret[filter[0]] = val;
			}
		}
	}
	return ret;
}

function serializeFilterData(data) {
	var str = '';
	var i = 0;
	for (filter in data) {
		if (i++)
			str += "|";		
		str += filter + "::" + data[filter];
	}
	return str;
}

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 writePageLinks( viewallThisTime, pageNum) {
	$("#pagelinks2").html(getPageLinks(viewallThisTime, pageNum, true));
}

function getPageLinks( viewallThisTime, pageNum, addTopLink) {
	var numLinks = 7;
	var plusMinus = 3;
	
	if (numPages > 1) {
		var pageLinks = "<span id=pagelinks>" + pageLinkPrefix;

		var a, b;
		
		if (numPages > numLinks) {
			a = pageNum - plusMinus;
			b = pageNum + plusMinus;
			if (a < 1) {a = 1;}
			if (b < numLinks) b = numLinks;
			if (b > numPages) {b = numPages;}
			if (a > (numPages - numLinks)) a = numPages - numLinks;
		} else {
			a = 1;
			b = numPages;
		}

		for(i=a; i<=b; i++) {
			if(i == pageNum && !viewallThisTime)
				pageLinks += "<span class=chosen>" + i + "</span>";
			else {
				pageLinks += '<a href="';
				pageLinks += (addTopLink)? '#top" onclick="' : 'javascript:';
				pageLinks += 'writePage(' + i + ',false);">' + i + '</a>';
			}
      
			if (i < b)
       	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="';
				if (addTopLink)
					pageLinks += '#top" onclick="';
				else
					pageLinks += 'javascript:';
				pageLinks += 'writePage(1,true)" class="viewall">View All</a>';
			}
		}
		pageLinks += "</span>";
	
		return pageLinks;
	}
	return '';
}

function writeItemXofX(viewallthistime,pageNum) {
	theItemDiv = FIND("itemof2");
	if (theItemDiv) theItemDiv.innerHTML = htmlItemXofX(viewallthistime, pageNum);
}

function htmlItemXofX(viewallthistime,pageNum) {
	var currentItemLow = ((pageNum - 1) * numPerPage + 1);
	var currentItemHigh = pageNum * numPerPage;
	var numItems = window.items.length == 0 ? 1 : window.items.length;
	var theString = "<span class=itemof>";

	if((currentItemLow <= numItems) && (numItems <= currentItemHigh)) {
		currentItemHigh = numItems;
	}
	
	if(currentItemLow == currentItemHigh) {
		theString += "showing product <span class=bold>" + currentItemLow + "</span> of " + numItems ;
	} else if(viewallthistime) {
		theString += "showing items <span class=bold>1</span> - <span class=bold>" + numItems + "</span> of " + numItems ;
	} else {
		theString += "showing items <span class=bold>" + currentItemLow + "</span> - <span class=bold>" + currentItemHigh + "</span> of " + numItems ;
	}
	theString += "</span>";
	
	return theString;
}

function writePageXofX(viewallthistime,pageNum) {
	pageofDiv = FIND("pageof2");
	if(pageofDiv) pageofDiv.innerHTML = htmlPageXofX(viewallthistime, pageNum);
}

function htmlPageXofX(viewallthistime,pageNum) {
	var localContent = "<span class=pageof>";
	if(viewallthistime)
		localContent += "Viewing all items";
	else
		localContent += "Page <span class=bold>" + pageNum + " </span>of " + numPages;

	localContent += "</span>";

	return localContent;
}

function writeArrowsHtml(viewallthistime,pageNum) {
	var localContent ="";
	var leftArrowString = "", rightArrowString = "";
	var prevText = "<< Previous";
	var nextText = "Next >>";
	var sepText = "&nbsp;&nbsp;|&nbsp;&nbsp;";
	
	if(viewallthistime) {
		localContent += prevText + sepText + nextText;
	} else {
		if(numPages == 1) {
			leftArrowString += prevText + sepText;
			rightArrowString += nextText;
		} else if(pageNum == 1) {
			leftArrowString += prevText + sepText;
			rightArrowString += "<a href=javascript:writePage(2)>" + nextText + "</a>";
		} else if (pageNum == numPages) {
			leftArrowString += "<a href=javascript:writePage(" + (numPages - 1) + ")>" + prevText + "</a>" + sepText;
			rightArrowString += nextText;
		} else {
			leftArrowString += "<a href=javascript:writePage(" + (pageNum - 1) + ")>" + prevText + "</a>"  + sepText;
			rightArrowString += "<a href=javascript:writePage(" + (pageNum + 1) + ")>" + nextText + "</a>";
		}
		
		localContent += "<span onClick=\"window.location.href = '#top'\">" + leftArrowString + "</span>";
		localContent += "<span onClick=\"window.location.href = '#top'\">" + rightArrowString + "</span>";
		
	}
	return localContent;
}

function pagingPrice(localItem) {
	var onsale = (localItem['showsalepricing']);
	var supersale = (localItem['showsupersalepricing']);
	var localContent = "";
	
	if (localItem.price != "") {
		if (localItem.price == "Currently Not Available") {
			localContent += "<span class=saleprice>" + localItem.price + "</span><br>";	
		}	else if (!onsale){
			localContent += "<span class=price>" + localItem.price + "</span><br>";
		} else if(onsale && supersale){
			localContent += "<span class=saleprice><b>" + localItem.saleprice + "</b></span><br>";			
		} else {
			localContent += "<span class=saleprice>" + localItem.saleprice + "</span><br>";
		}
	}
	
	if (localItem['minorder'] != '') {
		localContent += "<span class=minOrderQty>Minimum Order: " + localItem['minorder'] + "</span>";
	}
	
	return localContent;
}

function pagingQuantity(localItem) {
	var localContent = "";
	if(localItem.useprice != 0)
		localContent += (localItem.orderable) ? "<span class=qtytext>Quantity: <input type=text name=vwquantity size=2 class=qtybox value=1></span><br>":"";
	return localContent;
}

function writeVerticalInfo(currentRow, numRows) {
	var localContent = "<tr valign=top class=contents-row>";

	for(currentCol=0; currentCol<numColumns; currentCol++) {
		localContent += "<td width=" + 100 / numColumns + "% height=100% align=center";
		localContent += (pageSegment[currentItem])?" class=vcell id=vcell" + currentItem:"";
		localContent += "><div class='itemContent'>";
	
		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 "iboxgreen":
						if(localItem["green"]) localContent += "<div class=iboxgreen><img alt='InvitationBoxGreen' src='http://site.invitationbox.com/images/iboxgreenshort.gif'/></div>";
						else localContent += "<div class=iboxgreen></div>"
						break;
					case "icons":
						localContent += writeIcons(localItem);
						break;
					case "papercolor":
						if(localItem.papercolor) localContent += "<div class=papercolor>{ <a href=" + localItem.id + ".html>Pick Your Colors</a> }</div>";
						break;
					case "name":
						if(localItem.name != "") localContent += "<div class=advanceditem><a title='"+localItem.fullname+"' href=" + localItem.id + ".html>" + localItem.name + "</a></div>";
						break;
					case "code":
						if(localItem.code != "") localContent += "<div class=code>" + localItem.code + "</div>";
						break;
					case "price":
						localContent += pagingPrice(localItem);
						break;
					case "minorder":
						if(localItem.minorder != "") localContent += "<div class=minorder>Minimum Order: " + localItem.minorder + "</div>";
						break;
					case "abstract":
						if(localItem.abstr != "") localContent += "<div class=abstract>" + localItem.abstr + "</div>";
						break;
					case "quickview":
						if ( $.browser.msie && $.browser.version <= 6 ) {
							localContent += "";
					  } else {
							localContent += "<div class='qvHover'><a href='javascript:loadQuickView(" + (currentItem) + ");' onMouseOver='javascript:$(\"#qvImg"+currentItem+"\").attr(\"src\",\"http://site.invitationbox.com/images/ibox-quickview-on.gif\");' onMouseOut='javascript:$(\"#qvImg"+currentItem+"\").attr(\"src\",\"http://site.invitationbox.com/images/ibox-quickview-off.gif\");'><img id='qvImg" + currentItem + "' src='http://site.invitationbox.com/images/ibox-quickview-off.gif' border='0'></a></div>";
						}
						break;
					case "brand":
						localContent += "<div class=regpr>" + localItem.brand + "</div>";
						break;
					case "quantity": 
						break;
					case "image": 
						localContent += writeVerticalImage(localItem);
						break;
					case "reviews":
						localContent += writeReviewDiv(localItem);
						break;
				}
			}		
			currentItem++;
		} else {
			localContent += "&nbsp;";
		}
		localContent += "</div></td>";
	}
	localContent += "</tr>";

	return localContent;
}

function writeReviewDiv(localItem) {
	var sReview = '<div class="pr_snippet_category">';
	sReview += '<script type="text/javascript">';
	sReview += 'var pr_snippet_min_reviews=0;';
	sReview += 'POWERREVIEWS.display.snippet(document, { pr_page_id : "'+ localItem.id +'" });';
	sReview += '</script></div>';
	return sReview;
}

function writeIcons(localItem) {
	var s = "<div class=sectionIcons>";
	s += (localItem["quickship"]) ? "<img alt='Quick Ship' src='http://site.invitationbox.com/images/quick-ship-galler-icon.gif' title='Quick Ship Item' />" : "";
	s += (localItem["green"]) ? "<img alt='InvitationBoxGreen' src='http://site.invitationbox.com/images/recycle-icon-gallery.gif' title='InvitationBox Green Item'/>" : "";
	s += (localItem["multiColor"]) ? "<img alt='InvitationBoxGreen' src='http://site.invitationbox.com/images/iconMultiColor.gif' title='Available in Multiple Colors'/>" : "";
	s += "</div>";
	
	return s;
}

function writeVerticalImage(localItem) {
	var localContent = "";
	localContent += "<table cellspacing=0 cellpadding=0 border=0><tr>";	
	localContent += "<td style='background-color:transparent;'>";

	if (localItem.newitem) {
		localContent += "<div class=saleheader><img src='http://site.invitationbox.com/images/newitem_icon.gif' /></div>";
	} else { localContent += "&nbsp;"; }
	localContent += (localItem["multiColor"]) ? "<img alt='Multiple Colors Available' src='http://static.invitationbox.com/images/icoAdditionalColors.png' style='float:right;' title='Available in Multiple Colors'/>" : "";
	
	localContent += "</td></tr><tr><td id=contents-image style='background-color:transparent;' valign='bottom'><a title='"+localItem.fullname+"' href=" + localItem.id + ".html>" + localItem.img + "</a></td></tr></table>";
	
	return localContent;
};

function writeVertical(pageNum, viewallthistime) {
	var localContent = "";
	var numRows = Math.ceil(pageSegment.length / numColumns);
	currentItem=0; 
	
	for(currentRow=0; currentRow<numRows; currentRow++) {
		if(pageSegment[currentItem]) {
			localContent += writeVerticalInfo(currentRow, numRows);
			if (currentRow < numRows-1) {
				localContent += "<tr><td colspan='100'><hr shade color='#E4DBCA' width='95%' align='center'></td></tr>";
			}
		}		
	}
	
	return localContent;
};

function writePage(pageNum, viewallthistime) {	
	var localContent = "";
	
	if ((numPerPage > -1) && !(viewallthistime)) 
		pageSegment = pagingSegment(window.items, pageNum); 
	else 
		pageSegment = window.items; 
			
	var numRows = Math.ceil(pageSegment.length / numColumns); 

	$('#pagingNavBar').html(writePagingNavBar(viewallthistime, pageNum));
	$('#itemBlockFilter').html(writeItemFilterBlock(viewallthistime));
	localContent += "<table id=\"pagingTable\" cellspacing=0 cellpadding=0 width=" + tableWidth + " border=0>"; 
	localContent += writeVertical(pageNum, viewallthistime); 
	localContent += "</table>";

	$("#contents").fadeOut('fast', function() { $(this).html(localContent).fadeIn('fast') });

	writePageLinks(viewallthistime,pageNum); 
	writeItemXofX(viewallthistime,pageNum); 
	writePageXofX(viewallthistime,pageNum); 
	$("#navBottomNextPrev").html("<font style='font-family:arial;font-size:10pt;'>"+writeArrowsHtml(viewallthistime, pageNum)+"</font></td>").addClass('pagingNavBar'); 

	_pagingState.pageNum = pageNum;
	_pagingState.viewAll = viewallthistime;
	
	savePagingState(_pagingState);
	globalPageNum = pageNum; 
	globalViewallthistime = viewallthistime; 
	
  if(document.cookie.indexOf('invitationboxrecentitemsCookie') > 0) {  	
		var so = new SWFObject("http://site.invitationbox.com/Flash/recently_viewed_items/recently_viewed_widget.swf", "sotester", "200", "200", "8", "#FFFFFF");
		so.addParam("scale", "noscale");
		so.addParam("allowScriptAccess", "always");
		so.write("recentlyViewedItems");	
	}
}; 
	
function getCurrentPageHTML() {
	temp = document.location.href.split(".");
	temp2 = temp[temp.length - 2].split("/");
	return temp2[temp2.length - 1] + ".html";
}

function initPaging() {	
	numPages = Math.ceil(window.items.length / numPerPage);
	_pagingState = loadPagingState(); 
		
	if (_pagingState.sortBy != "defaultsort") {
		sortItems(window.items, _pagingState.sortBy, _pagingState.sortDirection);		
	}
	
	pageItems = window.items;
	
	if (assocArraySize(_pagingState.filters)) {
		applyActiveFilters(_pagingState.viewAll);
	}
		
	writePage(_pagingState.pageNum, _pagingState.viewAll); 
}

function applyFilter(attr, value, viewallthistime) {			
	if (value == "All") {
		unnapplyFilter(attr, viewallthistime)
		return;
	}

	filterItems(attr, value);
	calculatePaging();
	_pagingState.filters[attr] = value;
	writePage(globalPageNum, viewallthistime);	
}

function filterItems(attr, value) {	
	var ar = new Array(); 
	var j = 0; 
	
	if (attr.indexOf('-') != -1) {
		attr = attr.substring(0,attr.indexOf('-'));
	}

	var filterItemCallback = filterItem;
	
	if (_filterCallbacks[attr])
		filterItemCallback = _filterCallbacks[attr]; 
			
	for (var i = 0; i < window.items.length; i++) {
		var it = window.items[i];		
		var matchFound;

		if (matchFound = filterItemCallback(it, attr, value)) {
			ar[j] = it;
			j++;
		}
	}
	
	window.items = ar;
}

function filterItem(it, attr, value) {
	if (value == 'Other')
		value = '';			
	
	var filterValue = it[attr];
			
	return filterValueMatch(filterValue, value);
}

function resetAllFilters(viewallthistime) {
	_pagingState.filters = new Array();
	window.items = pageItems;
	calculatePaging();
	writePage(_pagingState.pageNum, viewallthistime);
}

function unnapplyFilter(attr, viewallthistime) {
	_pagingState.filters[attr] = false;
	window.items = pageItems; 
	applyActiveFilters(viewallthistime);
	calculatePaging();
	writePage(_pagingState.pageNum, viewallthistime);	
}

function applyActiveFilters(viewallthistime) {
	for (attr in _pagingState.filters) {
		if (_pagingState.filters[attr]) {
			filterItems(attr, _pagingState.filters[attr], viewallthistime);
		}
	}

	calculatePaging();
}

function hasActiveFilters() {
	for (attr in _pagingState.filters)					
		if (_pagingState.filters[attr])
			return true;
	
	return false;
}

function calculatePaging() {
	numPages = Math.ceil(window.items.length / numPerPage);
	numPages = (numPages == 0) ? 1 : numPages;
	
	if (globalPageNum > numPages) globalPageNum = 1;		
}

function filterValueMatch(filterValue, itemValue) {
	if (typeof filterValue == 'string' && typeof itemValue == 'string')	{
		return filterValue.toLowerCase().replace(/&quot;/g,"\"") == itemValue.toLowerCase();
	}	else return filterValue == itemValue;
}

function writeSortLinksImages(viewallthistime) {
	var sortDir = _pagingState.sortDirection;
	var strContent = ' &nbsp;&nbsp; ';
	
	strContent += '<a href="javascript:applySort(\'defaultsort\',' + viewallthistime + ');">';
	strContent += (_pagingState.sortBy == 'defaultsort') ? '<img class="valignCenter" src="http://site.invitationbox.com/images/paging/BTN-Default-Bu.gif" height="24">' : '<img class="valignCenter" src="http://site.invitationbox.com/images/paging/BTN-Default-BR.gif" height="24">'; 		
	strContent += '</a> &nbsp;&nbsp; ';	
	strContent += '<a href="javascript:applySort(\'name\',' + viewallthistime + ');">';
	
	if (_pagingState.sortBy == 'name') {
		if (sortDir == SORT_ASC) {
			strContent += '<img class="valignCenter" src="http://site.invitationbox.com/images/paging/BTN-Name-Up-Bu.gif" height="24">';
		} else {
			strContent += '<img class="valignCenter" src="http://site.invitationbox.com/images/paging/BTN-Name-Down-Bu.gif" height="24">';
		}
	} else {
		strContent += '<img class="valignCenter" src="http://site.invitationbox.com/images/paging/BTN-Name-BR.gif" height="24">';
	}
	
	strContent += '</a> &nbsp;&nbsp; <a href="javascript:applySort(\'asLowAs\',' + viewallthistime + ');">';
	
	if (_pagingState.sortBy == 'asLowAs') {
		if (sortDir == SORT_ASC) {
			strContent += '<img class="valignCenter" src="http://site.invitationbox.com/images/paging/BTN-Price-low-high-Bu.gif" height="24">';
		} else {
			strContent += '<img class="valignCenter" src="http://site.invitationbox.com/images/paging/BTN-Price-high-low-Bu.gif" height="24">';
		}
	} else {
		strContent += '<img class="valignCenter" src="http://site.invitationbox.com/images/paging/BTN-Price-BR.gif" height="24">';
	}
	
	strContent += '</a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ' + getBooleanFilters(viewallthistime);
	
	return strContent;
}

function applySort(newSort, viewallthistime) {
  sortDirection = (_pagingState.sortBy != newSort) ? SORT_ASC : _pagingState.sortDirection * -1; //check global sortby variable to determine which direction to sort
		
	window.items = sortItems(window.items, newSort, sortDirection);

	_pagingState.sortBy = newSort;	
	_pagingState.sortDirection = sortDirection;
	
	writePage(_pagingState.pageNum, viewallthistime);		
}

function sortItems(items, newSort, sortDirection) {
	if (!sortDirection)
		sortDirection = SORT_ASC;
		
	items.sort(	function () { 
		var arg0 = arguments[0][newSort];
		var arg1 = arguments[1][newSort];			
		if (typeof arg0 == 'string' && typeof arg1 == 'string') {
			arg0 = arg0.toLowerCase();
			arg1 = arg1.toLowerCase();
		}
					
		if (arg0 < arg1) { return -1 * sortDirection; }
		if (arg0 > arg1) { return 1 * sortDirection; }
		
		//secondary sort by name for brand and pricerange
		if (newSort == 'brand' || newSort == 'asLowAs') {				
			var name0 = arguments[0]['name'].toLowerCase();
			var name1 = arguments[1]['name'].toLowerCase();				

			if (name0 < name1) { return -1; }
			if (name0 > name1) { return 1; }
		}
		return 0;			
	});

	return items;
}

function writeItemFilterBlock(viewallthistime) {	
	$("#paging").addClass("advanced");
	
	var showPhotos = false;
	
	for (var i=0;i<window.items.length;i++) {
		if (window.items[i]['photovalue']) {
			if (window.items[i]['photovalue'] > 0) {
				showPhotos = true;
				break;			
			}
		}
  }
	
	var html = '<table border=0 style="font-size:12pt;" id="filterTable" cellpadding=1 cellspacing=0 width="100%">';
	
	if (typeof(showEventType)!="undefined") {
		if (showEventType) {
			html += '<tr><td><table class="filterBorder" cellpadding=0 cellspacing=0 width="100%"><tr><td>' + createMultiFilter('eventtype', 'Event', ',', 10, false, false) + '</td></tr></table><br></td></tr>';
		}
	}
	
	html += '<tr><td><table class="filterBorder" cellpadding=0 cellspacing=0 width="100%"><tr><td>' + createMultiFilter('theme', 'Theme', '|', 13, true, false) + '</td></tr></table><br></td></tr>';	
	
	if (typeof(showColorFilter) !="undefined") {
		if (showColorFilter) {
		  html += '<tr><td><table class="filterBorder" cellpadding=0 cellspacing=0 width="100%"><tr><td>' + createColorFilter(viewallthistime, false) + '</td></tr></table><br></td></tr>';	
		}
	}

	if (typeof(showPhotoCardStyle)!="undefined") {
		if (showPhotoCardStyle) {
		  html += '<tr><td><table class="filterBorder" cellpadding=0 cellspacing=0 width="100%"><tr><td>' + createFilter('photocardstyle', 'Card Style', 10, false) + '</td></tr></table><br></td></tr>';	
		}
	}
	
	if (showPhotos) {
		html += '<tr><td><table class="filterBorder" cellpadding=0 cellspacing=0 width="100%"><tr><td>' + createFilter('photovalue','# of Photos', 10, true) + '</td></tr></table><br></td></tr>';
	}
	
	html += '<tr><td><table class="filterBorder" cellpadding=0 cellspacing=0 width="100%"><tr><td>' + createFilter('brand', 'Designer', 100, true) + '</td></tr></table><br></td></tr>';
	html += '<tr><td><table class="filterBorder" cellpadding=0 cellspacing=0 width="100%"><tr><td>' + createMultiFilter('printMethod','Print Method', '|', 10, true, true) + '</td></tr></table><br></td></tr>';
	html += '<tr><td><table class="filterBorder" cellpadding=0 cellspacing=0 width="100%"><tr><td>' + createFilter('productsize', 'Size', 10, true) + '</td></tr></table><br></td></tr>';
 	html += '<tr><td><div id="recentlyViewedItems"></div></td></tr>';
	html += '</table>';
	
	return html;	
}

function writePagingNavBar(viewallthistime, pageNum) {
	var html = "<table align='center' border=0 cellpadding=4 cellspacing=0 width='988' height='35' background='http://site.invitationbox.com/images/paging/IMG-Section-Top-Bar.gif'><tr>";
	
	html += "<td class='pagingNavBar' valign='middle' width='250'>";
	html += "Narrow Your Results&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;";
	html += "<font class='pagingBlueText'>Sort By:</font></td>";
	html += "<td class='pagingSortButtons' valign='bottom'>" + writeSortLinksImages(viewallthistime) + "</td>";
	html += "<td class='pagingNavBar' valign='bottom' style='text-align:right !important;'><font style='font-family:arial;font-size:10pt;'>"+writeArrowsHtml(viewallthistime, pageNum)+"</font></td>";	
	html += "</tr></table>";
	html += "<table align='center' border=0 cellpadding=0 cellspacing=0 width='988' height='35'><tr>";
	html += "<td class='pagingNavBar' style='text-align:center;' valign='top' width='150'>"+window.items.length+" items";
	html += "<a href=\"javascript:resetAllFilters("+viewallthistime+")\"><img src='http://site.invitationbox.com/images/paging/BTN-Reset-All-FIlters.gif' border=0></a></td>";
	html += "<td class='pagingNavBottomBar'>" + htmlItemXofX(viewallthistime, pageNum) + "</td>";
	html += "<td class='pagingNavBottomBar'>" + getPageLinks(viewallthistime,pageNum,false) + "</td>";
	html += "<td class='pagingNavBottomBar' align='right'>" + htmlPageXofX(viewallthistime, pageNum);
	
	if (!viewallthistime) {
		html += '&nbsp;&nbsp;&nbsp;<a href="javascript:writePage(1,true)" class="viewall">View All</a>';
	}
	
	html += "</td></tr></table>";
	return html;
}

function createColorFilter(viewallthistime, startClosed) {  
	var html = '<div class="filterDiv"><div class="filterExpander'+ (startClosed?' expandClosed':'') +'"><img class="expander left" src="http://static.invitationbox.com/images/icoLN_Minus.png">&nbsp;<span class="filterTitle left">Filter By Color</span></div><div class="filterContainer clearFloat">';
	var allowEmptyValues = true;
	var attr = 'color';
	var arColors = new Array("White","Ivory","Pink","Red","Orange","Yellow","Green","Blue","Purple","Gold","Brown","Black","Grey / Silver");
	var attrValues = getItemColorValues();

	for (x in arColors)	{
		var attrValue = arColors[x];
		var colorCount = (attrValues[attrValue] ? attrValues[attrValue] : 0);
		if (colorCount > 0) {
			if (_pagingState.filters[attr + '-' + attrValue] == attrValue) {
				html += '<div class=filterCell><input id="cb'+attr+attrValue.replace(/&quot;/g,"\"")+'" type=checkbox class="filterBox" Checked OnClick="applyFilter(\'color-'+attrValue+'\',\'All\',false);">&nbsp;<a href="javascript:applyFilter(\'color-'+attrValue+'\',\'All\',false);"><img src="http://site.invitationbox.com/images/filters/imgFilterColor-'+attrValue.replace('/','').replace(/ /g,'').toLowerCase()+'.gif" border=0>' + attrValue + ' (' + colorCount + ')</a></div>';
			} else {
				html += '<div class=filterCell><input id="cb'+attr+attrValue.replace(/&quot;/g,"\"")+'" type=checkbox class="filterBox" OnClick="applyFilter(\'color-'+attrValue+'\',\'' + escapeQuotes(attrValue) + '\',false);">&nbsp;<a href="javascript:applyFilter(\'color-'+attrValue+'\',\'' + escapeQuotes(attrValue) + '\',false);"><img src="http://site.invitationbox.com/images/filters/imgFilterColor-'+attrValue.replace('/','').replace(/ /g,'').toLowerCase()+'.gif" border=0>' + attrValue + ' (' + colorCount + ')</a></div>';
			}
		}
	}
	html += '</div></div>';
	
	return html;
}

function createFilter(attr, titleStr, maxItems, startClosed) {
	var html = '<div class="filterDiv"><div class="filterExpander'+ (startClosed?' expandClosed':'') +'"><img class="expander left" src="http://static.invitationbox.com/images/icoLN_Minus.png">&nbsp;<span class="filterTitle left">Filter By '+titleStr+'</span></div><div class="filterContainer clearFloat">';
	var allowEmptyValues = true;
	var attrValues = getItemValues(attr, allowEmptyValues);
	var attrValue;
	var numAttributes = assocArraySize(attrValues);
	
	if (numAttributes)	{ 
		var attrValues = ksort(attrValues);
		var topAttrValues = getTopAttrValues(attrValues, attr);		
		var cx = 0;

		for (attrValue in attrValues)	{
			if (! isAttrLinkHidden(attrValue, topAttrValues) && cx < maxItems) {
				if (_pagingState.filters[attr] == attrValue.replace(/&quot;/g,"\"")) {
					html += '<div class=filterCell><input id="cb'+attr+attrValue.replace(/&quot;/g,"\"")+'" type=checkbox Checked class="filterBox" OnClick="applyFilter(\''+attr+'\',\'All\',false);">&nbsp;<a href="javascript:applyFilter(\''+attr+'\',\'All\',false);">' + attrValue + ' (' + attrValues[attrValue] + ')</a></div>';
				} else {
					html += '<div class=filterCell><input id="cb'+attr+attrValue.replace(/&quot;/g,"\"")+'" type=checkbox class="filterBox" OnClick="applyFilter(\''+attr+'\',\'' + escapeQuotes(attrValue) + '\',false);">&nbsp;<a href="javascript:applyFilter(\''+attr+'\',\'' + escapeQuotes(attrValue) + '\',false);">' + attrValue + ' (' + attrValues[attrValue] + ')</a></div>';
				}
				cx++;
			}
		}
	}				
	html += '</div></div>';
	
	return html;
}

function createMultiFilter(attr, titleStr, sepChar, numItemsToShow, useDropDown, startClosed) {
	var html = '<div class="filterDiv"><div class="filterExpander'+ (startClosed?' expandClosed':'') +'"><img class="expander left" src="http://static.invitationbox.com/images/icoLN_Minus.png">&nbsp;<span class="filterTitle left">Filter By '+titleStr+'</span></div><div class="filterContainer clearFloat">';
	var allowEmptyValues = true;

	var attrValues = getItemDelimitedValues(attr, allowEmptyValues,sepChar);
	var attrValue; 
	var numAttributes = assocArraySize(attrValues);
	var dropDown = "<select class='filterDropDown' onchange='applyFilter(\""+attr+"-\"+this.options[this.selectedIndex].value,escapeQuotes(this.options[this.selectedIndex].value),false);'><option value='All'>--- View All Themes ---</option>";

	if (numAttributes)	{ 
		var attrValues = ksort(attrValues);
		var topAttrValues = getTopAttrValues(attrValues, attr);
	
		var cx = 0;
		var maxItems = numItemsToShow;
		
		for (attrValue in attrValues)	{
			if (! isAttrLinkHidden(attrValue, topAttrValues) && cx < maxItems) {
				if (_pagingState.filters[attr +'-'+attrValue] == attrValue.replace(/&quot;/g,"\"")) {
					html += '<div class=filterCell><input type=checkbox Checked class="filterBox" OnClick="applyFilter(\''+attr+'-'+escapeQuotes(attrValue)+'\',\'All\',false);">&nbsp;<a href="javascript:applyFilter(\''+attr+'-'+escapeQuotes(attrValue)+'\',\'All\',false);">' + attrValue + ' (' + attrValues[attrValue] + ')</a></div>';
				} else {
					html += '<div class=filterCell><input type=checkbox class="filterBox" OnClick="applyFilter(\''+attr+'-'+escapeQuotes(attrValue)+'\',\'' + escapeQuotes(attrValue) + '\',false);">&nbsp;<a href="javascript:applyFilter(\''+attr+'-'+escapeQuotes(attrValue)+'\',\'' + escapeQuotes(attrValue) + '\',false);">' + attrValue + ' (' + attrValues[attrValue] + ')</a></div>';
				}
				cx++;
			}
			dropDown += "<option value=\"" + attrValue + "\">" + attrValue + " (" + attrValues[attrValue] + ")</option>";
		}
		if (cx >=  maxItems && useDropDown) {
			html += '<div class=filterCell>REPLACE_DD</div>';
		}
	}	
	
	if (useDropDown) {
		dropDown += "<option value='All'>View All</option></select>";
		html = html.replace('REPLACE_DD',dropDown);
	}
				
	html += '</div></div>';
	
	return html;
}

function isAttrLinkHidden(attrValue, topAttrValues) {
	return (typeof topAttrValues[attrValue] == "undefined");		
}

function escapeQuotes(val) {
	return val.replace(/'/, "\\'");
}

function getItemValues(attr, allowEmptyValues) {
	var values = new Array();
	for (var i = 0; i < window.items.length; i++) {
		var it = 	window.items[i];
		var val = it[attr];

		if (val.length == 0) {
			if (!allowEmptyValues)
				continue;
			else 
				val = 'Other';
		}
		
		var count = (values[val]) ? values[val] : 0;
		values[val] = count + 1;
	}	
	
	return values;
}

function getItemDelimitedValues(attr, allowEmptyValues, delimChar) {
	var values = new Array(); //array to hold all values and their count	
	for (var i = 0; i < window.items.length; i++) {
		var it = 	window.items[i];
		var val = it[attr];

		if (val) {
			if (val.length == 0) {
				if (!allowEmptyValues)
					continue;
				else 
					val = 'Other';
			}
		} else {
			continue;
		}

		var separatedValues = val.split(delimChar);
		for (var idx = 0; idx < separatedValues.length; idx++) {
			var count = (values[separatedValues[idx]]) ? values[separatedValues[idx]] : 0;
			values[separatedValues[idx]] = count + 1;
		}
	}	

	return values;
}

function getItemColorValues() {
	var values = new Array(); 
	for (var i = 0; i < window.items.length; i++) {
		var it = 	window.items[i];
		var val = it['primarycolor'];
		values[val] = ((values[val]) ? values[val] : 0) + 1;
		val = it['secondarycolor'];
		values[val] = ((values[val]) ? values[val] : 0) + 1;
		val = it['thirdcolor'];
		values[val] = ((values[val]) ? values[val] : 0) + 1;
	}	

	return values;
}

function getBooleanFilters(viewallthistime) {
	var html = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';

	html += getBooleanFilter('Sale Items', 'onsale', viewallthistime, itemsAreOnSale);

	var ssfilter = getBooleanFilter('Super Sale Items', 'showsupersalepricing', viewallthistime);

	if ( ssfilter.indexOf('DISABLED') <= -1 ) {
		html += ssfilter;
	}

	html += getBooleanFilter('Top Sellers', 'topseller', viewallthistime);
	html += getBooleanFilter('What\'s New', 'newitem', viewallthistime);
	html += getBooleanFilter('Quick Ship', 'quickship', viewallthistime);
	html += getBooleanFilter('InvitationBox Green', 'green', viewallthistime);
	
	return html;
}

function getBooleanFilter(label, attr, viewallthistime, itemsHaveBooleanValueCallback) {
	var html = '';
	var num;
	
	if (!itemsHaveBooleanValueCallback)
		itemsHaveBooleanValueCallback = itemsHaveBooleanValue;
		
	num = itemsHaveBooleanValueCallback(attr);
	
	if (_pagingState.filters[attr]) { 
		html += '<a javascript="applyFilter(\'' + attr + '\', \'All\',' + viewallthistime + ');">&nbsp;<a class="'+attr+'Filter" alt="View '+label+'" href="javascript:applyFilter(\'' + attr + '\', \'All\',' + viewallthistime + ');"><img class="valignCenterIcon hoverChange" src="http://static.invitationbox.com/images/ico-'+attr+'_on.png"></a>';
	}	else {
		num = (typeof(num) == 'undefined') ? 0 : num;
		if (num > 0) {
			html += '<a class="'+attr+'Filter" href="javascript:applyFilter(\'' + attr + '\', true,' + viewallthistime + ');"><img alt="View '+label+'" class="valignCenterIcon hoverChange" src="http://static.invitationbox.com/images/ico-'+attr+'_off.png"></a>';
		} 
	}
	
	return html;
}
	
function itemsHaveBooleanValue(attr) {		
	var values = getItemValues(attr);
	
	if (assocArraySize(values) == 0) {
		return 0;
	}
	
	return values[true];	
}

function itemsAreOnSale() {
	var count = 0;
	
	for (var i = 0; i < window.items.length; i++) {
		var it = 	window.items[i];
		if (isSaleItem(it))
			count++;
	}	
	
	return count;
}

function getTopAttrValues(arr,attr) {
	attributeLimiter = 10; 
	if (attr == 'theme') attributeLimiter = 13;
	if (attr == 'brand') attributeLimiter = 100;
	var newArr = new Array();
	var i = 0;
	
	arr = assocArraySort(arr, numericCompareValueDesc);	
	
	for (var key in arr) {
		if (i++ >= attributeLimiter)
			break;
		newArr[key] = arr[key];
	}
	return newArr;
}

function assocArraySize(arr) {
	var l = 0;
	for (var k in arr) {
		l++;
	}
	return l;
}

function ksort(arr) {
	return assocArraySort(arr, alphaCompareKey);
}

function assocArraySort(aInput, compareFunction) {
	var aTemp = [];
	for (var sKey in aInput)
		aTemp.push([sKey, aInput[sKey]]);

	//sort the multi indexed array
	if (!compareFunction)
		compareFunction = function () { return arguments[1][1] > arguments[0][1]}

	aTemp.sort(compareFunction);

	//convert back to an assoc array
	var aOutput = [];
	for (var nIndex = aTemp.length - 1; nIndex >=0; nIndex--)
		aOutput[aTemp[nIndex][0]] = aTemp[nIndex][1];
		
	return aOutput;
}

function alphaCompare(a, b) {
	var A = a.toLowerCase();
	var B = b.toLowerCase();
	if (A < B) return -1;
	if (A > B) return 1;
	return 0;
}

function alphaCompareKey(a, b) {
	var A = a[0].toLowerCase();
	var B = b[0].toLowerCase();
	//console.log("A=%s, B=%s", A, B);
	if (A < B) return 1;
	if (A > B) return -1;
	return 0;
}

function numericCompareValueDesc(a, b) {
	return a[1] - b[1];
}

function loadjscssfile(filename, filetype){
	if (filetype=="js"){
		var fileref=document.createElement('script')
		fileref.setAttribute("type","text/javascript")
		fileref.setAttribute("src", filename)
	} else if (filetype=="css") { 
		var fileref=document.createElement("link")
		fileref.setAttribute("rel", "stylesheet")
		fileref.setAttribute("type", "text/css")
		fileref.setAttribute("href", filename)
	}
	
	if (typeof fileref!="undefined")
		document.getElementsByTagName("head")[0].appendChild(fileref)
}

function getParameterByName( name ) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
