// Ad-hoc promotion at line 450
// Disable ordering at line 241

var productDetailDefaultTab = "";
var test = false;

function convertSpacesToUnderscore(string) {
	return string.replace(/ /g, "_");
}
function cssStringWithString(string) {
	string = string.replace(/ /g, "_");
	return string.replace(/\?/g, "");
}
function convertDashesToUnderscore(string) {
	return string.replace(/-/g, "_");
}
$(window).bind("load",function(){
	$(".lightbox").each(function() {
		$("a", this).filter(function(index) {
		  return $('img', this).length == 1;
		}).lightBox();
	});
	
	// Snow effect December 2010,11
	// $('body').prepend('<div id="pageBgSnow"></div>');
	// $('#pageBgSnow').css({ 'position':'fixed', 'top':'170px', 'width':'100%', 'height':'511px', 'background':'url(../images/masthead_bg_snow.jpg) 0 0 repeat-x', 'display':'none'});
	// $('#pageBgSnow').fadeTo(0,.3);
	// $('#pageBgSnow').fadeTo(1000,1);
	
	
	if ($(".fadingSlideshow").length) {
		$('.fadingSlideshow').cycle({ 
		    fx:     'fade', 
		    timeout: 6000,
			delay:	1000,
			speed:	1500
		});
	}
	if ($("body#about").length) if (showPolicy) $("#policyLink").click();	// only for the about page
//	$.fn.media.mapFormat('mp3', 'quicktime');
	$('a.audioMedia').media( { width: 300, height: 20 } );
	$('a.galleryMedia').media( { width: 320, height: 500 } );
	$('a.galleryMediaWide').media( { width: 480, height: 340 } );
	$(".equalheights").equalHeights(100,15000);
	// CHECKOUT LINK
	$("a.faderLink").click(function() {
		$(this).children().fadeTo("fast", ".5");
		$(this).children().fadeTo("fast", "1", function(){
			document.location=$(this).parents().attr("href");
		});
		return false
	});



	// CODE FOR THE PRODUCT DETAIL PAGES.......................................................... //
	$(".productDetailMenu li").click(function() {
		if ($(this).hasClass("addToCart")) return true;
		var myName = cssStringWithString($(this).text());
		var chosenDiv = $(this).parents(".productDetailContainer").find("#productDetailPage"+myName);
		$(this).parents(".productDetailContainer").find(".productDetailPage").hide();
		chosenDiv.fadeIn("slow");
		$(this).siblings().removeClass("productDetailTabSelected");
		$(this).addClass("productDetailTabSelected");
		return true	// so it can propogate to an add to cart event
	});
	$(".productDetailMenu li").eq(productDetailDefaultTab).click();	// click the default tab when the page loads
	$(".tabClick").live("click", function() {
		var children = $(".productDetailMenu").children();
		var count = children.size();
		children.eq(count - $(this).attr("number")).click();
		return false
	});
//	$(".productAnswer").click(function() { return false; $(this).prev().click(); });
	$(".showAllAnswers").click(function() { $(this).parents(".faqs").find("h2").click(); });
	$(".faqs h2").click(function() {
		// if ($(this).next().is(":visible")) {
		// 	$(this).add($(this).next()).insertBefore($(this).parent());
		// 	$(this).next().next().remove();
		// }
		// else $(this).add($(this).next()).wrapAll("<div class='faqFocus'></div>");
		$(this).next().slideToggle("fast");
	});
	$(".videoStillDiv, .videoControlDiv").click(function() {
		$(this).parent().find('.videoControlDiv').fadeOut();
		$(this).parent().find("object")[0].playVideo();
		return false
	});
	$(".pdFeaturedAppNext").click(function() {
		var websiteDataName = $(this).attr('data-featured-apps');
		arbitraryServerFunction("cmsGetWebsiteDataWithName",websiteDataName,function(data) {
			var appsTemp = JSON.parse(data);
			var apps = {};
			var currentApp = $(".pdFeaturedAppCurrent").val();
			var nextApp, lastAppInLoop;
			// strip apps object of all non-displayed data
			for(key in appsTemp) {
				if (key != 'selected' && appsTemp[key].display == 1) apps[key] = appsTemp[key];
			}
			// find next entry, if there is one.
			for(key in apps) {
				if (lastAppInLoop == currentApp) {	
					nextApp = key;
					break;
				}
				lastAppInLoop = key;
			}
			// if currentApp was last in array, wrap around to get the first.
			if (!nextApp) {
				for(key in apps) {
					nextApp = key;
					break;
				}
			}	
			var im = new Image();
			im.src = "/php/slir/w300-q100/" + apps[nextApp].screenShotImage;	// prefetch image so the page doesn't jump around as the image loads.  totally works.
			$(".pdFeaturedAppScreenShotImage").animate({ marginRight: "-=400" },function() {
				$(".pdFeaturedAppScreenShotImage").animate({ marginRight: "+=400" });
			});
			$(".pdFeaturedApp").delay(180).fadeOut("fast",function() {					
				// populate the data
				$(".pdFeaturedAppCurrent").val(nextApp);
				$(".pdFeaturedAppTitle a").text("lovely "+apps[nextApp].appTitle);
				$(".pdFeaturedAppLinkTitle").text(apps[nextApp].appTitle);
				$(".pdFeaturedAppImage").html("<img src=\"/php/slir/w75-q100/" + apps[nextApp].appIcon + "\" alt=\"\" />");
				$(".pdFeaturedAppTitle").html("<a href=\"" + apps[nextApp].appLink + "\">" + apps[nextApp].appTitle + "</a>");
				$(".pdFeaturedAppLink").parent().attr("href",apps[nextApp].appLink);
				$(".pdFeaturedAppDescription").text(apps[nextApp].appText);
				$(".pdFeaturedAppQuoteText").html(apps[nextApp].quote);
				$(".pdFeaturedAppAttributionText").html(apps[nextApp].quoteAttribution);
				$(".pdFeaturedAppScreenShotImage").html("<a href=\"/php/slir/w800/" + apps[nextApp].screenShotImage + "\"><img src=\"/php/slir/w300-q100/" + apps[nextApp].screenShotImage + "\" alt=\"\" /></a>");
				$(this).fadeIn();
			});
			
		});
		return false;
	});
	$(".arbitraryFunctionDiv").each(function() {
		var functionName = $(this).attr("function");
		var params = $(this).attr("params");
		var destination = $(this);
		var callback = $(this).attr("callback");
		$.ajax({
			url: 'php/handler.php',
			type: 'POST',
			timeout: 0,
			dataType: 'html',
			data: functionName+"="+params,
			success: function (data, textStatus) {
				destination.html(data);
				$(".lightbox").each(function() {
					$("a", this).filter(function(index) {
					  return $('img', this).length == 1;
					}).lightBox();
				});
				if (callback) { eval(callback+"()");}
			}
				
		});
		
	});

	$(".addToCart").live("click",function() {
		var data = JSON.parse($(this).attr("data"));
		var cartAdd = data['cartAdd'];
		var t1Cart={};
		if ($.cookie("t1CartItems")) {
			t1Cart = JSON.parse($.cookie("t1CartItems"));
		}
		for (key in cartAdd) {
			if (t1Cart[key] == undefined) {
				t1Cart[key] = cartAdd[key];
			}
			else { t1Cart[key] += cartAdd[key]*1; }
		}
		$.cookie("t1CartItems",JSON.stringify(t1Cart));

		if($("body#checkout").length>=1) {	// if on checkout page
			$("ul.checkoutCartUl").empty();
			readCartFromCookies();
			$(this).prev().before('<img src="images/checkout_check.png" alt="check" />');
		}
		else window.location = "checkout.php?product="+data['checkoutPage'];	// cookies may get lost if we switch from www.tenonedesign to just tenonedesign or the opposite
	});
	// CODE FOR THE TWITTER AND NEWS FEED........................................................... //
	
	// $.get("php/handler.php?getNewsItems=<li>|~</li>",function(html){
	// 	$("#sidebarNews ul").html(html);
	// 	$("#sidebarNews ul").children("li:gt(2)").remove();	// remove everything after the first 3 results
	// });
	
	// DISABLED FOR HIGH VOLUME
	// $.ajax({
	// 	url: 'php/handler.php',
	// 	type: 'POST',
	// 	data: "getNewsItems=<li>|~</li>",
	// 	success: function (html, textStatus) {
	// 			$("#sidebarNews ul").html(html);
	// 			$("#sidebarNews ul").children("li:gt(2)").remove();	// remove everything after the first 3 results
	// 		},
	// 	error: function (XMLHttpRequest, textStatus, errorThrown) {
	// 		  $("#sidebarNews ul").html("Check back later");
	// 		},
	// 	timeout: 3000,
	// 	dataType: 'html'
	// });
	$("#sidebarNews ul").html("");
	$(".loadMoreTwitter").live("click",function() {
		loadTwitter($(this).data('searchString'),$(this).data('from'),$(this).data('loadAfter'),$(this).data('number'),$(this).data('destination'));
		$(this).parent().remove();
	});
	if ($("body#news").length || $("body#press").length) {		// this might actually be the simplest way to detect a certain page...
		loadTwitter('"Pogo%2BSketch"%2BOR%2B"Pogo%2BStylus"%2BOR%2B"Fling%2BJoystick"','',0,6,$('#newsTwitterHits'));
		loadTwitter('','TenOneDesign',0,6,$('#newsTwitterFeed'));
	}

	// CODE FOR THE CASES PAGE............................................................. //
	$(".casesTypeDiv").click(function() {
		$(this).find(".casesContent").slideToggle();
	})
	
	
	
	// CODE FOR THE APPS PAGE............................................................. //
	
	$("#appGallery").html($("#appGalleryDefault").html());	// fill by default
	
	$(".appBanner").click(function() {
		// fade out existing gallery content, copy appBanner to gallery, animate appBanner as below
		var activeBanner = $(this);
		$("#appGallery").children().fadeOut("slow", function() {
			$("#appGallery").html(activeBanner.clone());
			$(".appBannerClose").click(function() {		// Bind Close Button
				$("#appGallery").html($("#appGalleryDefault").html());
			})
			var content = $("#appGallery").find("div.appBannerExpand");
			if (content.css("width")=="0px") {
				content.animate( {width: "500px"}, 1000,"linear", function() {
					content.children().fadeIn("slow");
				});
			}
			else {
				content.children().hide();
				content.animate( {width: "0px"}, 1000);
			}
		});
	})
	
	// CODE FOR THE CHECKOUT PAGE.......................................................... //
	
	$("div.checkoutSidebarGroupDiv").click(function() {		// manage product group sidebar
		var selection = $(this).children("input").val();
		$(".checkoutSidebarGroupDiv").removeClass("checkoutSidebarBackground");  // this overrides css hover.  use add/remove class methods
		$(this).addClass("checkoutSidebarBackground");
		$(".checkoutPagesPage").hide();
		if (selection=="all") $(".checkoutPagesPage").fadeIn();
		else $("#checkoutPage"+selection).show();
		return false
	});
	$(".checkoutItemAddButton").click(function() {		// add things to cart
		var pn = $(this).parents("div.checkoutItemDiv").find("input.checkoutItemPartNumber").val();
		addPartNumberToCart(pn);
		return false
	});

	$("#couponInvite").click(function() {			// operate the coupon code input
		$(this).html("Enter your coupon code here:<br />");
		$(this).css("text-decoration","none");
		$("#couponInput").slideDown();
		return false
	});
	$("#couponApply").click(function() {			// get coupon info
		if ($("#couponCodeInput").val()=="") {
			$("#couponLoader").hide();
			$("#couponDiscount").html("0,0,0,Invalid coupon code");
			$("#couponInput").slideUp();
			$("#couponExplanation").slideUp();
			$(".checkoutHideThis").click();
			refreshCart();
			return false;
		}
		$("#couponExplanation").html("<img id=\"couponLoader\" src=\"images/loader_f1f2f6.gif\" alt=\"loading\" />");
		$.ajax({
			url: 'php/handler.php',
			type: 'POST',
			data: "getCheckoutCoupon="+$("#couponCodeInput").val(),
			success: function (data, textStatus) {
				$("#couponLoader").hide();
				$("#couponDiscount").html(data);
				data = data.split(",");
				$("#couponExplanation").html(data[3]).slideDown();
				showBannerMessage($("#couponExplanation").text());
				
//				if (data[4]) refid = data[4];
				refreshCart();
				},
			timeout: 0,
			dataType: 'html'
		});
		return false
	});
	if($("body#checkout").length>=1) {		// restore items to cart
		readCartFromCookies();
		if (shippingData["promotionMessage"].length>=1) showBannerMessage(shippingData["promotionMessage"]);
	}
	$("#checkoutCartShippingSelect").change(function() {			// run every time shipping is updated
		var temp = shippingData[$(this).val()].price*1;
		$("#checkoutCartShippingPrice").text(temp.toFixed(2));	// essential to round here because .001 = free shipping to evade cart checker
		refreshCart();
	})
	$("#checkoutCartShippingDetails,#checkoutCartHelpDiv").click(function() {		// show the help div
		$("#checkoutCartHelpDiv").slideToggle();
		return false;
	});
	$(".checkoutHideThis").live('click',function() {	// for the banner notice of discount
		$(this).parent().slideUp();
	});
	
	
	// DISABLE ORDERING HERE FOR NOW
	$(".checkoutCartNowButton").click(function() {		// Check and send the cart to paypal		
		// alert("Our ordering system is down for a few minutes.  This notice will go away when it's back up.  Sorry for any inconvenience!");
		// return false;
		submitCart();
	});
	$(".altTarget").click(function() {
		test = true;
		submitCart();
	});
	$(".secretCheckoutCartNowButton").hide();
	$(".secretCheckoutCartNowButton").click(function() {		// Check and send the cart to paypal
		submitCart();
	});
	
	
	$(".paypalButton").click(function() {		// Check and send the cart to paypal
		$(".paypalSubmit").submit();
	});
	$("#couponCodeInput").keydown(
	  function(e){
		var key = e.keyCode || 0;
		if (key == 13) {		// if it's the enter key
    		$("#couponApply").click();
			return false	// TODO: doesn't seem to block form submission in firefox
  		}
	  }
	);

});
function arbitraryServerFunction(functionName,params,callback) {
	$.ajax({
		url: '/php/handler.php',
		type: 'POST',
		timeout: 0,
		dataType: 'html',
		data: functionName+"="+params,
		success: function (data, textStatus) {
			if (typeof callback == "function") { callback.call(this, data); }
		}
			
	});
}
function loadTwitter(searchString,from,loadAfter,number,destination) {
		var loadAfter = loadAfter?loadAfter:0;
		 //alert("page = "+(loadAfter/number+1));
		// alert('url: php/handler.php?proxy=http%3A%2F%2Fsearch.twitter.com%2Fsearch.atom%3Fq%3D"Pogo%2BSketch"%2BOR%2B"Pogo%2BStylus"%26rpp%3D'+number+'%26page%3D'+(loadAfter/number+1));
		jQuery.getFeed({
	//		url: 'php/proxy.php?url=http%3A%2F%2Fwww.tweetscribe.com%2Ffeed.php%3Fuser_name%3Dtenonedesign',	// other url
			url: 'php/handler.php?proxy=http%3A%2F%2Fsearch.twitter.com%2Fsearch.atom%3Fq%3D'+searchString+'%26from%3D'+from+'%26rpp%3D'+number+'%26page%3D'+(loadAfter/number+1),
	        success: function(feed) {
	            var html = '';
	            for(var i = 0; i < feed.items.length; i++) {
	                var item = feed.items[i];
					html += '<div class="newsLineDiv"><a href="'+item.link+'"><img src="'+item.image+'" alt="" /></a>'+item.description+'</div>';
	            }	
					html += '<div class="newsLineDiv newsLineButtonHolder"><div id="" class="shipButton loadMoreTwitter">Load More</div></div>';
				//	alert(html);
				if (loadAfter>0) destination.append(html);
	            else destination.html(html);
				var button = destination.find(".loadMoreTwitter");
	            button.data("loadAfter",loadAfter+number);
	            button.data("searchString",searchString);
	            button.data("from",from);
	            button.data("destination",destination);
	            button.data("number",number);
	        }    
	    });
}

