$(document).ready(function() {								
	doYoThangCookieMonster();
	click2chat();
	testimonial_cycle();	
	systemMessageInit({                                 
		//'FreeShipCode' : 'HOLSHIP09',
		//'BannerImagePath' : '/images/00_persistent/freeshipping_red.jpg',
		//'BannerImageDesc' : '2009 SmartPak Holiday Free Shipping Promotion'
		//'BannerImageDest' :	'doomsday.php',
		//'PromoType' : 'all'
		});
	productReferral({                                 
		'productClassID' : '7735',
		'relatedProducts' : '7457'
		})
	$(".searchMain input").focus(function () {
		$('input.s').keypress(function(e) {
			//alert(e.keyCode);
			if(e.keyCode == 13) { $('.searchMain a.b').click(); }
			});
		});
	if ($('#pnlSuggest').find('ul').children('li').length == 0) { $('#pnlSuggest').hide(); }
	});
////////////////////////////////////////////////////////////////////
//       BEGIN RECENTLY VIEWED PROJECTS (cookieMonster.js)
////////////////////////////////////////////////////////////////////
/* 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(pvgOptions) {
	var default_args = {
		'view'		:	"list",
		'gridCount' : 	4
		}
	if (pvgOptions["items"] && pvgOptions["conID"]) {
		for(var index in default_args) {if(typeof pvgOptions[index] == "undefined") pvgOptions[index] = default_args[index];}
		data = pvgOptions["items"];
		$.getJSON("/Services/ProductClass.svc/productClasses/"+pvgOptions["items"],function(data){
			if (pvgOptions["view"] == "list") {
				var pvgOutput = '<ul class="productList">';
				$.each(data, 
					   function(i,item){
							plAltTitle = rvpCleanTitle(item.Title,"alt");
							if (pvgOptions["cm"]) {plSafeTitle = rvpCleanTitle(item.Title,"cm"); plCoreTag = '&cm_sp='+pvgOptions["cm"]+plSafeTitle;} else {plCoreTag = '';}													  
							pvgOutput += "<li><a href='/ProductClass.aspx?productclassid="+item.Id+plCoreTag+"'><img src='http://img.smartpak.com/product/thumbnails/"+item.Image+"' alt='"+plAltTitle+"' /></a><a href='/ProductClass.aspx?productclassid="+item.Id+plCoreTag+"'>"+item.Title+"</a><span class='price'>"+item.Price+"</span></li>";
							});
				pvgOutput += '</ul>';
				}
			else if (pvgOptions["view"] == "grid") {
				var pvgOutput = '<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 (pvgOptions["cm"]) {plSafeTitle = rvpCleanTitle(item.Title,"cm"); plCoreTag = '&cm_sp='+pvgOptions["cm"]+plSafeTitle;} else {plCoreTag = '';}														   
							if (c == 1) {pvgOutput += '<tr valign="top">';}
							pvgOutput += '<td><a href="/ProductClass.aspx?productclassid='+item.Id+plCoreTag+'"><img src="http://img.smartpak.com/product/thumbnails/'+item.Image+'" alt="'+plAltTitle+'" /></a><a href="/ProductClass.aspx?productclassid='+item.Id+plCoreTag+'"><br />'+item.Title+'</a><br /><span class="price">'+item.Price+'</span></td>';
							if (c % pvgOptions["gridCount"] == 0) {pvgOutput += '</tr>'; c = 0;} c++;
						   });
				pvgOutput += '</tbody></table>';					
				}
			$(pvgOutput).prependTo("#"+pvgOptions["conID"]+"");
			});
		}
	}		
////////////////////////////////////////////////////////////////////
//       END RECENTLY VIEWED PROJECTS (cookieMonster.js)
////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////
//       BEGIN TABLE OF CONTENTS
////////////////////////////////////////////////////////////////////
function aboutTOC() {
	var tocHead = '<h2>The Highlights</h2>';
	var btt = '<a class="inlineButton" href="#top">Back to Top</a>';
	var aboutTOC = '<ul id="start">';
	$('.aboutInt h2, .aboutInt h3').each(function() {
		//alert($(this).text());
		var prevTag = '';														  				
		var nextTag = '';
		var thisTag = $(this).get(0).tagName.toLowerCase();
		var text = $(this).text();
		var textStripped = text.replace(/[-!"#$%&'()*+,.\/:;<=>?@\[\\\]_`{|}~]/g,""); 
			textStripped = textStripped.replace(/\s/g,"_");
		var previous = $(this).prevAll(':header:first').each(function(){ prevTag = $(this).get(0).tagName.toLowerCase(); });
		var next = $(this).nextAll(':header:first').each(function(){ nextTag = $(this).get(0).tagName.toLowerCase(); });
		var theLink = '<a href="#'+textStripped+'">'+text+'</a>';				
		
		if (thisTag == 'h2') {
			if (((prevTag == 'h2') && (nextTag == 'h3')) || ((prevTag == '') && (nextTag == 'h3'))) { aboutTOC += '<li>'+theLink+'</li><ul>'; }					
			else if ((prevTag == 'h3') && (nextTag == 'h3')) { aboutTOC += '</ul><li>'+theLink+'</li><ul>'; }
			else if ((prevTag == 'h3') && (nextTag == 'h2')) { aboutTOC += '</ul><li>'+theLink+'</li>'; }
			else { aboutTOC += '<li>'+theLink+'</li>'; } 
			$(btt).prependTo(this);					
			}
		else if (thisTag == 'h3') { aboutTOC += '<li>'+theLink+'</li>'; }					
		
		//aboutTOC += '<li>'+theLink+'</li>'
		$(this).attr('id',textStripped);
	});
	aboutTOC += '</ul>';
	//alert(aboutTOC);
	$(aboutTOC).prependTo('#aboutTOC');
	$(tocHead).prependTo('#aboutTOC');
	}
////////////////////////////////////////////////////////////////////
//       END TABLE OF CONTENTS
////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////
//       BEGIN PPC CHECK (BANNER INJECTOR)
////////////////////////////////////////////////////////////////////	
function systemMessageInit(systemMsgOptions) {
	// Build System Message Variable	
	var noteWelcome = '<div class="systemMsg"><span>Welcome %%CHANNEL%% Customers</span></div>';
	var noteDB = '<div class="systemMsg minus"><span>We cannot ship your current order until you <a href="/secure/ChangeCreditCard.aspx">update</a> your credit card.</span></div>';
	var noteFreeShipTxt = '<div class="systemMsg plus"><span>%%CHANNEL%% customers receive <em>free shipping</em>! Use promo code <strong>%%PROMOCODE%%</strong> at checkout.</span></div>';
	var noteFreeShipImg = '<div class="systemMsg img"><a href="%%DESTINATION%%"><img src="%%IMAGEPATH%%" alt="%%DESCRIPTION%%" /></a></div> ';                   
	var messageBuild ='';
	var CurURL = location.href.toLowerCase();
	var refURL = document.referrer.toLowerCase();
	var dgt_status = readCookie("spe_dg");
	if (CurURL.indexOf("google-_-") > -1) {var channel = "Google";}
	else if (CurURL.indexOf("yahoo-_-") > -1) {var channel = "Yahoo!";}
	else if (CurURL.indexOf("msn-_-") > -1) {var channel = "MSN";}
	else if ((CurURL.indexOf("cothbigbanner-_-") > -1) || (refURL.indexOf("chronofhorse.com") > -1)) {var channel = "Chronicle of the Horse";}
	else if	(systemMsgOptions['PromoType'] == "all") {var channel = "SmartPak";};
	//var str = CurURL;  var re = "/cf_[A-Za-z0-9]{6}/"; re = eval(re); var check = str.search(re); var flag = CurURL.substring(check,check+9);
	// Build System Messages		
	if (systemMsgOptions['BannerImagePath'] && systemMsgOptions['BannerImageDesc'] && systemMsgOptions['BannerImageDest']) { var noteShipImg_all = noteFreeShipImg.replace(/%%DESTINATION%%/g, systemMsgOptions['BannerImageDest']).replace(/%%IMAGEPATH%%/g, systemMsgOptions['BannerImagePath']).replace(/%%DESCRIPTION%%/g, systemMsgOptions['BannerImageDesc']); messageBuild += noteShipImg_all; }
	else if (systemMsgOptions['FreeShipCode']) {
		if (channel) { var noteFreeShipTxt_ppc = noteFreeShipTxt.replace(/%%CHANNEL%%/g, channel).replace(/%%PROMOCODE%%/g, systemMsgOptions['FreeShipCode']); messageBuild += noteFreeShipTxt_ppc; }		
		}
	else if (channel) {
		var flag = 'cf_9b8dpo';	
		if (CurURL.indexOf(flag) > -1) { 
				messageBuild = geoTargetCode(channel,flag,messageBuild);				
			}
		else { var noteWelcome_ppc = noteWelcome.replace(/%%CHANNEL%%/g, channel); messageBuild += noteWelcome_ppc; }
		}			
	else if (dgt_status) {
		var cookieArray = dgt_status.split('|');
		var channel = cookieArray[0];
		var flag = cookieArray[1];
		messageBuild = geoTargetCode(channel,flag,messageBuild);
		}
	// Deliver System Messages
	if (messageBuild) { $("div.systemMsgCon").prepend(messageBuild); }		
	}
function productReferral (productRefOptions) {
	var CurURL = location.href.toLowerCase();
	if (CurURL.indexOf("productclassid="+productRefOptions['productClassID']) > -1) {
		var suggestHTML = '<div class="productSuggestBanner"><div class="productSuggestQ"><h2>Are you looking for...</h2></div><div id="prodRefSuggest" class="productSuggestR"></div></div>';	
		$(".systemMsgCon").append(suggestHTML);
			buildMyProducts({                                            
				'items'	:	productRefOptions['relatedProducts'],
				'conID' : 	"prodRefSuggest",
				'cm' 	:	"PVG-_-ProductClass-_-"
				});                    
		}	
	}
function geoTargetCode(channel,flag,messageBuild) {
	/*
		Set dgt_start to Epoch Time of Campaign Start Date for Current Year 
		http://www.esqsoft.com/javascript_examples/date-to-epoch.htm
	*/
	var dgt_start = 1262494800;
	//var dgt_start = 1230958800;
	var dgt_weekInt = 604800;
	var dgt_curDate = new Date().getTime();
	var dgt_curDate = Math.floor(dgt_curDate/1000);
	
	var dgt_dateVar = dgt_curDate - dgt_start;
	if (dgt_dateVar > 0) {
		var dgt_weekNum = Math.floor(dgt_dateVar/dgt_weekInt) + 1;
		if (dgt_weekNum) {
			var the_goods = new Array("%66%73%67%74%64%73","%64%73%66%73%31%30","%31%37%67%74%66%73","%66%73%63%32%34","%66%73%64%73%33%30","%32%36%67%74%64%73","%70%63%66%73%31%30","%67%74%7A%66%73%33","%32%30%31%30%66%73%63%64%73","%7A%63%66%73%64%73","%66%72%65%65%73%68%69%70%30%33", "%73%70%72%69%6E%67%66%73%30%33", "04%66%73%74%67", "%66%73%61%70%72%69%6C%31%30", "%30%34%61%70%72%69%6C%66%73", "%66%73%67%74%32%30%31%30", "%6D%61%79%66%73%31%30", "%66%73%73%70%72%69%6E%67%30%35", "05%73%70%66%73", "%66%73%6D%61%79%30%35", "%66%73%30%35%32%30%31%30");
			var the_answer_you_seek = the_goods[dgt_weekNum - 1];
			if (the_answer_you_seek) {
				the_answer_you_seek = decodeURI(the_answer_you_seek);
				var dgt_nextCycle = new Date();
				dgt_nextCycle.setTime( ((dgt_start + (dgt_weekInt * (dgt_weekNum + 1)))*1000)+68400000);						
				document.cookie = "spe_dg="+channel+"|"+flag+"; expires="+dgt_nextCycle.toGMTString()+"; path=/";
				writeAnotherSysMsg('text',the_answer_you_seek,channel);			
				}
			}
		}
	}
