// JavaScript Document
var ISCUST = '';

var myURL = document.URL;
myURL = myURL.toLowerCase(); 


$(document).ready(function() {
	ISCUST = $.cookie('CustomerID');
	getVolusionPageType (myURL);
	makeMegaMenu ();
	cartSummary ();
	autoFill('#topSearch input', "Search for Keyword(s)", "#83b6ec");
	$.superbox();
	$('input').bind('focusin focusout',function() {
		$(this).toggleClass("inputFocus");
	});
 });

function catDescriptionCntrl () {
	$('.cdToggle').hide().find('h1').before('<a id="closeDescr" class="button small orange" href="#">[x] Close</a>');
	$('#closeDescr').live('click', function(e) {
		e.preventDefault();
		$('.cdToggle').slideUp();
		$('.moreCatDesc').parent().fadeIn();
	});
	$('.moreCatDesc').click( function (e) {
		e.preventDefault();
		$('.cdToggle').show('fast');
		$(this).parent().hide();
	});
}
//get page type
function getVolusionPageType (myURL) {
	var myPageType = "unknown";
	if (myURL.search(/-s\/[^<]+?.htm/) > 0) {
		myPageType = "category";
		createPadding ();
		$('#myContentArea table').eq(0).wrap('<div id="productWrap"></div>');
		$('#myContentArea').append('<div id="sideMiniCart"></div>');
		$('#myContentArea').closest('table').attr('cellspacing','0');
		$('#content_area').width(980);
		setUpBreadCrumbs ();
		setUpSubCategory ();
		setUpSoftAdd ();
		$('#sideMiniCart').stickyfloat({ duration: 600 });
		quickCart ();
		addBGImage ();
		$('.colors_productprice:contains("Sale Price")').closest('td').addClass('saleTD');
		$('.saleTD .colors_text').addClass('salePriceSlash');
		$('.saleTD').append('<div class="onSale"></div>');
		catDescriptionCntrl ();
		$('.refinement_brand_section').closest('td').children('select').addClass('sRefine');
		$('.sRefine').appendTo('.refinement_brand_section:eq(0)');
	} else {
		//subNavHide ();
		
	}
	
	if (myURL.search(/-p\/[^<]+?.htm/) > 0 | myURL.search(/productdetails.asp/) > 0) {
		myPageType = "productDetail";
		createPadding ();
		addBGImage (true);
		cleanUpProductPage ();
	}
	
	if (myURL.search(/one-page-checkout.asp/) > 0) {
		myPageType = "onePageCheckout";
		addBGImage (true);
		onePageCheckoutCleanUp ();
	}
	
	if (myURL.search(/searchresults.asp/) > 0) {
		myPageType = "searchResults";
		addBGImage (true);
		//createPadding ();
	}
	
	if (myURL.search(/shoppingcart.asp/) > 0) {
		myPageType = "shoppingCart";
		addBGImage (true);
		createPadding ();
		checkCartForFreeShip ();
		cleanupCartPage();
	}
	
	if (myURL.search(/myaccount.asp/) > 0) {
		myPageType = "myAccount";
		addBGImage (true);
		createPadding ();
		formatMyAccountPage ();
	}
	
	if (myURL.search(/login.asp/) > 0) {
		myPageType = "login";
		addBGImage (true);
	}
	
	if (myURL.search(/_a\//) > 0) {
		myPageType = "article";
		addBGImage (true);
	}
	
	if (myURL.search(/myrewards.asp/) > 0) {
		myPageType = "rewards";
		addBGImage (true);
	}
	
	if (myURL.search(/wishlist.asp/) > 0) {
		myPageType = "wishList";
		createPadding (20);
		addBGImage (true);
	}
	
	if (myURL.search(/default.asp/) > 0 | myURL.search(/coffeerocket.com\/\?/) > 0 | myURL=="http://www.coffeerocket.com/" | myURL=="https://www.coffeerocket.com/") {
		myPageType = "homePage";
		injectTopBrands ();
		autoFill('#iNwslttr', 'Enter Email...', "#999")
		autoFill('#iOrdrSts', 'Order Number...', "#999")
		$('#header').css('margin-bottom', '18px');
		$("#indexPromoWrap").closest('td').stop().find('table:eq(0)').addClass('featuredProducts').stop().find('tr:eq(0)').append('<td width="319" valign="top"><div id="whatsHot"></div></td>');
		$("#whatsHot").append('<div class="hotItem"><img src="/v/vspfiles/templates/crv3/images/aV3/template/indexPromo/hot_title.png" /><div>')
				    .append('<div class="hotItem"><a href="http://www.coffeerocket.com/Keurig-Coffee-Makers-K-Cups-s/3.htm"><img src="/v/vspfiles/templates/crv3/images/aV3/template/indexPromo/hot_k-cups.png" /></a><div>')
				    .append('<div class="hotItem"><a href="http://www.coffeerocket.com/Coffee-Rocket-Newsletter-Signup_a/150.html"><img src="/v/vspfiles/templates/crv3/images/aV3/template/indexPromo/hot_newsletter.png" /></a><div>');
		$('#contentWrap').css('background','url(/v/vspfiles/templates/crv3/images/aV3/template/contentWrap2_bg.png) no-repeat center bottom');
		$('#newCustWrap .qLink:first').css('background','url(/v/vspfiles/templates/crv3/images/aV3/template/indexPromo/coupon_NEW5.png) no-repeat center top').height(76).find('p').hide();
		$('#curCustWrap .qLink:first').css('background','url(/v/vspfiles/templates/crv3/images/aV3/template/indexPromo/coupon_SAVE5.png) no-repeat center top').height(76).find('p').hide();
		
		simpleGalleryInit ();
	}
	//$("<div>" + myPageType + "</div>").prependTo("body");
	//return myPageType;
	function addBGImage (addCap) {
		$('#contentWrap').css('background','url(/v/vspfiles/templates/crv3/images/aV3/template/contentWrap_bg.gif) repeat-y center top');
		if (addCap == true) {
			$("#contentWrap").before("<div id='contentCap'></div>");
		}
	}
}
function createPadding (padding) {
	if (padding) {
		var myP = padding;
	} else {
		var myP = 1;
	}
	$('.colors_productname:first').parent("td").parent("tr").parent("tbody").parent("table").attr('cellspacing', myP).parent("td").attr("id", "myContentArea");
	
}
function checkCartForFreeShip () {
	var priceString = $('#content_area font.pricecolor b:contains("$")').text();
	var priceString2 = 75.00 - priceString.substr(priceString.indexOf("$")+1,5);
	//alert(priceString);
	if (priceString2 > 0) {
		$('#content_area div').eq(0).after('<div class="InfoMessage">Free domestic shipping on orders over <strong>$75</strong>. Add <strong>$' + priceString2.toFixed(2) + '</strong> more to ship free!</div>');
	}
 
}
function onePageCheckoutCleanUp () {
	$("#content_area form:eq(0) table:eq(0)").width(980);
	$("select").attr("name", function (i) {
		if(this.name == "My_Saved_Billing") {
			$("option:eq(0)", this).text("Please Choose:");
		} else if (this.name == "My_Saved_Shipping") {
			$("option:eq(0)", this).text("Please Choose:");
		}
	});
	$('input[type="text"]:not("#topSearch input")').addClass('checkoutInput');
	
}
function cleanupCartPage () {
	$('#content_area form:eq(0)').find("img[src*='/photos/']").wrap('<div style="margin:10px;text-align:center"></div>').closest('tr').addClass('cartRow');
	$('.carttext.colors_text:contains("remove an item from your cart")').wrap('<div style="margin:10px;"></div>');
	$('.cartRow center input[type="text"]').addClass('cartInput');
	$('#content_area form td td input[type="text"]:not("cartInput")').addClass('checkoutInput');
	$('#content_area form td td input[type="password"]:not("cartInput")').addClass('checkoutInput');
	$('#content_area br:lt(6)').remove();
	$('#content_area td[background="v/vspfiles/templates/ycc1/images/cart/cart_br_background.gif"]').attr('background', '');
	$('#content_area img[src="v/vspfiles/templates/ycc1/images/cart/cart_br.gif"]').remove();
	$('#content_area .colors_background1 img[src="v/vspfiles/templates/crv3/images/cart/cart_tl.gif"]').remove();
	$('#content_area .colors_background1 img[src="v/vspfiles/templates/crv3/images/cart/cart_tr.gif"]').remove();
	$('.colors_background1_text').wrap('<div style="margin:10px;"></div>').css('color', '#000');
	$('.colors_lines').removeClass('colors_lines');
	$('#content_area img[src="/v/vspfiles/templates/crv3/images/buttons/btn_continueshopping.gif"]').parent().addClass('historyBtn');
	$('.historyBtn').bind('click', function (e) {
		e.preventDefault();
		window.history.go(-1);
	});
}
function cleanUpProductPage () {
	$('#content_area form:eq(0) > table').attr("cellspacing","20");
	$("#content_area .wishpot_form").remove();
	$("#content_area .productnamecolorLARGE").css({"font-size":"28px","color":"#363636","font-weight":"bold","text-shadow": "0 2px 2px rgba(0,0,0,.25)","letter-spacing":"-1px"});
	$("#content_area .colors_pricebox .colors_productprice").css({"font-size":"18px","font-weight":"bold"}).find('b').css({"font-size":"18px","font-weight":"normal"});
	$("#content_area .colors_pricebox .colors_productprice").closest('table').addClass('priceTable');
	$("#content_area input[name^='QTY']:not(:hidden)").addClass("prodDetailInput");
	$("#content_area .prodDetailInput").closest('tr').find('td:eq(0)').after("<td valign='top'><div id='inputCntrlsWrap'><div id='upCntrl' class='btnCntrl'>&nbsp;<div><div id='dwnCntrl' class='btnCntrl'>&nbsp;<div></div></td>");
	$('.colors_pricebox').css("background","#e4f1ff");
	var myPrice = $(".pricecolor.colors_productprice:eq(0):contains('$')").text();
	myPrice = myPrice.substring(myPrice.indexOf('$')+1,myPrice.length);
	var myVal = $("#content_area .prodDetailInput").val();
	
	$(".priceTable").after("<div id='priceSubTotal'>Subtotal:</div>");
	updateSubtotal (myPrice,myVal);
	$("#content_area .prodDetailInput").attr({"size":"4", "maxlength":"3" }).bind('keyup', keyP);
	$("#upCntrl").live('click', clickUp);
	$("#dwnCntrl").live('click', clickDwn);
	
	function updateSubtotal (myP,myV) {
		var subTotal = myP * myV;
		subTotal= subTotal.toFixed(2);
		var subTotalStr = "Subtotal: $" + myP + "x " + myV + " = $" + subTotal;
		$('#priceSubTotal').text(subTotalStr);
		//alert("ddd")
	}
	function clickUp () {
		myVal++;
		$("#content_area .prodDetailInput").val( myVal );
		updateSubtotal (myPrice,myVal);
	}
	function clickDwn () { 
		myVal--;
		if (myVal < 1) { myVal = 1}
		$("#content_area .prodDetailInput").val( myVal );
		updateSubtotal (myPrice,myVal);
		return false;
	}
	function keyP () {
		myVal = $("#content_area .prodDetailInput").val();
		updateSubtotal (myPrice,myVal);
		//alert("ddd")
	}
	var myInfoTitle = $('nobr b').text() + ":";
	var myDescrHTML = $('.colors_descriptionbox table td').attr("id","prodDescr").html();
	$('.colors_descriptionbox').parent().prepend('<div id="newInfoBox"><div id="infoBoxTitle">'+myInfoTitle+'</div><div id="infoBoxHTML">'+myDescrHTML+'</div></div>').find('> table:not(.colors_lines_light)').hide();
}
function quickCart () {
	
	
	getCartData ();
	
	function getCartData () {
		$.ajax({
			type: "GET",
			cache:false,
			url: "/shoppingcart.asp",
			dataType: "html",
			success: function(xhr) {
				getCartDataSuccess(xhr);
				
			} //close $.ajax success(
		}); //close $.ajax(
	} // end getCartData
	
	function getCartDataSuccess (xhr) {
		
		$('#sideMiniCart div:not("#softLoading")').remove();
		$('#sideMiniCart').prepend('<div id="sideMiniCartTitle"><a href="/shoppingcart.asp"><span>link</span></a></div>');
		
		var myForm = $(xhr).find('#content_area form:eq(0)');
		if ($(myForm).size() < 1) {
			$('<div id="miniCartEmpty">Your cart is empty :(</div>').appendTo('#sideMiniCart');
			$('#miniCartSumm').html('<a href="/shoppingcart.asp">Cart</a> is empty :(');
			return;
		}
		
		//extract content from cart page
		var myCartProdNames = $(myForm).find('.colors_productname');
		var myCartImages = $(myForm).find("img[src*='/photos/']");
		var myCartQuantities = $(myForm).find("input[id*='Quantity']");
		var myCartProductTotals = $(myForm).find(".carttext.colors_text b").not(".carttext.colors_text a b");
		var myCartPriceTotal = $(myForm).find(".pricecolor.colors_productprice:has(b)");
		var NumProducts = $(myCartProdNames).size();
		
		
		var myCartDivs = new Array();
		$(myCartImages).each(function (j) {
			
			var myIdName = 'miniCartProdWrapper_' + j;
			$("<div id='" + myIdName + "' class='miniCrtWrp' />").appendTo('#sideMiniCart');
			$(myCartImages).eq(j).appendTo('#miniCartProdWrapper_' + j).addClass('miniCartProdImg').wrap('<div class="miniCartProdImgDiv" />');
			$("<div class='miniCartNamePriceWrap' />").appendTo('#miniCartProdWrapper_' + j);
			var myProdLink = "/" + $(myCartProdNames).eq(j).appendTo(".miniCartNamePriceWrap:eq(" + j + ")").attr('href');
			$(myCartProdNames).eq(j).appendTo(".miniCartNamePriceWrap:eq(" + j + ")").attr('href', myProdLink).addClass('miniCartProdName').wrap('<div class="miniCartProdNameDiv" />');
			$(myCartProductTotals).eq(j).appendTo(".miniCartNamePriceWrap:eq(" + j + ")").addClass('miniCartProdTotal').wrap('<div class="miniCartProdTotalDiv" />');
			$(myCartQuantities).eq(j).appendTo('#miniCartProdWrapper_' + j).addClass('miniCartProdQuan').wrap('<div class="miniCartProdQuanDiv" />');
			
		})
		
		$('.miniCrtWrp').hide();
		//add qty
		var qtyTotal = 0;
		$(myCartQuantities).each(function (i) {
			$('.miniCartProdQuanDiv').eq(i).text("x " + $(this).val());
			qtyTotal = qtyTotal + parseInt($(this).val());
		});
		
		//make mini cart footer
		$(myCartPriceTotal).appendTo('#sideMiniCart').addClass('miniCartPriceTotal').wrap('<div id="miniCartPriceTotalDiv" />');
		$('<div>Subtotal: </div>').prependTo('#miniCartPriceTotalDiv');
		$('<div id="miniCartShipInfo">Shipping costs will be shown during Checkout.</div>').appendTo('#sideMiniCart');
		$('<div id="miniCartEdit"><a class="button medium blue" href="/shoppingcart.asp">View / Edit Cart</a></div>').appendTo('#sideMiniCart');
		$('#miniCartSumm').html('(' + qtyTotal +') items in <a href="/shoppingcart.asp">Cart</a><br>' + $('#miniCartPriceTotalDiv b').text());
		$('#topCartWrap').css('background', 'url(/v/vspfiles/templates/crv3/images/aV3/template/topCartWrap_bg.gif) no-repeat center bottom');
		
		$('#softLoading').slideUp('slow', function () {
			$('#softLoading').remove();
		});
		$('.miniCrtWrp').slideDown('slow');
		
	} // end getCartDataSuccess
	
	
	
}// end quickCart

//soft add
function setUpSoftAdd () {
	
	myPs = findImages ();
	findRows (myPs);
	softAddClick ();
	var readyClick = true;
	
	function findImages () {
		var myProdCodes = new Array();
		var myImgs = $("#myContentArea").find("img[src*='/photos/']");
		$("#myContentArea").find("img[src*='/photos/']").parent().wrap("<div class='softAdd' />");
		$(myImgs).each(function (i) {
			var myHeight = $(this).height();
			var mySrc = $(this).attr("src");
			//var mySrcSplit = mySrc.split('/');
			//mySrc2 = '/' + mySrcSplit[4].toUpperCase();
			//$('#mainWrap').prepend('<div style="display:none">' + mySrc2 + '</div>');
			var re = new RegExp("[A-Z0-9-]", "g");
			var myArray = mySrc.match(re);
			var myArrayLength = myArray.length - 2;
			var myProdCode = myArray.slice(0, myArrayLength);
			var myProdCode = myProdCode.join("");
			$('.softAdd img:eq(' + i +')').attr("id", myProdCode);
			myProdCodes.push(myProdCode);
		});
		
		return myProdCodes;
	}
	
	function findRows (myPs) {
		$('#myContentArea tr:nth-child(5n-1)').addClass('descripRow');
		$('#myContentArea tr:nth-child(5n-3)').addClass('priceRow');
		$('.descripRow').each( function (i) {
			$('td' , this).html('<div class="softAddWrap"></div>');
		});
		
		
		// K-Cup Cookie Stuff
		
				
		
		if (ISCUST === null) {
			ISCUST = '';
			//$('.aMessage').prepend('-');
			$('.priceRow td a:contains("K-Cup")').each( function (i) {
				//$(this).addClass('productNameLink');
				var kcupHTML = "<div class='kMessage'><a class='button small orange' href='/login.asp'>login for price</a></div>";
				$(this).addClass('kcupLink').parent('td').addClass('kcupTD').append(kcupHTML);
				$('.softAddWrap').css('display','none');
			});
        	}
		
		
		
		
		
		$('.softAddWrap').each( function (i) {
			var myHtml = '<div class="addToCartCtrls">Qty: <input name="' + myPs[i] + '" type="text" id="prodQty' + i + '" value="1" size="3" maxlength="3" /> <a class="quickAddSubmit button medium orange" href="#">Add to Cart</a></div>';
			$(this).append(myHtml);
		});
	}
	
	function softAddClick () {

		$('.quickAddSubmit').live('click', function(event) {
			event.preventDefault();
			if (readyClick == true) {
				//var myParentTarget = $(this).parent().parent();
				//$(myParentTarget).hide();
				$('.addToCartCtrls').fadeTo(200,.35);
				$(this).parent().parent().append('<div class="softLoading"></div>');
				$(this).parent().hide();
				var myQty = $(this).parent().find("input").val();
				var myCode = $(this).parent().find("input").attr('name');
				softAddSendData ($(this), myQty, myCode);
			}
						
		}); // close click
		
		
		$('.addToCartCtrls input').live('keypress', function(event) {
			if (event.keyCode == '	13') {
				event.preventDefault();
				myT = event.target;
				$(myT).closest('.addToCartCtrls').find('.quickAddSubmit').trigger('click');
			}
		});
		
	} // close softAddClick
	
	function softAddSendData (softThisRef, myQ, myC) {
		
		var myCode = myC;	
		var myQ = "/shoppingcart.asp?ProductCode=" + myCode + "&QTY." + myCode + "=" + myQ;
		readyClick = false;
		$.ajax({
			type: "POST",
			url: myQ,
			dataType: "html",
			success: function(xhr) {
				
				$('.softLoading').remove();
				$('.miniCrtWrp').slideUp('fast');
				$('#sideMiniCartTitle').after('<div id="softLoading"></div>');
				$('#softLoading').hide().stop().slideDown('fast');
				quickCart ();
				$('.addToCartCtrls').fadeTo('slow',1);
				readyClick = true;
				
			} //close $.ajax success(
		}); //close $.ajax(
	} // end softAddSendData
}

function setUpBreadCrumbs () {
	$("#contentWrap").before("<div id='breadCrumbs'><ul></ul></div>");
	var breadCrumbLinks = $("b:contains('You are here:') a");
	$("b:contains('You are here:') a").parent().parent().parent().parent().parent().parent().parent().remove();
	$(breadCrumbLinks).each( function (i) {
		$("#breadCrumbs ul").append("<li></li>");
		$("#breadCrumbs ul li").eq(i).prepend(this);
	});
	//$("#breadCrumbs ul").prepend("<li>You are Here:</li>");
	$("#breadCrumbs ul li:first").css({'background': 'transparent'}, {'text-indent': '-15px'});
}
function setUpSubCategory () {
		$("b:contains('Choose a sub category:')").parent().parent().parent().parent().parent().parent().attr("id", "volSubCats").addClass("volSubCatsClass");
	if ( $("#volSubCats").hasClass("volSubCatsClass") ) {
		var categoryLinks = $("#volSubCats a");
		$("#volSubCats table").hide();
		var categoryName = $("#breadCrumbs a:last").text();
		$("#volSubCats").removeClass('colors_backgroundneutral').parent().parent().children().eq(1).hide();
		$("#breadCrumbs").after("<div id='newSubCats'><h4><span>"+categoryName+"</span> sub categories:</h4><div id='newSubCatsCanvas'><ul></ul></div></div>");
		var linkWidth = 0;
		$(categoryLinks).each( function (i) {
			$("#newSubCatsCanvas ul").append("<li><a class='button medium blue' href='" +$(this).attr("href")+ "'>"+$(this).text()+"</a></li>");
			linkWidth += $(".button").eq(i).width();
		});
		if (linkWidth > 700) {
			$("#newSubCats").height( 96 );
		} else {
			$("#newSubCats").height( 60 );
		}
		
		//move next image
		//$("#newSubCats").prepend($("input.next_page_img:eq(0)").css({"position": "relative", "top":"5px","float":"right","right":"10px"}));
		//$("#newSubCats").prepend($("input.previous_page_img:eq(0)").css({"position": "relative", "top":"5px","float":"right","right":"10px"}));
	}
}
function cartSummary () {
	var miniCartText = $(".cartsummary_full").text();
	if (miniCartText) {
		var miniCartTextArray = miniCartText.split(" ");
		var myItems = miniCartTextArray[4];
		var myTotalArray1 = miniCartText.split("$");
		var myTotalArray = myTotalArray1[1].split(")");
		var myTotal = myTotalArray[0];
		var myHtml = '(' + myItems + ') items in <a href="/shoppingcart.asp">Cart</a><br />' + '$' + myTotal;
		$("#miniCartSumm").html(myHtml);
		$('#topCartWrap').css('background', 'url(/v/vspfiles/templates/crv3/images/aV3/template/topCartWrap_bg.gif) no-repeat center bottom');
	} else {
		//alert('empty cart');	
	}
}

function autoFill(id, v, dColor) {
	$(id).css({ color: dColor }).attr({ value: v }).focus(function(){
		if($(this).val()==v){
			$(this).val("").css({ color: "#535353" });
		}
	}).blur(function(){
		if($(this).val()==""){
			$(this).css({ color: dColor }).val(v);
		}
	});

}
function injectTopBrands () {
	
	$('#blurbWrap').hide();
	var arr = []
	while(arr.length < 4){
		var randomnumber=Math.ceil(Math.random()*9)
		var found=false;
		for(var i=0;i<arr.length;i++){
		if(arr[i]==randomnumber){found=true;break}
	}
		if(!found)arr[arr.length]=randomnumber;
	}
	
	var myBrands = {'flavia': ['Flavia Coffee','http://www.coffeerocket.com/Flavia-Coffee-s/2.htm'],
				'illy': ['Illy Coffee &amp; Espresso','http://www.coffeerocket.com/Illy-Espresso-Coffee-s/694.htm'],
				'lavazza': ['Lavazza Coffee &amp; Espresso','http://www.coffeerocket.com/Lavazza-Coffee-Espresso-s/43.htm'],
				'segafredo': ['Segafredo Coffee &amp; Espresso','http://www.coffeerocket.com/Segafredo-Espresso-Coffee-s/712.htm'],
				'dolcegusto': ['Nescafe Dolce Gusto','http://www.coffeerocket.com/Nescafe-Dolce-Gusto-Single-Serve-Coffee-Capsules-s/421.htm'],
				'tassimo': ['Tassimo T-Discs','http://www.coffeerocket.com/Tassimo-Coffee-T-DISCs-s/449.htm'],
				'keurig': ['Keurig K-Cups','http://www.coffeerocket.com/Keurig-Coffee-Makers-K-Cups-s/3.htm'],
				'senseo': ['Senseo Coffee Pods','http://www.coffeerocket.com/Senseo-Coffee-Pods-s/480.htm'],
				'teaforte': ['Tea Forte','http://www.coffeerocket.com/tea-forte-s/927.htm']};

	var myPath = '/v/vspfiles/templates/crv3/images/aV3/template/indexPromo/topBrands/';
	var imgCount = 0;
	for(key in myBrands)
	{
		imgCount++;
		for (i=0;i<=arr.length;i++) {
			if (arr[i] == imgCount) {
				var myImg = '<img src="' + myPath + key + '.jpg" />';
				var myImgBtn = '<img src="' + myPath + 'shopnow_btn.png" />';
				var myHref = myBrands[key][1];
				$('#jqTBWrap').append('<div class="brandWrap"><div class="brandImg">' + myImg + 
								  '</div><div class="brandInfo"><a class="myBrndTtl" href="'+myHref+'">' + myBrands[key][0] + 
								  '</a><a class="myBrndBtn button bigrounded orange" href="'+myHref+'">Shop Now!</a></div></div>');
			}
		}
		
	}
	
}
//megaMenu
function makeMegaMenu () {

	function megaHoverOver(){
	
	var thisSub = $(this).find(".sub");
	var myPos = $(this).position();
	var myVal = myPos.left * -1 + 'px -53px';
	$('a:first:not(".sub ul li a")',this).css('background-position', myVal);
	
	$(this).find(".sub").stop().fadeTo('fast', 1).show();
	
	//Calculate width of all ul's
	(function($) { 
		jQuery.fn.calcSubWidth = function() {
			rowWidth = 0;
			//Calculate row
			$(this).find("ul").each(function() {     
				rowWidth += $(this).width(); 
			}); 
		};
	})(jQuery); 
	
	if ( $(this).find(".row").length > 0 ) { //If row exists...
		var biggestRow = 0; 
		//Calculate each row
		$(this).find(".row").each(function() {          
			$(this).calcSubWidth();
			//Find biggest row
			if(rowWidth > biggestRow) {
				biggestRow = rowWidth;
			}
		});
		//Set width
		$(this).find(".sub").css({'width' :biggestRow});
		$(this).find(".row:last").css({'margin':'0'});
		
	} else { //If row does not exist...
		
		$(this).calcSubWidth();
		//Set Width
		$(this).find(".sub").css({'width' : rowWidth});
		
		}
	
	
	}
 
	function megaHoverOut(){ 
		
		var myPos = $(this).position();
		var myVal = myPos.left * -1 + 'px 0';
		$('a:first:not(".sub ul li a")',this).css('background-position', myVal);
		
		
		$(this).find(".sub").stop().fadeTo('fast', 0, function() {
			$(this).hide(); 
		});
	}
 
 
	var config = {    
		sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
		interval: 100, // number = milliseconds for onMouseOver polling interval    
		over: megaHoverOver, // function = onMouseOver callback (REQUIRED)    
		timeout: 150, // number = milliseconds delay before onMouseOut    
		out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
	};

	$("ul#gNav li .sub").css({'opacity':'0'});
	$("ul#gNav li").hoverIntent(config);

}

/*
 * stickyfloat - jQuery plugin for verticaly floating anything in a constrained area
 * 
 * Example: jQuery('#menu').stickyfloat({duration: 400});
 * parameters:
 * 		duration 	- the duration of the animation
 *		startOffset - the amount of scroll offset after it the animations kicks in
 *		offsetY		- the offset from the top when the object is animated
 *		lockBottom	- 'true' by default, set to false if you don't want your floating box to stop at parent's bottom
 * $Version: 05.16.2009 r1
 * Copyright (c) 2009 Yair Even-Or
 * vsync.design@gmail.com
 */

$.fn.stickyfloat = function(options, lockBottom) {

	var $obj 				= this;
	if ($obj.parent().height() < 200 ) {return;}
	var parentPaddingTop 	= parseInt($obj.parent().css('padding-top'));
	var startOffset 		= $obj.parent().offset().top;
	var opts 				= $.extend({ startOffset: startOffset, offsetY: parentPaddingTop, duration: 200, lockBottom:true }, options);
	
	$obj.css({ position: 'relative' });
	
	if(opts.lockBottom){
		var bottomPos = $obj.parent().height() - $obj.height() + parentPaddingTop; //get the maximum scrollTop value
		if( bottomPos < 0 )
			bottomPos = 0;
	}
	
	$(window).scroll(function () { 
		$obj.stop(); // stop all calculations on scroll event

		var pastStartOffset		= $(document).scrollTop() > opts.startOffset;	// check if the window was scrolled down more than the start offset declared.
		var objFartherThanTopPos	= $obj.offset().top > startOffset;	// check if the object is at it's top position (starting point)
		var objBiggerThanWindow 	= $obj.outerHeight() < $(window).height();	// if the window size is smaller than the Obj size, then do not animate.
		
		// if window scrolled down more than startOffset OR obj position is greater than
		// the top position possible (+ offsetY) AND window size must be bigger than Obj size
		if( (pastStartOffset || objFartherThanTopPos) && objBiggerThanWindow ){ 
			var newpos = ($(document).scrollTop() -startOffset + opts.offsetY );
			if ( newpos > bottomPos )
				newpos = bottomPos;
			if ( $(document).scrollTop() < opts.startOffset ) // if window scrolled < starting offset, then reset Obj position (opts.offsetY);
				newpos = parentPaddingTop;

			$obj.animate({ top: newpos }, opts.duration );
		}
	});
};


function formatMyAccountPage () {
	$("#content_area form:eq(0) table tbody:eq(0) > tr:gt(0):lt(4)").addClass("acctPanel");
	$(".acctPanel tr:first-child td b").addClass("acctPanelTitle");
	//insert new div for account controls
	$("#content_area form:eq(0) table tbody:eq(0) > tr:eq(0)").after("<tr><td><div id='newAcctDiv'></div></td></tr>");
	
	var panelTitles = new Array();
	$(".acctPanelTitle").each( function(i) {
		//alert($(".acctPanelTitle")eq(i).text());
		$("#newAcctDiv").append("<div class='newAcctDivCanvas'></div>");
		panelTitles.push($(".acctPanelTitle").eq(i).text());
		$("#newAcctDiv .newAcctDivCanvas").eq(i).append("<h2>"+ panelTitles[i] +"</h2>");
		$("#newAcctDiv h2").eq(i).after("<div class='panelLinkWrapOuter' id='panelContent"+ i +"'></div>");
		var myLinks = $(".acctPanel").eq(i).stop().find("a");
		$(myLinks).each( function(j) {
			$("#panelContent"+i).append($(this).clone());
			$("#panelContent" + i + " a").eq(j).wrap("<div class='panelLinkWrap'></div>");
		}); 
	});
	
	
	$(".newAcctDivCanvas").each( function (i) {
		var myWidth = $("#newAcctDiv").innerWidth() / $(".newAcctDivCanvas").size();
		$(this).width(myWidth-5);
	});
	$(".panelLinkWrap").hover(function () {
		$(this).css("background", "#603913")
		$("a", this).css("color", "#fff");
	}, function () { 
		$(this).css("background", "transparent");
		$("a", this).css("color", "#4986c9");
	});
	
	$(".panelLinkWrapOuter .panelLinkWrap:first-child").css("margin-top", "5px");
	$(".acctPanel").hide();
}

//simple gallery init

function simpleGalleryInit () {
	var mygallery=new simpleGallery({
		wrapperid: "simplegallery1", //ID of main gallery container,
		dimensions: [620, 284], //width/height of gallery in pixels. Should reflect dimensions of the images exactly
		imagearray: [
			["/v/vspfiles/templates/crv3/images/aV3/template/indexPromo/spotlight/welcome_05-2010.jpg", "/", "_self", "Welcome to CoffeeRocket.com - Fuel Up and Save!"],
			["/v/vspfiles/templates/crv3/images/aV3/template/indexPromo/spotlight/melitta_08-2010.jpg", "/Melitta-One-Coffee-Pods-s/36.htm", "_self", "Celebrate the new look!"],
			["/v/vspfiles/templates/crv3/images/aV3/template/indexPromo/spotlight/ez-pod_05-2010.jpg", "/Perfect-Pod-EZ-Cup-p/pp-ezc.htm", "_self", "Go Green with your K-Cups - Perfect Pod's E-Z Cup"],
			["/v/vspfiles/templates/crv3/images/aV3/template/indexPromo/spotlight/carousels_05-2010.jpg", "/SearchResults.asp?Search=Carousel", "_self", "New Single Cup Coffee Carousels for Keurig, Tassimo and Dolce Gusto"],
			["/v/vspfiles/templates/crv3/images/aV3/template/indexPromo/spotlight/coffee-amp-blog_05-2010.jpg", "http://www.coffeeamp.com", "_new", "Check out our new blog! www.CoffeeAmp.com"],
			["/v/vspfiles/templates/crv3/images/aV3/template/indexPromo/spotlight/revv-k-cups_05-2010.jpg", "/SearchResults.asp?Search=Revv", "_self", "CoffeeRocket.com proudly presents Revv and REVV pulse K-Cups. Login to view pricing!"]
			
		],
		autoplay: [true, 8000, 6], //[auto_play_boolean, delay_btw_slide_millisec, cycles_before_stopping_int]
		persist: true, //remember last viewed slide and recall within same session?
		fadeduration: 800, //transition duration (milliseconds)
		oninit:function(){ //event that fires when gallery has initialized/ ready to run
			//Keyword "this": references current gallery instance (ie: try this.navigate("play/pause"))
		},
		onslide:function(curslide, i){ //event that fires after each slide is shown
			//Keyword "this": references current gallery instance
			//curslide: returns DOM reference to current slide's DIV (ie: try alert(curslide.innerHTML)
			//i: integer reflecting current image within collection being shown (0=1st image, 1=2nd etc)
		}
	})	
}




//** Simple Controls Gallery- (c) Dynamic Drive DHTML code library: http://www.dynamicdrive.com
//** Dec 7th, 08'- Script created (Requires jquery 1.2.x)
//** February 6th, 09'- Updated to v 1.3:
	//1) Adds Description Panel to optionally show a textual description for each slide
	//2) In Auto Play mode, you can now set the number of cycles before gallery stops.
	//3) Inside oninit() and onslide(), keyword "this" now references the current gallery instance


var simpleGallery_navpanel={
	panel: {height:'45px', opacity:0.5, paddingTop:'5px', fontStyle:'bold 11px Verdana'}, //customize nav panel container
	images: [ '/v/vspfiles/templates/crv3/js/img/left.gif', '/v/vspfiles/templates/crv3/js/img/play.gif', '/v/vspfiles/templates/crv3/js/img/right.gif', '/v/vspfiles/templates/crv3/js/img/pause.gif'], //nav panel images (in that order)
	imageSpacing: {offsetTop:[-4, 0, -4], spacing:10}, //top offset of left, play, and right images, PLUS spacing between the 3 images
	slideduration: 500 //duration of slide up animation to reveal panel
}

function simpleGallery(settingarg){
	this.setting=settingarg
	settingarg=null
	var setting=this.setting
	setting.panelheight=(parseInt(setting.navpanelheight)>5)? parseInt(setting.navpanelheight) : parseInt(simpleGallery_navpanel.panel.height)
	setting.fadeduration=parseInt(setting.fadeduration)
	setting.curimage=(setting.persist)? simpleGallery.routines.getCookie("gallery-"+setting.wrapperid) : 0
	setting.curimage=setting.curimage || 0 //account for curimage being null if cookie is empty
	setting.ispaused=!setting.autoplay[0] //ispaused reflects current state of gallery, autoplay[0] indicates whether gallery is set to auto play
	setting.currentstep=0 //keep track of # of slides slideshow has gone through
	setting.totalsteps=setting.imagearray.length*setting.autoplay[2] //Total steps limit: # of images x # of user specified cycles
	setting.fglayer=0, setting.bglayer=1 //index of active and background layer (switches after each change of slide)
	setting.oninit=setting.oninit || function(){}
	setting.onslide=setting.onslide || function(){}
	var preloadimages=[], longestdesc=null //preload images
	setting.longestdesc="" //get longest description of all slides. If no desciptions defined, variable contains ""
	for (var i=0; i<setting.imagearray.length; i++){
		preloadimages[i]=new Image()
		preloadimages[i].src=setting.imagearray[i][0]
		if (setting.imagearray[i][3] && setting.imagearray[i][3].length>setting.longestdesc.length)
			setting.longestdesc=setting.imagearray[i][3]
	}
	var slideshow=this
	jQuery(document).ready(function($){
		var setting=slideshow.setting
		setting.$wrapperdiv=$('#'+setting.wrapperid).css({position:'relative', visibility:'visible', background:'black', overflow:'hidden', width:setting.dimensions[0], height:setting.dimensions[1]}).empty() //main gallery DIV
		if (setting.$wrapperdiv.length==0){ //if no wrapper DIV found
			alert("Error: DIV with ID \""+setting.wrapperid+"\" not found on page.")
			return
		}
		setting.$gallerylayers=$('<div class="gallerylayer"></div><div class="gallerylayer"></div>') //two stacked DIVs to display the actual slide 
			.css({position:'absolute', left:0, top:0})
			.appendTo(setting.$wrapperdiv)
		setting.gallerylayers=setting.$gallerylayers.get() //cache stacked DIVs as DOM objects
		setting.navbuttons=simpleGallery.routines.addnavpanel(setting) //get 4 nav buttons DIVs as DOM objects
		if (setting.longestdesc!="") //if at least one slide contains a description (feature is enabled)
			setting.descdiv=simpleGallery.routines.adddescpanel(setting)
		$(setting.navbuttons).filter('img.navimages').css({opacity:0.8})
			.bind('mouseover mouseout', function(e){
				$(this).css({opacity:(e.type=="mouseover")? 1 : 0.8})
			})
			.bind('click', function(e){
				var keyword=e.target.title.toLowerCase()
				slideshow.navigate(keyword) //assign behavior to nav images
			})
		setting.$wrapperdiv.bind('mouseenter', function(){slideshow.showhidenavpanel('show')})
		setting.$wrapperdiv.bind('mouseleave', function(){slideshow.showhidenavpanel('hide')})
		slideshow.showslide(setting.curimage) //show initial slide
		setting.oninit.call(slideshow) //trigger oninit() event
		$(window).bind('unload', function(){ //clean up and persist
			$(slideshow.setting.navbuttons).unbind()
			if (slideshow.setting.persist) //remember last shown image's index
				simpleGallery.routines.setCookie("gallery-"+setting.wrapperid, setting.curimage)
			jQuery.each(slideshow.setting, function(k){
				if (slideshow.setting[k] instanceof Array){
					for (var i=0; i<slideshow.setting[k].length; i++){
						if (slideshow.setting[k][i].tagName=="DIV") //catches 2 gallerylayer divs, gallerystatus div
							slideshow.setting[k][i].innerHTML=null
						slideshow.setting[k][i]=null
					}
				}
				if (slideshow.setting[k].innerHTML) //catch gallerydesctext div
					slideshow.setting[k].innerHTML=null
				slideshow.setting[k]=null
			})
			slideshow=slideshow.setting=null
		})
	})
}

simpleGallery.prototype={

	navigate:function(keyword){
		clearTimeout(this.setting.playtimer)
		this.setting.totalsteps=100000 //if any of the nav buttons are clicked on, set totalsteps limit to an "unreachable" number 
		if (!isNaN(parseInt(keyword))){
			this.showslide(parseInt(keyword))
		}
		else if (/(prev)|(next)/i.test(keyword)){
			this.showslide(keyword.toLowerCase())
		}
		else{ //if play|pause button
			var slideshow=this
			var $playbutton=$(this.setting.navbuttons).eq(1)
			if (!this.setting.ispaused){ //if pause Gallery
				this.setting.autoplay[0]=false
				$playbutton.attr({title:'Play', src:simpleGallery_navpanel.images[1]})
			}
			else if (this.setting.ispaused){ //if play Gallery
				this.setting.autoplay[0]=true
				this.setting.playtimer=setTimeout(function(){slideshow.showslide('next')}, this.setting.autoplay[1])
				$playbutton.attr({title:'Pause', src:simpleGallery_navpanel.images[3]})
			}
			slideshow.setting.ispaused=!slideshow.setting.ispaused
		}
	},

	showslide:function(keyword){
		var slideshow=this
		var setting=slideshow.setting
		var totalimages=setting.imagearray.length
		var imgindex=(keyword=="next")? (setting.curimage<totalimages-1? setting.curimage+1 : 0)
			: (keyword=="prev")? (setting.curimage>0? setting.curimage-1 : totalimages-1)
			: Math.min(keyword, totalimages-1)
		setting.gallerylayers[setting.bglayer].innerHTML=simpleGallery.routines.getSlideHTML(setting.imagearray[imgindex])
		setting.$gallerylayers.eq(setting.bglayer).css({zIndex:1000, opacity:0}) //background layer becomes foreground
			.stop().css({opacity:0}).animate({opacity:1}, setting.fadeduration, function(){ //Callback function after fade animation is complete:
				clearTimeout(setting.playtimer)
				setting.gallerylayers[setting.bglayer].innerHTML=null  //empty bglayer (previously fglayer before setting.fglayer=setting.bglayer was set below)
				try{
					setting.onslide.call(slideshow, setting.gallerylayers[setting.fglayer], setting.curimage)
				}catch(e){
					alert("Simple Controls Gallery: An error has occured somwhere in your code attached to the \"onslide\" event: "+e)
				}
				setting.currentstep+=1
				if (setting.autoplay[0]){
					if (setting.currentstep<=setting.totalsteps)
						setting.playtimer=setTimeout(function(){slideshow.showslide('next')}, setting.autoplay[1])
					else
						slideshow.navigate("play/pause")
				}
			}) //end callback function
		setting.gallerylayers[setting.fglayer].style.zIndex=999 //foreground layer becomes background
		setting.fglayer=setting.bglayer
		setting.bglayer=(setting.bglayer==0)? 1 : 0
		setting.curimage=imgindex
		setting.navbuttons[3].innerHTML=(setting.curimage+1) + '/' + setting.imagearray.length
		if (setting.imagearray[imgindex][3]){ //if this slide contains a description
			setting.$descpanel.css({visibility:'visible'})
			setting.descdiv.innerHTML=setting.imagearray[imgindex][3]
		}
		else if (setting.longestdesc!=""){ //if at least one slide contains a description (feature is enabled)
			setting.descdiv.innerHTML=null
			setting.$descpanel.css({visibility:'hidden'})

		}
	},

	showhidenavpanel:function(state){
		var setting=this.setting
		var endpoint=(state=="show")? setting.dimensions[1]-setting.panelheight : this.setting.dimensions[1]
		setting.$navpanel.stop().animate({top:endpoint}, simpleGallery_navpanel.slideduration)
		if (setting.longestdesc!="") //if at least one slide contains a description (feature is enabled)
			this.showhidedescpanel(state)
	},

	showhidedescpanel:function(state){
		var setting=this.setting
		var endpoint=(state=="show")? 0 : -setting.descpanelheight
		setting.$descpanel.stop().animate({top:endpoint}, simpleGallery_navpanel.slideduration)
	}
}

simpleGallery.routines={

	getSlideHTML:function(imgelement){
		var layerHTML=(imgelement[1])? '<a href="'+imgelement[1]+'" target="'+imgelement[2]+'">\n' : '' //hyperlink slide?
		layerHTML+='<img src="'+imgelement[0]+'" style="border-width:0" />'
		layerHTML+=(imgelement[1])? '</a>' : ''
		return layerHTML //return HTML for this layer
	},

	addnavpanel:function(setting){
		var interfaceHTML=''
		for (var i=0; i<3; i++){
			var imgstyle='position:relative; border:0; cursor:hand; cursor:pointer; top:'+simpleGallery_navpanel.imageSpacing.offsetTop[i]+'px; margin-right:'+(i!=2? simpleGallery_navpanel.imageSpacing.spacing+'px' : 0)
			var title=(i==0? 'Prev' : (i==1)? (setting.ispaused? 'Play' : 'Pause') : 'Next')
			var imagesrc=(i==1)? simpleGallery_navpanel.images[(setting.ispaused)? 1 : 3] : simpleGallery_navpanel.images[i]
			interfaceHTML+='<img class="navimages" title="' + title + '" src="'+ imagesrc +'" style="'+imgstyle+'" /> '
		}
		interfaceHTML+='<div class="gallerystatus" style="margin-top:1px">' + (setting.curimage+1) + '/' + setting.imagearray.length + '</div>'
		setting.$navpanel=$('<div class="navpanellayer"></div>')
			.css({position:'absolute', width:'100%', height:setting.panelheight, left:0, top:setting.dimensions[1], font:simpleGallery_navpanel.panel.fontStyle, zIndex:'1001'})
			.appendTo(setting.$wrapperdiv)
		$('<div class="navpanelbg"></div><div class="navpanelfg"></div>') //create inner nav panel DIVs
			.css({position:'absolute', left:0, top:0, width:'100%', height:'100%'})
			.eq(0).css({background:'black', opacity:simpleGallery_navpanel.panel.opacity}).end() //"navpanelbg" div
			.eq(1).css({paddingTop:simpleGallery_navpanel.panel.paddingTop, textAlign:'center', color:'white'}).html(interfaceHTML).end() //"navpanelfg" div
			.appendTo(setting.$navpanel)
		return setting.$navpanel.find('img.navimages, div.gallerystatus').get() //return 4 nav related images and DIVs as DOM objects
	},

	adddescpanel:function(setting){
		setting.$descpanel=$('<div class="gallerydesc"><div class="gallerydescbg"></div><div class="gallerydescfg"><div class="gallerydesctext"></div></div></div>')
			.css({position:'absolute', width:'100%', left:0, top:-1000, zIndex:'1001'})
			.find('div').css({position:'absolute', left:0, top:0, width:'100%'})
			.eq(0).css({background:'black', opacity:simpleGallery_navpanel.panel.opacity}).end() //"gallerydescbg" div
			.eq(1).css({color:'white'}).end() //"gallerydescfg" div
			.eq(2).html(setting.longestdesc).end().end()
			.appendTo(setting.$wrapperdiv)
		var $gallerydesctext=setting.$descpanel.find('div.gallerydesctext')
		setting.descpanelheight=$gallerydesctext.outerHeight()
		setting.$descpanel.css({top:-setting.descpanelheight, height:setting.descpanelheight}).find('div').css({height:'100%'})
		return setting.$descpanel.find('div.gallerydesctext').get(0) //return gallery description DIV as a DOM object
	},

	getCookie:function(Name){ 
		var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
		if (document.cookie.match(re)) //if cookie found
			return document.cookie.match(re)[0].split("=")[1] //return its value
		return null
	},

	setCookie:function(name, value){
		document.cookie = name+"=" + value + ";path=/"
	}
}



/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};