function onPlayerStateChange(player,state) {
	switch(state) {
		case 0:	// ended
			player.siblings().fadeIn();
			break;
		case 1:	// started
			player.siblings('.videoStillDiv').fadeOut(1200);
			break;
	}
}
function onYouTubePlayerReady(playerId) {
	player = document.getElementById(playerId);
	if (!player) $("#"+playerId+"Div").siblings().remove();	// if swfobject didn't load for some reason, remove fancy stuff
	else player.addEventListener("onStateChange",playerId+"StateChange");
}
function addPartNumberToCart(pn) {
	var existing = $("ul.checkoutCartUl").find("#checkoutCartItem"+pn);
	if (existing.length>=1) {
		var quantity = existing.find("select");
		if (quantity.val()<30) quantity.val(quantity.val()*1+1);
	}
	else addHTMLToCart("ul.checkoutCartUl",pn);
	refreshCart();
}
function addHTMLToCart(scope,partnumber) {
	
	$(scope).append(''
	+	'<li class="checkoutCartItem" id="checkoutCartItem'+partnumber+'">'
	+	'		<ul class="checkoutCartItemUl">'
	+	'			<li>'+productData[partnumber].description+'</li>'
	+	'			<li class="checkoutCartItemQuantity">quantity: '
	+	'	            <select class="checkoutCartItemQuantitySelect" name="">'
	+	'	              <option value="0">0</option>'
	+	'		          <option selected value="1">1</option>'
	+	'	              <option value="2">2</option>'
	+	'	              <option value="3">3</option>'
	+	'		          <option value="4">4</option>'
	+	'	              <option value="5">5</option>'
	+	'	              <option value="6">6</option>'
	+	'	              <option value="7">7</option>'
	+	'		          <option value="8">8</option>'
	+	'	              <option value="9">9</option>'
	+	'	              <option value="10">10</option>'
	+	'		          <option value="11">11</option>'
	+	'	              <option value="12">12</option>'
	+	'	              <option value="13">13</option>'
	+	'		          <option value="14">14</option>'
	+	'	              <option value="15">15</option>'
	+	'	              <option value="16">16</option>'
	+	'		          <option value="17">17</option>'
	+	'	              <option value="18">18</option>'
	+	'	              <option value="19">19</option>'
	+	'		          <option value="20">20</option>'
	+	'	              <option value="21">21</option>'
	+	'		          <option value="22">22</option>'
	+	'	              <option value="23">23</option>'
	+	'	              <option value="24">24</option>'
	+	'	              <option value="25">25</option>'
	+	'	              <option value="26">26</option>'
	+	'	              <option value="27">27</option>'
	+	'	              <option value="28">28</option>'
	+	'	              <option value="29">29</option>'
	+	'	              <option value="30">30</option>'
	+	'	            </select>'
	+	'				<a href="">remove</a></li>'
	+	'			<li class="checkoutCartItemSubtotal">$<span>'+productData[partnumber].price+'</span></li>'
	+	'			<li class="checkoutCartItemPrice hidden">'+productData[partnumber].price+'</li>'
	+	'			<li class="checkoutCartItemName hidden">'+productData[partnumber].name+'</li>'
	+	'			<li class="checkoutCartItemSoftware hidden">'+productData[partnumber].software+'</li>'
	+	'			<li class="checkoutCartItemPartNumber hidden">'+productData[partnumber].partnumber+'</li>'
	+	'		</ul>'
	+	'	</li>');
	$(scope).find("li#checkoutCartItem"+partnumber).find("select").val(1);	// force val to fix safari bug
	$(".checkoutCartItemQuantity a").unbind();
	$(".checkoutCartItemQuantity a").click(function() {		// bind removal function
		var item = $(this).parents("li.checkoutCartItem");
		item.slideUp("fast",function(){
			item.remove();
			refreshCart();
		});
		return false
	})
	$("li.checkoutCartItem").find("select").unbind();
	$("li.checkoutCartItem").find("select").change(function() {		// bind update function
		if ($(this).val()==0) $(this).next().click();
		refreshCart();
		return false
	})

}
function readCartFromCookies() {
	
	var t1CartShipping = $.cookie("t1CartShipping");	// offload cookies here b/c addPartNumberToCart clears them
	var t1CartCoupon = $.cookie("t1CartCoupon");
	if ($.cookie("t1CartItems")) {
		t1Cart = JSON.parse($.cookie("t1CartItems"));
		for ( key in t1Cart) {
			for(i=0;i<t1Cart[key];i++) {
				if (productData[key] != undefined && productData[key].orderable=="1") {	// avoid adding unorderable things to cart
    				addPartNumberToCart(key);
				}
  			};
		}
	}
	if (t1CartShipping) {
		$("#checkoutCartShippingSelect").val(t1CartShipping); // restore shipping to cart
		$("#checkoutCartShippingPrice").text((shippingData[t1CartShipping].price*1).toFixed(2));	// make it visible
	}
	if (t1CartCoupon) { 	// replace any coupon
		$("#couponCodeInput").val(t1CartCoupon);
		$("#couponInvite").click();
		$("#couponApply").click();
	}
	refreshCart();
	
}
function refreshCart() {
	var cartQuantity = 0;
	var cartPrice = 0;
	var cartSoftwareCount = 0;	// detect how much software is in cart
	var cartCookieContents={};	// new associative array
	var cartLineItemCount=0;
	// for promotion
	var promotionActive = 0;
	var flingCount = 0;
	var oldCouponExplanation=$("#couponExplanation").html();
	var oldCouponDiscount=$("#couponDiscount").html();
	var oldCouponInput=$("#couponCodeInput").val();
	$("li.checkoutCartItem").each(function() {
		var quantity = $(this).find("select").val()*1;
		var price = $(this).find("li.checkoutCartItemPrice").text()*1;
		var software = $(this).find("li.checkoutCartItemSoftware").text()*1;
		var subtotal = (quantity*price).toFixed(2);
		$(this).find("li.checkoutCartItemSubtotal").children("span").text(subtotal);
		cartPrice += subtotal*1;
		cartQuantity += quantity;
		cartSoftwareCount += software;
		cartCookieContents[convertDashesToUnderscore($(this).find("li.checkoutCartItemPartNumber").text())]=quantity;
		cartLineItemCount ++;
		// Autograph promotion
		// if ($(this).find("li.checkoutCartItemName").text()=="Pogo Sketch - Silver"
		// 		|| $(this).find("li.checkoutCartItemName").text()=="Pogo Sketch - Hot Pink") {
		// 	$("li.checkoutCartItem").each(function() {
		// 		if ($(this).find("li.checkoutCartItemName").text()=="Autograph") {
		// 			promotionActive = 1;
		// 			$("#couponDiscount").html("0,6.95,6.95,<b style=\"color: green\">AandS</b>,00008");
		// 			$("#couponExplanation").html("<b style=\"color: green\">$6.95 has been subtracted from your price.<br />Autograph is now free!</b>");
		// 			$("#couponCodeInput").val("FreeAutographWithSketch");
		// 		}
		// 	});	
		// }
		
		// Count the number of flings for promotion
		var name = $(this).find("li.checkoutCartItemName").text();
		if (name == "Fling Game Controller - Ice" || name == "Fling Game Controller - Ninja" || name == "Fling Game Controller - Ultraviolet") {
			flingCount += quantity;			
		}

	});	

// Fling Promotion start	
	var discount = 0; //Math.floor(flingCount/2)*7.49;
	
	if (discount>0) {	// if promotion is active
		promotionActive = 1;
		refreshCart.promotionWasActive = 1;
		$(".checkoutHideThis").click();
		$("#couponDiscount").html("0,"+discount+","+discount+",Fling30,00008");
		$("#couponExplanation").html("Fling pre-order discount!<br />$"+discount+" has been subtracted from your price.");
		$("#couponCodeInput").val("Fling30");
		console.log("promotion active");
	}
	else if (refreshCart.promotionWasActive) {	// if transitioning to off state (avoiding race condition on coupon)
		refreshCart.promotionWasActive = 0;
		// remove and hide coupon
		$("#couponExplanation").html("");
		$("#couponDiscount").html("0,0,0,");
		$("#couponCodeInput").val("");
		// restore from cookie if possible
		var t1CartCoupon = $.cookie("t1CartCoupon");
		if (t1CartCoupon) {
			$("#couponCodeInput").val(t1CartCoupon);
			$("#couponInvite").click();
			$("#couponApply").click();
		}
		console.log("promotion inactive");
	}
// Fling promotion end
	
	if (cartQuantity==1) $(".checkoutCartCounter").text(cartQuantity+" item:");
	else if (cartQuantity>1) $(".checkoutCartCounter").text(cartQuantity+" items:");
	else $(".checkoutCartCounter").text("Cart is empty");

	reduction = calculateDiscount(cartPrice,$("#couponDiscount").text());
	reduction = (reduction*1).toFixed(2);	// round to cent
	$("#couponPaypal").text(reduction);	// store for Paypal submit
		// if (reduction>0) $("#couponDisplay").text("-$" + reduction + " ");	// display if nonzero
		// else $("#couponDisplay").text("");
	var cartShipping = $("#checkoutCartShippingSelect");
	var cartSoftwareShipping = $("#checkoutCartSoftwareShippingSelect");
	
	if (cartSoftwareCount==cartLineItemCount && cartLineItemCount >0) {	// only software in cart
		cartShipping.hide();
		cartSoftwareShipping.show();
		var cartNewShipping = 0;
		$("#checkoutCartShippingPrice").text(0.00);
	}
	else {
		cartShipping.show();
		cartSoftwareShipping.hide();
		var cartNewShipping = shippingData[cartShipping.val()].price*1;
		$("#checkoutCartShippingPrice").text(cartNewShipping.toFixed(2));
		if ((cartPrice - reduction)> shippingData[cartShipping.val()].freeOver*1) {
			$("#checkoutCartShippingPrice").html("&nbsp;<b style='color: green'>Free!</b>");
			cartNewShipping = 0;
		}
	}
	cartPrice = cartPrice*1 - reduction;	// minus discount
	if ((cartQuantity>=1)&&(cartPrice==0)) cartPrice = 0.01;	// cart can only be zero if empty.  Otherwise, Paypal will have a fit.
	if (cartPrice<0) cartPrice = 0.01;
	cartPrice += cartNewShipping;
	$("#checkoutCartTotalPrice").text(cartPrice.toFixed(2));
	$.cookie("t1CartItems", JSON.stringify(cartCookieContents));	// put cart data into cookies
	$.cookie("t1CartShipping",$("#checkoutCartShippingSelect").val());
	if (!promotionActive) $.cookie("t1CartCoupon",$("#couponCodeInput").val());
}
function showCheckoutMessage(message) {
	var display = showCheckoutMessage.arguments.length;
	if (display==0) $("#checkoutCartMessageBox").hide();
	else $("#checkoutCartMessageBox").html(message).show();
}
function showBannerMessage(message) {
	if ($("#couponExplanationBanner:visible").length>=1) {
		$("#couponExplanationBanner").delay(1000).slideUp(function() {
			$(this).html(message+" <span class='checkoutHideThis'>hide this</span>").slideDown();
			pulseBanner();
		});
	}
	else {
		$("#couponExplanationBanner").html(message+" <span class='checkoutHideThis'>hide this</span>").slideDown();
		pulseBanner();
	}
	
}
function pulseBanner() {
	$("#couponExplanationBanner").css("background-color","#fff").animate({ backgroundColor: "#afa" }, 500,"linear" ).animate({ backgroundColor: "#fff" }, 2200,"linear" );
}
function calculateDiscount(subtotal,discount) {	// todo: check for not a number
	discount = discount.split(",");
	if (subtotal == 0) return 0;
	if (discount[0] == 0) reduction = discount[1];
	else reduction = subtotal * discount[1];
	if (reduction>discount[2]) reduction = discount[2];
	return roundNumber(reduction,2);
}
function getShippingPromotionLevel() {
	if (cartPrice >35) {
		return 1;
		// promotionActive = 1;
		// $("#couponDiscount").html("0,0,0,<b style=\"color: green\">FreeShip</b>,00009");
		// $("#couponExplanation").html("<b style=\"color: green\">Well done!  Ground Shipping is now free!</b>");
		// $("#couponCodeInput").val("FreeShipOver35");
	}
}
function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places
	var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
	return newnumber;
}