function writeAnotherSysMsg(type, code, channel) {
	var wpcTxt = '<div class="systemMsg wpc"><span>You qualify for <em>free shipping</em> until this Sunday at midnight!<br /> Use promo code <strong>%%PROMOCODE%%</strong> at checkout.</span></div>';		
	var wpcTxt = wpcTxt.replace(/%%PROMOCODE%%/g, code); 
	messageBuild = wpcTxt;
	$("div.systemMsgCon").prepend(messageBuild);
	}
	//writeAnotherSysMsg('text','hi','google');
////////////////////////////////////////////////////////////////////
//       END PPC CHECK (BANNER INJECTOR)
////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////
//       BEGIN CLICK TO CHAT
//////////////////////////////////////////////////////////////////// 
var chatURL = '/Chat.aspx';
var CurChatURL = location.href.toLowerCase();
function agents_available(url) {	 
	$('#chatButton_Head')
		.removeClass('chat_off')
		.addClass('chat_on')
		.removeAttr('href')
		.click( function () { window.open(chatURL,'custclient','width=600,height=340,scrollbars=0,resizable=0,menubar=0,toolbar=0,status=0,location=0'); });
	$('#chatButton_Sidebar')
		.removeClass('chat_off')
		.addClass('chat_on')
		.removeAttr('href')
		.click( function () { window.open(chatURL,'custclient','width=600,height=340,scrollbars=0,resizable=0,menubar=0,toolbar=0,status=0,location=0'); });
	return true;
	}
