var productDetailDefaultTab = "";

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(){
	
	setupZoom();
	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() {
		var myName = cssStringWithString($(this).children("a").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 false
	});
	$(".productDetailMenu li").eq(productDetailDefaultTab).click();
	$(".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
	});
	if ($("body#autograph").length) {
		if (navigator.userAgent.indexOf("10_6")!=-1 || navigator.userAgent.indexOf("10.6")!=-1) {	// is SL?
			$("#snowLeopardDetected").show();
		}
		else if ($("body#autograph").length && navigator.userAgent.indexOf("OS X")!=-1) {
			$("#snowLeopardNotDetected").show();
		}	// is it Mac OS at least, so we can tease?
	}	// snow leopard detection
	
	// 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"','',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
		$("#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();
	});
	$(".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.charCode || 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 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()<10) 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>'
	+	'	            </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 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");
		// 		}
		// 	});	
		// }

	});	
	// for promotion
	// if (promotionActive==0){
	// 	$("#couponExplanation").html(oldCouponExplanation);
	// 	$("#couponDiscount").html(oldCouponDiscount);
	// 	$("#couponCodeInput").val(oldCouponInput);
	// 		$("#couponExplanation").html("");
	// 		$("#couponDiscount").html("0,0,0,");
	// 		$("#couponCodeInput").val("");
	// }
	// $("#couponInvite").hide();
	// $("#couponCodeInput").hide();
	// $("#couponApply").hide();
	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());
	$.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 = {}
//		custom['cart'][cartInc-1]=cartArray;
//		custom['cart'][cartInc-1]['name']=itemName;
//		custom['cart'][cartInc-1]['quantity']=itemQuantity;
//		custom['cart'][cartInc-1]['number']=itemNumber;
//		custom['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());
	$("input[name='shipping_1']").val($("#checkoutCartShippingPrice").text());
	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();
	$(".paypalSubmit").append("<input type=\"hidden\" name=\"custom\" value=''>");
	$("input[name='custom']").val(JSON.stringify(custom));	// two-step process keeps safari from caching value (why?!)
//	alert(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... 
		$("input[name='amount_"+highestCartInc+"']").val(amount_1);
//		alert(highestCartInc+" "+$("input[name='amount_"+highestCartInc+"']").val());
	}
	var shippingCode = $("#checkoutCartShippingSelect").val();
	if (shippingData[$("#checkoutCartShippingSelect").val()].type=="international") $(".paypalSubmit").attr("action","https://www.paypal.com/cgi-bin/webscr");
	setTimeout("$(\".paypalSubmit\").submit();",200);	// I think this just leaves a little time (700ms) to report the purchase button click.  I'm dropping to 200 with no report.
	
}