/* INITIALIZE */
function doYoThangCookieMonster() {
    
	var CurURL = location.href;
	var rvTest = readCookie("speRecentlyViewed");		
	//This is where we edit the viewed items list
	var pageTypeTest = findTheZone();
	if (pageTypeTest == "ProductClass") {
		var randomNum = getValue("productclassid");
		if (rvTest) {
		    var newArray = processTheArray(rvTest);

		    var newArrayTest = jQuery.inArray(randomNum, newArray);

		    if (newArrayTest >= 0) {
				if (newArrayTest > 0) {
					newArray.splice(newArrayTest,1);					
					recentViewUpdate(newArray,randomNum);										
					}				
				}
			else {
				recentViewUpdate(newArray,randomNum);
				}			
			}
		else{recentViewNewCookie(randomNum);}
		}
	//This is where we write the widget to the DOM
	if (rvTest) {
		if ($("#recentViewCon").length > 0) {
			recentViewWrite(rvTest);
			}	
		}	
	}

/* WIDGET CONTROLLERS */
function recentViewWrite(rvTest) {
	var newArray = processTheArray(rvTest);
	var newVar = "";
	var rvpZoneName = findTheZone();
	for (var i in newArray){
		newVar += newArray[i]+"|";
		}			
	$.getJSON("/Services/ProductClass.svc/productClasses/"+newVar,function(data){
		var output = '<div class="grayWidget listWidget"><div class="widgetCon"><div class="widgetTop"><div class="widgetBot"><h2>Your Recently Viewed Items</h2><ul>';
		$.each(data, function(i,item){var rvpSafeTitle = rvpCleanTitle(item.Title,"cm"); rvpAltTitle = rvpCleanTitle(item.Title,"alt"); output += "<li><a href='/ProductClass.aspx?productclassid="+item.Id+"&cm_sp=RVP-_-"+rvpZoneName+"-_-"+rvpSafeTitle+"'><img src='http://img.smartpak.com/product/thumbnails/"+item.Image+"' alt='"+rvpAltTitle+"' />"+item.Title+"</a><span class='price'>"+item.Price+"</span></li>";});
		output += '</ul></div></div></div></div>';
		$(output).prependTo("#recentViewCon");
		});	
	}
function recentViewUpdate(newArray,randomNum){
	newArray.unshift(randomNum);
	if (newArray.length < 3) {var arrayLimit = newArray.length;}
	else {var arrayLimit = 3;}
	var finalArray = new Array();
	var i=0;
	for (i=0;i<=(arrayLimit-1);i++){
		popped = newArray.shift();
		finalArray.unshift(popped);
		}			
	createCookie("speRecentlyViewed",finalArray,90);
	newArray = [];finalArray = [];
	}
function recentViewNewCookie(randomNum){
	var rvArray = new Array(randomNum);
	createCookie("speRecentlyViewed",rvArray,90);	
	}
function getValue(varname) {
	varname = varname.toLowerCase();
	var url = location.href;
	var qparts = url.split("?");
	if (qparts.length == 0) {
		return "";
		}
	var query = qparts[1];
	var vars = query.split("&");
	var value = "";
	for (i=0;i<vars.length;i++) {
		var parts = vars[i].split("=");
		partsTest = parts[0].toString();
		partsTest = partsTest.toLowerCase();
		if (partsTest == varname) {
			value = parts[1];
			break;
			}
		}
	value = unescape(value);
	value.replace(/\+/g," ");
	return value;
	}
function processTheArray(rvTest) {
	    newArray = rvTest.split(",");
	    newArray.reverse();	    
	return newArray;
	}
function findTheZone() {
	var CurURL = location.href;
	CurURL = CurURL.toLowerCase();
	if ((CurURL.indexOf("productclass.aspx") > -1)) {var pageType = "ProductClass";}
	else if ((CurURL.indexOf("basket.aspx") > -1)) {var pageType = "Cart";}
	else {var pageType = "Home";}
	return pageType;
	}
function rvpCleanTitle(text,flag) {	
	if (flag == "cm") {text = text.replace(/\s/g,"_"); text = text.replace(/<[A-Za-z0-9]+[^>]*>|<\/[A-Za-z0-9]+[^>]*>/g,"");}
	text = text.replace(/<sup>|<\/sup>|&reg;|&trade;|\'|\"|<[A-Za-z0-9]+[^>]*>|<\/[A-Za-z0-9]+[^>]*>/g,"");
	return text;
	}

/* COOKIE CONTROLLERS */
function createCookie(name,value,days) {
	//alert("We are creating a cookie");
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
	}

function readCookie(name) {
	//alert("We read a cookie");
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
	}

function eraseCookie(name) {
	//alert("We erased a cookie");
	createCookie(name,"",-1);
	}	

/* OTHER PRACTICAL USES OF THIS WIDGET */
function buildMyProducts(options) {
	var default_args = {
		'view'		:	"list",
		'gridCount' : 	4
		}
	if (options["items"] && options["conID"]) {
		for(var index in default_args) {if(typeof options[index] == "undefined") options[index] = default_args[index];}
		data = options["items"];
		$.getJSON("/Services/ProductClass.svc/productClasses/"+options["items"],function(data){
			if (options["view"] == "list") {
				var output = '<ul class="productList">';
				$.each(data, 
					   function(i,item){
							plAltTitle = rvpCleanTitle(item.Title,"alt");
							if (options["cm"]) {plSafeTitle = rvpCleanTitle(item.Title,"cm"); plCoreTag = '&cm_sp='+options["cm"]+plSafeTitle;} else {plCoreTag = '';}													  
							output += "<li><a href='/ProductClass.aspx?productclassid="+item.Id+plCoreTag+"'><img src='http://img.smartpak.com/product/thumbnails/"+item.Image+"' alt='"+plAltTitle+"' /></a><a href='http://www.smartpakequine.com/ProductClass.aspx?productclassid="+item.Id+plCoreTag+"'>"+item.Title+"</a><span class='price'>"+item.Price+"</span></li>";
							});
				output += '</ul>';
				}
			else if (options["view"] == "grid") {
				var output = '<table cellpadding="5" cellspacing="0" border="0" width="100%" class="productList"><tbody>';
				c = 1;
				$.each(data, 
					   function(i,item){						   
							plAltTitle = rvpCleanTitle(item.Title,"alt");
							if (options["cm"]) {plSafeTitle = rvpCleanTitle(item.Title,"cm"); plCoreTag = '&cm_sp='+options["cm"]+plSafeTitle;} else {plCoreTag = '';}														   
							if (c == 1) {output += '<tr valign="top">';}
							output += '<td><a href="/ProductClass.aspx?productclassid='+item.Id+plCoreTag+'"><img src="http://img.smartpak.com/product/thumbnails/'+item.Image+'" alt="'+plAltTitle+'" /></a><a href="http://www.smartpakequine.com/ProductClass.aspx?productclassid='+item.Id+plCoreTag+'"><br />'+item.Title+'</a><br /><span class="price">'+item.Price+'</span></td>';
							if (c % options["gridCount"] == 0) {output += '</tr>'; c = 0;} c++;
						   });
				output += '</tbody></table>';					
				}
			$(output).prependTo("#"+options["conID"]+"");
			});
		}
	}		