function agents_not_available() {
	//alert('not avail');
	return true;
	}		
function click2chat () {
	if (CurChatURL.indexOf("https") > -1) { var chatSecure = "https";} else { var chatSecure = "http";}
	/*
	$.ajax({ 
		url: 'http://admin.instantservice.com/resources/smartbutton/5984/16175/available.gif?'+Math.floor(Math.random()*10001),
		type: 'get',
		error: function() { agents_not_available(chatURL); },
		success: function() { agents_available(chatURL); }
		})
	*/
	$("body").append('<img src="'+chatSecure+'://admin.instantservice.com/resources/smartbutton/5984/16175/available.gif?'+Math.floor(Math.random()*10001)+'" style="width:0;height:0;visiblity:hidden;position:absolute;" onLoad="agents_available()" onError="agents_not_available()" />');	
	}
////////////////////////////////////////////////////////////////////
//       END CLICK TO CHAT
////////////////////////////////////////////////////////////////////	

////////////////////////////////////////////////////////////////////
//       BEGIN COUNTDOWN TIMER
////////////////////////////////////////////////////////////////////	
function calcage(secs, num1, num2) {
	s = ((Math.floor(secs/num1))%num2).toString();
	if (LeadingZero && s.length < 2)
		s = "0" + s;
	return "<b>" + s + "</b>";
	}