function checkCart() {
	$("div.checkoutCartShippingDiv").css("background-color","transparent");		// reset
	if ($(".checkoutCartItem").length<1) {showCheckoutMessage("Your cart is empty"); return false}
	if ($("#checkoutCartShippingSelect").val()=="select" && $("#checkoutCartShippingSelect").is(":visible")) {showCheckoutMessage("Please choose a shipping method"); $("div.checkoutCartShippingDiv").css("background-color","#ffa"); return false}
	if (!$('#policyCheckbox').is(':checked')) {showCheckoutMessage("Please review our ordering policies"); window.scrollTo(0,500); return false}
	return true
}
function submitCart() {
	if (!checkCart()) return false;
	showCheckoutMessage("Working...");
	var cartInc = 0;
	var highestPrice = 0;
	var highestCartInc = 1;
	var cartSoftwareCount = 0;
	var custom = {};	// create object
	var cart = {}
//	custom['cart']=cart;	// prepare cart
	$("input.dynamicInput").remove();
	$(".checkoutCartItem").each(function() {
		cartInc++;
		var itemQuantity = $(this).find(".checkoutCartItemQuantitySelect").val();
		var itemName = $(this).find(".checkoutCartItemName").text();
		var itemNumber = $(this).find(".checkoutCartItemPartNumber").text();
		var itemPrice = $(this).find(".checkoutCartItemPrice").text();
		var software = $(this).find("li.checkoutCartItemSoftware").text()*1;
		$(".paypalSubmit").append("<input type=\"hidden\" name=\"item_name_"+cartInc+"\" class=\"dynamicInput\" value=\""+itemName+"\">"
			+ "<input type=\"hidden\" name=\"item_number_"+cartInc+"\" class=\"dynamicInput\" value=\""+itemNumber+"\">"
			+ "<input type=\"hidden\" name=\"amount_"+cartInc+"\" class=\"dynamicInput\" value=\""+itemPrice+"\">"
			+ "<input type=\"hidden\" name=\"quantity_"+cartInc+"\" class=\"dynamicInput\" value=\""+itemQuantity+"\">");
		$("input[name='quantity_"+cartInc+"']").val(itemQuantity);		// force value because safari remembers old quantity after hitting 'back' to get to this page, even when removed and reentered.  value must be overwritten.
		$("input[name='item_name_"+cartInc+"']").val(itemName);
		$("input[name='item_number_"+cartInc+"']").val(itemNumber);
		$("input[name='amount_"+cartInc+"']").val(itemPrice);
		var cartArray = {}
		cart[cartInc-1]=cartArray;
		cart[cartInc-1]['name']=itemName;
		cart[cartInc-1]['quantity']=itemQuantity;
		cart[cartInc-1]['number']=itemNumber;
		cart[cartInc-1]['price']=itemPrice;
		if ((itemPrice*itemQuantity)>highestPrice) {
			highestCartInc = cartInc;
			highestPrice = (itemPrice*itemQuantity);
		};
		cartSoftwareCount += software;
	});
	$(".paypalSubmit").append("<input type=\"hidden\" name=\"num_cart_items\" class=\"dynamicInput\" value=\""+cartInc+"\">"
		+ "<input type=\"hidden\" name=\"mc_gross\" class=\"dynamicInput\" value=\""+$("#checkoutCartTotalPrice").text()+"\">");
	$("input[name='num_cart_items']").val(cartInc);
	$("input[name='mc_gross']").val($("#checkoutCartTotalPrice").text());
	$(".paypalSubmit").append("<input type=\"hidden\" name=\"total\" value=''>");	// for new cart
	$("input[name='total']").val($("#checkoutCartTotalPrice").text());	// for new cart
	$("input[name='shipping_1']").val($("#checkoutCartShippingPrice").text());
	$(".paypalSubmit").append("<input type=\"hidden\" name=\"tax\" value=''>");	// for new cart (not used)
	$(".paypalSubmit").append("<input type=\"hidden\" name=\"shippingPrice\" value=''>");	// for new cart
	$("input[name='shippingPrice']").val($("#checkoutCartShippingPrice").text());	// for new cart
	custom['refid']=refid;	// store referral
//	custom['order_number']='';	// placeholder - removed because space is limited in paypal custom field
	custom['coupon_code']=$("#couponCodeInput").val();
	custom['coupon_discount']=$("#couponDiscount").html();
	custom['coupon_total']=$("#couponPaypal").text();
	custom['software_only']=(cartSoftwareCount==cartInc);
	if (custom['software_only']) custom['shipping_code']="EMAIL";
	else custom['shipping_code']=$("#checkoutCartShippingSelect").val();
	
	// promoting custom variable to first-class citizens.  Paypal shouldn't mind seeing them come through for a bit until we switch to the new system and discontinue custom
	$(".paypalSubmit").append("<input type=\"hidden\" name=\"refid\" value=''>");
	$("input[name='refid']").val(refid);
	$(".paypalSubmit").append("<input type=\"hidden\" name=\"couponCode\" value=''>");
	$("input[name='couponCode']").val($("#couponCodeInput").val());
	$(".paypalSubmit").append("<input type=\"hidden\" name=\"couponDiscount\" value=''>");
	$("input[name='couponDiscount']").val($("#couponDiscount").html());
	$(".paypalSubmit").append("<input type=\"hidden\" name=\"couponTotal\" value=''>");
	$("input[name='couponTotal']").val($("#couponPaypal").text());
	$(".paypalSubmit").append("<input type=\"hidden\" name=\"softwareOnly\" value=''>");
	if (cartSoftwareCount==cartInc) $("input[name='softwareOnly']").val("1");	// if this were an array, I could actually do a boolean
	$(".paypalSubmit").append("<input type=\"hidden\" name=\"shippingCode\" value=''>");
	if (cartSoftwareCount==cartInc) $("input[name='shippingCode']").val("EMAIL");
	else $("input[name='shippingCode']").val($("#checkoutCartShippingSelect").val());
	
	
	$(".paypalSubmit").append("<input type=\"hidden\" name=\"custom\" value=''>");
	$("input[name='custom']").val(JSON.stringify(custom));	// two-step process keeps safari from caching value (why?!)
	$(".paypalSubmit").append("<input type=\"hidden\" name=\"cart\" value=''>");
	$("input[name='cart']").val(JSON.stringify(cart));	// 	for new cart
//	$(".copyrightTextBlack").append(JSON.stringify(custom));
	if ($("#couponPaypal").text()>0) {
		var amount_1 = roundNumber($("input[name='amount_"+highestCartInc+"']").val() - $("#couponPaypal").text()/$("input[name='quantity_"+highestCartInc+"']").val(),2);
		if (amount_1 <= 0) amount_1 = 0.01; // this finds the most expensive line item, and subtracts the full card discount from it (adjusted for item quantity)
		// also, if we don't round, paypal will choke on bad javascript precision errors (4.949999999...)
		// If no single line item has enough value, the discount will drop the prices to .01, but no lower.
		// if a $15 discount is split 7 ways, rounding to the cent will cause a 2 cent error.  Wish paypal supported discounts... 
		// OK, so this should go away as soon as we switch to the new paypal flow.  Guess they do support discounts with negative line items
		$("input[name='amount_"+highestCartInc+"']").val(amount_1);
//		alert(highestCartInc+" "+$("input[name='amount_"+highestCartInc+"']").val());
	}
	var shippingCode = $("#checkoutCartShippingSelect").val();

	// temp override for test
	if ($("body").hasClass("checkout_mobile")) $(".paypalSubmit").attr("action","https://www.paypal.com/cgi-bin/webscr?cmd=_-express-checkout-mobile&useraction=commit&token=valueFromSetExpressCheckoutResponse");
	
	if (test) {
		if (shippingData[$("#checkoutCartShippingSelect").val()].type=="international") {		
			$(".paypalSubmit").attr("action","https://www.tenonedesign.com/cart_process.php");
		}
		else {
			$(".paypalSubmit").attr("action","https://www.tenonedesign.com/cart_redirect.php");	
			$(".paypalSubmit").attr("method","get");
		}
		$(".paypalSubmit").submit();
		return;
	}
	if (shippingData[$("#checkoutCartShippingSelect").val()].type=="international") {		
		$(".paypalSubmit").attr("action","https://www.tenonedesign.com/cart_process.php");
	}
	else {
		$(".paypalSubmit").attr("action","https://www.tenonedesign.com/cart_redirect.php");	
		$(".paypalSubmit").attr("method","get");
	}


 	//if (shippingData[$("#checkoutCartShippingSelect").val()].type=="international" || true) $(".paypalSubmit").attr("action","https://www.paypal.com/cgi-bin/webscr");
 	$(".paypalSubmit").submit();
 	return;
}