function CountBack(secs) {
	if (secs < 0) {
		$('span#cntdwn').html(FinishMessage);
		return;
		}
	DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs,86400,100000));
	DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs,3600,24));
	DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs,60,60));
	DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60));
	
	$('span#cntdwn').html(DisplayStr);
	if (CountActive)
		setTimeout("CountBack(" + (secs+CountStepper) + ")", SetTimeOutPeriod);
	}

function putspan() {
	var timerSpan = "<span id='cntdwn'></span>";
	$(timerSpan).prependTo(ParentID);
	}

function startCountdown(timerOptions) {
	var counter_default_args = {
		'TargetDate' : '12/31/2020 5:00 AM',
		'DisplayFormat' : "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds",
		'CountActive' : true,
		'FinishMessage' : "",
		'CountStepper' :  -1,
		'LeadingZero' : true,
		'ParentID' : '.mainContent'
		}
	for(var index in counter_default_args) {if(typeof timerOptions[index] == "undefined") timerOptions[index] = counter_default_args[index];}
		TargetDate = timerOptions['TargetDate'];
		CountActive = timerOptions['CountActive'];
		CountStepper = timerOptions['CountStepper'];
		LeadingZero = timerOptions['LeadingZero'];
		DisplayFormat = timerOptions['DisplayFormat'];
		FinishMessage = timerOptions['FinishMessage'];
		ParentID = timerOptions['ParentID'];
	
	CountStepper = Math.ceil(CountStepper);
	if (CountStepper == 0)
	  CountActive = false;
	SetTimeOutPeriod = (Math.abs(CountStepper)-1)*1000 + 990;
	putspan();
	var dthen = new Date(TargetDate);
	var dnow = new Date();
	if(CountStepper>0)
	  ddiff = new Date(dnow-dthen);
	else
	  ddiff = new Date(dthen-dnow);
	gsecs = Math.floor(ddiff.valueOf()/1000);
	CountBack(gsecs);
	}
////////////////////////////////////////////////////////////////////
//       END COUNTDOWN TIMER
////////////////////////////////////////////////////////////////////	

////////////////////////////////////////////////////////////////////
//       BEGIN TESTIMONIAL CYCLE
////////////////////////////////////////////////////////////////////

function testimonial_cycle() {
	num = 0;
	testimonial_trigger('start');
	$('li[class^="testimonial"]').bind("mouseenter", function(e){ testimonial_trigger('stop'); });
	$('li[class^="testimonial"]').bind("mouseleave", function(e){ testimonial_trigger('start');	});	
	var CurURL = location.href.toLowerCase();
	if (CurURL.indexOf('testimonials.aspx') > -1) {
		str = CurURL; re = "/#[0-9]+$/"; re = eval(re); check = str.search(re); flag = CurURL.substring(check+1,check+4);
		flag = flag.replace(' ','');
		$('a[name="'+flag+'"]').parents('td:first').addClass('test_hi_lite');
		}	
	}
function testimonial_trigger(flag) {
	if ($('li[class^="testimonial"]').length > 0) {
		switch(flag) {
			case 'start': testimonial_timer = setInterval ( function(){ testimonial_change(num); }, 7000); break;
			case 'stop': clearTimeout(testimonial_timer); break;
			}
		}	
	}
function testimonial_change(current) {
	var test_count = $('li[class^="testimonial"] li').length;	
	num = (Math.floor(Math.random()*(test_count-1))+1);	
	if (num == current) {
		if (num == test_count) { num = num-1; }
		else { num = num+1; }
		}
	var fadeInt = 500;
	$('li[class^="testimonial"] li:visible').fadeOut(fadeInt,function(){ $('li[class^="testimonial"] li:nth-child('+num+')').fadeIn(fadeInt); });
	}

////////////////////////////////////////////////////////////////////
//       END TESTIMONIAL CYCLE
////////////////////////////////////////////////////////////////////		   