//
//custom estore with donation
//
var giftamount = 0;

if (document.location.href.indexOf("supporter.asp") > 0) {
	//remove existing shopping cart
	$('#TableCartOuter').remove();

	//force width of page
	$('#estore table:eq(0)').attr("width","640");
	
	//display loading message
	var loading = $("<div id='loading'>Loading... <img src='/atf/cf/{E76FD46F-EF16-484F-9548-4314617B3E8F}/loading.gif' /></div>");
	$('#header').after($(loading));
	
	//change billing info header to new format
	$('#TableInner tr.CTsubtitle td font:contains("Billing Information")')[0].innerHTML = "<div class='section'><span class='title'>6</span><span class='ECRelatedFeatured1Label'><b>Billing Information</b></span></div>";

	//change shipping info header to new format
	var shiptitle = "<tr class='shiptitle'><td colspan=3><div class='section'><span class='title'>7</span><span class='ECRelatedFeatured1Label'><b>Shipping Address</b></span></div></td></tr>";
	$('font:contains("Billing and Shipping address")').parent().parent().before($(shiptitle));
	//remove default shipping header
	$('#TableInner tr.CTsubtitle td font:contains("Shipping Address")').parent().parent().remove();
	
	//rewrite already registered link
	var chkAR = $('font:contains("Already Registered")');
	if (chkAR.length > 0) {
		chkAR[0].innerHTML = "<a href='#' onclick='javascript:window.open(\"../home/loginpopup.asp?c=grLOK5PDLmF&b=5105447&Caller=%2Fsite%2Fapps%2Fka%2Fec%2Fsupporter%2Easp%3Fc%3DgrLOK5PDLmF%26b%3D5105447\",\"loginwin\",\"menubar=no,scrollbars=yes,resizable=yes,width=625,height=400\")'>Click here</a> to login if already registered";
	}
	
	//change submit button to image
	$('#TableButton td')[0].innerHTML = '<input type="image" src="/atf/cf/{e76fd46f-ef16-484f-9548-4314617b3e8f}/btn_submit.gif" name="SubmitButton" id="SubmitButton" value="Submit"  class="HtmlButton" >';
	
	//override onsubmit function
	document.getElementById('FormSupporter').onsubmit = function(){return CheckFormNew(document.SUPPORTER);};
	
	//preset shipto country to US
	$('select[name=ShiptoCountry]').val('US');
	
	//preselect member
	$('input[name=Field4853338]:eq(0)').attr("checked","checked");
	
	//so that loading will display - pause then rebuild page
	setTimeout(function(){buildPage();},0);
} else {
	if(document.location.toString().indexOf("category.asp") > 0){
		document.write("<style type=text/css>");
		document.write("#catalog_intro { display:block}");
		document.write("</style>");
		$('#estore').hide();
		postNewItem();
		
	} else {
	
		//-------------------------------------------------
		//ALL OTHER PAGES THAT ARE NOT THE SUPPORTER PAGE
		//-------------------------------------------------
		//move donation total above the name/descr
		//-------------------------------------------------	
		$('#estore').hide();
		//on credit card page
		$('#TableCartInner tr:eq(0)').before($('#TableCartInner tr.CTsubtitle:eq(1)'));
		$('#TableCartInner td.CTtablein:eq(0)').attr("colspan","1")
												.attr("align","left");
		//bold donation title
		$('#TableCartInner td.CTtablein:eq(0) font').attr("style","font-weight:bold");
	
		//on orderok page
		if (document.location.href.indexOf("orderok.asp") > 0) {
			$('#estore table:eq(8)').attr("id","dontable");
			$('#estore #dontable tr:eq(0)').remove();
			$('#estore #dontable tr:eq(1)').remove();		
			$('#estore #dontable tr:eq(0) td:eq(0)').attr("width","50");
			$('#estore #dontable tr:eq(0) td:eq(0) font').attr("style","font-weight:bold");			
			$('#estore table:eq(7)').before($('#estore #dontable'));
			var support = '';
			switch ($.session("Field4812623")) {
				case "Radio" : support = "MPBN Radio";break;
				case "TV" : support = "MPBN Television";break;
				case "Both" : support = "Both MPBN Radio and Television";break;
			}
			if ($.session("recurring") > 0) {
				$('#estore #dontable').html($('#estore #dontable').html().replace(($.session("recurring")+".00"),($.session("recurring")+".00/Month to support "+support)));
			} else {
				$('#estore #dontable').html($('#estore #dontable').html().replace(($.session("donation")+".00"),($.session("donation")+".00 to support "+support)));
			}
			$('#softProductDownloadsTable').parent().parent().remove();
		}
		
		var html = $('#estore')[0].innerHTML;
		html = html.replace('<td class="CTtitle"><b><font class="CTtablein">Shopping Cart</font></b>',"<td><div class='section'><span class='title'>8</span><span class='ECRelatedFeatured1Label'><b>Selected Thank You Gift</b></span></div>");
		html = html.replace('<TD class=CTtitle><B><FONT class=CTtablein>Shopping Cart</FONT></B>',"<td><div class='section'><span class='title'>8</span><span class='ECRelatedFeatured1Label'><b>Selected Thank You Gift</b></span></div>");
		html = html.replace("Shopping Cart","Selected Thank You Gifts");
		html = html.replace("Additional Donation Sub total","Donation");
		html = html.replace("Additional Donation","Donation");
		html = html.replace("Grand Total","Donation");	
		html = html.replace("Name","Thank You Gift");
		html = html.replace("Order&nbsp;#","Donation #");
		$.sessionStart();		
		if (document.location.href.indexOf("orderok.asp") < 0) {
			if ($.session("recurring") > 0) {
				//var dollar = new RegExp("0.00");
				html = html.replace(($.session("recurring")+".00"),($.session("recurring")+".00/Month"));
			}
		}
		html = html.replace("following summarizes your order","following summarizes your donation");
		$('#estore')[0].innerHTML = html;
		$('#TableCartInner tr.CTodd, #TableCartInner tr.CTeven, #TableCartInner tr.CTsubtitle:eq(1), .CTtablein tr.CTodd, .CTtablein tr.CTeven, .CTtablein tr.CTsubtitle:eq(0)').each(function(){
			$(this).find('td:eq(4)').remove();
			$(this).find('td:eq(3)').remove();
			$(this).find('td:eq(2)').remove();
		});
		$('#TableCartInner tr.CTsubtitle:eq(2), #estore tr.CTsubtitle:eq(2)').remove();
		$('#TableCartInner td.CTtablein:eq(0)').attr("colSpan","1");
		$('#TableCartInner td.CTtablein:eq(0)').attr("width","50");		
		if (document.location.href.indexOf("AdditionalInfoEC.asp") > 0) {
			//$.sessionStart();
			$(document).ready(function(){
				$('input[name=Field4860708]').val(($.session("recurring") != undefined) ? "/Month" : "");
				$('input[name=Field4855919]').val(($.session("recurring") != undefined) ? $.session("recurring") : 0);
				$('input[name=Field4855669]').val($.session("Field4855669"));
				$("input[name=Field4812623]").each(function(){if (this.value == $.session("Field4812623")) {$(this).val($.session("Field4812623"));$(this).attr("checked","checked");}});
				$.sessionStop();
				$('#Submit1').click();
			});
		}
		
		if (document.location.href.indexOf("CreditCardInfoEC.asp") > 0) {
			document.getElementsByTagName('form')[0].id="FormCC";
			//change submit button
			if ($('.HtmlButton').length > 0) $('.HtmlButton').parent().html('<input type="image" src="/atf/cf/{e76fd46f-ef16-484f-9548-4314617b3e8f}/btn_submit_donation.gif" name="SubmitButton" id="SubmitButton" value="Submit"  class="HtmlButton" >');
			
			//override submit button	
			$(document).ready(function(){
				//hard code table width - styles not working
				$('#TableCartInner').attr('width','635');
				document.getElementById('FormCC').onsubmit = function(){
					//store cc fields
					//$.sessionStart();
					//store values needed for credit card form
					$('#estore input').each(function(){
						if (this.name != '' || this.value != undefined) $.session(this.name,this.value);
					});
					$('#estore select').each(function(){
						if (this.name != '' || this.value != undefined) $.session(this.name,this.value);
					});
					$.sessionStop();
					return CheckForm(document.creditInfoForm);
				};
			});
		}
		
		if (document.location.href.indexOf("orderok.asp") > 0) {
			var orderheading = "<div class='section'><span class='title'>9</span><span class='ECRelatedFeatured1Label'><b>Donation Completed</b></span></div>";
			orderheading += "<div><h3>Thank you for your donation to MPBN!</h3></div>";	
			$('#TableOrder').before($(orderheading));
			$('#estore table tr font:contains("system-generated email")').parent().parent().hide();
			$('#contentBottom').show();
			$('#estore font:contains("(PT)")').remove();
			//$.sessionStart();	
			if ($.session("recurring") > 0) {
				var postfields = $.getSessionData();
				var postdollar = $.session("recurring");
				var currdate = new Date();
				for (x=0;x<60;x++) {
					postfields['Amount'+(x+1)] = postdollar;
					postfields['PaymentDate'+(x+1)] = formatdate(new Date(currdate.setMonth(currdate.getMonth()+1)))
				}
				$.post("/site/apps/ka/sd/donateprocess.asp?c=grLOK5PDLmF&b=5129629",postfields,function(){$.sessionInit()});
			}
			//by not doing session stop session vars are cleared
			//$.sessionStop();	
		}
		
		if (document.location.href.indexOf("AdditionalInfoEC.asp") < 0) {
			$('#estore').fadeIn();
		};
	}
}

function buildPage() {

	//this will set up position on the form
	$('a:contains("Order More Items")').each(function(){
		//put all new content where the order items link is
		//if (this.innerHTML == "Order More Items") {
			//get parent
			var featured = $(this).parent();
			//clear current link
			this.innerHTML = '';
			var loading = $('<div id="loadingpopup"></div>');
			$('.CheckoutStep1').before($(loading));
			$('.CheckoutStep1').parent().attr("align","left");
			var nogift = $('<div id="nogift"></div>');
			$(featured).append($(nogift));
			//var div = document.createElement("div");
			//div.id = "loadingpopup";
			//var bod = document.getElementsByTagName('body')[0];
			//bod.appendChild(div);
			//create fetured item area
			var featureditems = "<div class='section'><span class='title'>4</span><span class='ECRelatedFeatured1Label'><b>Choose a Thank You Gift</b></span></div><input type='checkbox' id='nogiftchk' value='nogift' onclick='noGifts(this)'/> No thank you gifts please. I would like my entire donation to support programming.<div id='featuredwrapper'><h3>Featured Thank You Gifts</h3><div id='featured'></div></div>";
			$(featured).append($(featureditems));
			//create all catalog items area
			var listitems = "<div id='listitemswrapper'><br /><br /><a name='showall'></a><span id='showall'><input type='button' onclick='showAllItems()' value='Browse All Thank You Gifts'/></span><div id='listitems' style='display:none'></div></div>";
			$(featured).append($(listitems));
			//get featured catalog
			//create donation field
			showFeaturedItems();
			var donation = "<div class='donation'>";
			donation += "<div class='section'><span class='title'>1</span><span class='ECRelatedFeatured1Label'><b>I want to be an Evergreen Friend</b> </span> - <a href='/site/lookup.asp?c=grLOK5PDLmF&b=5129599'><i>Click here for more info</i></a></div>";
			donation += '<div style="padding-top:10px;padding-left:5px"><input name="PledgeLevelID" onclick="SetDAmount(\'recurring\');" id="Radio1" type="radio"> Evergreen Friend at $';
			donation += "<input size='15' maxlength='250' name='rec_donation_amount' id='rec_donation_amount' value='' type='text' onblur='recurringDonation(this)' /> per month (minimum of $5/month)</div>";
			donation += "<br />";
			donation += "<div class='section'><span class='title'>2</span><span class='ECRelatedFeatured1Label'><b>I would rather make a one-time donation</b></span></div>";
			donation += '<div style="padding-left:5px"><input name="PledgeLevelID" value="106379" onclick="SetDAmount(35);" id="Radio1" type="radio"> $35.00';
			donation += '<input name="PledgeLevelID" onclick="SetDAmount(60);" id="Radio1" type="radio"> $60.00';
			donation += '<input name="PledgeLevelID" onclick="SetDAmount(90);" id="Radio1" type="radio"> $90.00';
			donation += '<input name="PledgeLevelID" onclick="SetDAmount(120);" id="Radio1" type="radio"> $120.00';
			donation += '<input name="PledgeLevelID" onclick="SetDAmount(150);" id="Radio1" type="radio"> $150.00';
			donation += '<input name="PledgeLevelID" onclick="SetDAmount(240);" id="Radio1" type="radio"> $240.00';
			donation += '<input name="PledgeLevelID" onclick="SetDAmount(500);" id="Radio1" type="radio"> $500.00';
			donation += '<input name="PledgeLevelID" onclick="SetDAmount(1000);" id="Radio1" type="radio"> $1000.00</div>';
			donation += '<div style="padding-top:10px;padding-left:5px"><input name="PledgeLevelID" onclick="SetDAmount(\'other\');" id="Radio1" type="radio"> SURPRISE US: ';
			donation += "&nbsp;&nbsp;&nbsp;<input size='15' maxlength='250' name='other_donation_amount' id='other_donation_amount' value='' type='text' onblur='standardDonation(this)' /><input name='donation_amount' id='donation_amount' value='' type='hidden' />";
			//donation += "&nbsp;&nbsp;&nbsp;<select id='recurring' onchange='recurringDonation(this)'><option value='single'>Single</option><option value='monthly'>Monthly</option</select>";
			donation += "</div></div>";
			donation += "<div class='section'><span class='title'>3</span><span class='ECRelatedFeatured1Label'><b>I would like my contribution to support</b> </span></div>";
			donation += "<div id='support' style='text-align:left;padding-left:10px'>";			
			donation += '<input name="Field4812623" value="Radio" type="radio"> Radio&nbsp;&nbsp;&nbsp;';
			donation += '<input name="Field4812623" value="TV" type="radio"> TV&nbsp;&nbsp;&nbsp;';
			donation += '<input name="Field4812623" value="Both" type="radio"> Both&nbsp;&nbsp;&nbsp;';
			donation += "</div>";
			donation += "<br />";			
			$(featured).before($(donation));
			//create cart area
			var showitems = $("<div id='showitems' style='display:none'><input type=button onclick='clearItem(\"loading\")' value='Clear selected gift and redisplay' id='cleargifts'/></div>");
			$(featured).append($(showitems));
			//create cart area
			var cart = $("<div id='cart'></div>");
			$(featured).append($(cart));
			//temp html storage
			var temp = $("<div id='temp' style='display:none'></div>");
			$(featured).append($(temp));			//update totals
			updateTotal('noloading');	
			//remove loading popup
			//display estore
			return true;
		//}
	});
}

function noGifts(e) {
	if (e.checked) {
		giftamount = 0;
		//hide shipping info
		var hide = false;
		$('#TableInner tr').each(function(){
			if ($(this).find('#CheckAddress').length > 0) {
				hide = true;
			}
			if (hide) $(this).hide();
		});
		clearItem('nogift');
		$('.shiptitle').hide();
		$('#featuredwrapper').slideUp();
		$('#listitemswrapper').slideUp();
	} else {
		var show = false;
		$('#TableInner tr').each(function(){
			if ($(this).find('#CheckAddress').length > 0) {
				show = true;
			}
			if (show) $(this).show();
		});
		$('.shiptitle').show();		
		$('#featuredwrapper').slideDown();
		$('#listitemswrapper').slideDown();
	}

}

function SetDAmount(amt) {
	if (amt == 'recurring') amt = $('#rec_donation_amount').val();
	if (amt == 'other') amt = $('#other_donation_amount').val();
	$('#rec_donation_amount').val('');
	$('#other_donation_amount').val('');	
	$('#donation_amount').val((amt == 0) ? '' : amt);
	if (amt != '') updateTotal('noloading');
}

function showFeaturedItems() {
	$.get("/site/apps/ka/ec/category.asp?c=grLOK5PDLmF&b=5107469&CategoryID=253141",function(data){
		$('#featured')[0].innerHTML = "<table>"+$(data).find('#RelatedProductsInnerTable').html()+"</table>";
		$('#featured .CTtitle:eq(0)').remove();
		//get all catalog items
		//getCatalogItems();
		$('#featured td.ECRelatedFeatured1OddRow').each(function(i){
			var href = $(this).html().match(/ProductID=\d+/g);
			var amt = $(this).html().match(/class=\"tdg\" alt=\"\d+\"/g);
			if (amt == null) amt = $(this).html().match(/class=tdg alt=\"\d+\"/g);
			var amttotal = 0;
			if (amt != null) amttotal = amt[0].match(/\d+/g);
			var img = "<div class='addtocart' style='cursor:pointer'><img src='https://www.kintera.com/accounttempfiles/account14128/images/cart.gif' alt='Add to cart' onclick='addtocart("+href[0].match(/\d+/g)+","+amttotal+")' /></div>";
			$(this).append(img);
		});
		$('#featured td.ECRelatedFeatured1OddRow a').each(function(i){
			this.href = "javascript:void(0)";
		});
		$('#loading').remove();
		$('#estore').fadeIn();	
	});
}

function showAllItems(page,keyword) {
	if ($('#showitems')[0].style.display != 'none') {
		alert('A Thank You gift has already been selected!');
	} else {
		if (page == undefined) page=1;
		if (keyword == undefined) keyword='';
		$('#showall input').after($(" <img src='/atf/cf/{E76FD46F-EF16-484F-9548-4314617B3E8F}/loading.gif' border=0/>"));
		$.post("/site/apps/ka/ec/searchit.asp?c=grLOK5PDLmF&b=5107469",{Page:page,ProductKeyPrice:"1",priceSearchOpt:"2",ProductKeyword:keyword,IsAdvancedSearch:"N",IsPostBack:"N",ProductPageSize:500},function(data2) {
			//html from sphere is bad and causes find within data2 to hang in IE - had to write differently for IE
			if ($.browser.msie) {
				$('#listitems')[0].innerHTML = "<table>"+data2+"</table>"; //$(data2).;
				$('#listitems')[0].innerHTML = "<span id='search'>"+$('#listitems #SearchForm').html() + "</span>" + $('#listitems .CTtablein td:eq(0)').html() + "<span id='listitemsinner'>"+$('#listitems #TableOuter').html()+"</span>" + $('#listitems .CTtablein td:eq(0)').html();
				$('#listitems')[0].innerHTML = $('#listitems')[0].innerHTML.replace("Search Result","");
				//$('#listitems')[0].innerHTML = $.htmlClean($('#listitems').html());
			} else {
				$('#listitems')[0].innerHTML = "<span id='search'>"+$(data2).find("#SearchForm").html() + "</span>" + $(data2).find(".CTtablein td:eq(0)").html();
				$('#listitems')[0].innerHTML += "<span id='listitemsinner'>"+$(data2).find("#TableInner").html()+"</span>" + $(data2).find(".CTtablein td:eq(0)").html();
			}
			$('#listitems #search table:eq(0) tr:eq(0)').remove();
			$('#listitems #search table:eq(0) tr:eq(0) a:eq(0)').remove();		
			$('#listitems input[type=image]').each(function(i){
				var amt = $(this).parent().parent().html().match(/class=\"tdg\" alt=\"\d+\"/g);
				if (amt == null) amt = $(this).parent().parent().html().match(/class=tdg alt=\"\d+\"/g); //for IE
				var amttotal = 0;
				if (amt != null) amttotal = amt[0].match(/\d+/g);
	
				var img = "<span class='addtocart' style='cursor:pointer'><img src='https://www.kintera.com/accounttempfiles/account14128/images/cart.gif' alt='Add to cart' onclick='addtocart("+$('input[name="ProductID"]')[i].value+","+amttotal+",\"f\")' /></span>";
				$(this).parent().append(img);
				$(this).remove();
			});
			$('#listitems #Submit1').click(function(){
				SetSearch($('#ProductKeyword').val());
			});
			$('#listitems a').each(function(i){
				if (this.href.indexOf("product.asp") > 0) this.href = "javascript:void(0)";
			});
			$('#listitems tr').each(function(){$(this).find('td:eq(3)').remove()});
			$('#listitems').slideDown();
			$('#showall').hide();
		});
	}
}

function SetSearch(keyword) {
	$('#listitems')[0].innerHTML = "Loading... <img src='/atf/cf/{E76FD46F-EF16-484F-9548-4314617B3E8F}/loading.gif' />";
	showAllItems(1,keyword);
}
function SetPage(page) {
	$('#listitems')[0].innerHTML = "Loading... <img src='/atf/cf/{E76FD46F-EF16-484F-9548-4314617B3E8F}/loading.gif' />";
	showAllItems(page);
}
//add to cart
function addtocart(id,amt,type) {
	var chkval = $('#donation_amount').val();
	if ($("input[name=PledgeLevelID]:first").attr("checked")) {
		chkval = parseInt($('#rec_donation_amount').val())*12;
	}

	if (amt <= chkval) {
		if (chkval > 0) {
			if (type == 'f') $('#loadingpopup')[0].style.top = "800px";
			else $('#loadingpopup')[0].style.top = "500px";
			$('#loadingpopup')[0].innerHTML='<div id="bloadingpos"><div id="bloading-outer"><div id="bloading" class="shadow">Adding Thank You Gift... <img src="/atf/cf/{E76FD46F-EF16-484F-9548-4314617B3E8F}/loading.gif" /></div></div></div>';
			//$.ajax({
			//	async : false,
			//	type : "POST",
			//	url : "/site/apps/ka/ec/addtobasket.asp?c=grLOK5PDLmF&b=5105447",
			//	data : {ProductID:id,StoreID:""},
			//	success : updateTotal,
			//	error : reloadPage
			//})
			$.post("/site/apps/ka/ec/addtobasket.asp?c=grLOK5PDLmF&b=5105447",{ProductID:id,StoreID:""},function(){	updateTotal();});
		}
	} else {
		alert("Item selected is greater than donation specified!");
	}
}

function standardDonation(e) {
	if (e.value != '') {
		$('#rec_donation_amount').val('');
		var recval = $('#other_donation_amount').val();
		//$('#rec_donation_amount')[0].value = '';
		$("input[name=PledgeLevelID]:last").attr("checked","checked");
		$('#donation_amount')[0].value = $('#other_donation_amount').val();
		updateTotal('noloading');
	}
}

function recurringDonation(e) {
	if (e.value != '') {	
		var recval = $('#rec_donation_amount').val();
		if ( recval < 5 && recval > 0 && recval != '') {
			alert("A minimum of $5 is required to be an Evergreen Friend!");
			$('#rec_donation_amount').focus();
		} else {
			$('#other_donation_amount').val('');		
			$('#donation_amount').val($('#rec_donation_amount').val());
			$("input[name=PledgeLevelID]:first").attr("checked","checked");
			updateTotal('noloading');
		}
	}
}

//update totals
function updateTotal(noloading) {
	var chkval = $('#donation_amount')[0];
	if ($("input[name=PledgeLevelID]:first").attr("checked")) chkval = $('#rec_donation_amount')[0];
	if ($("input[name=PledgeLevelID]:last").attr("checked")) chkval = $('#other_donation_amount')[0];
	if (CheckAmount(chkval)) {
		var rval = chkval.value;
		if ($("input[name=PledgeLevelID]:first").attr("checked")) rval = (parseInt($('#rec_donation_amount').val())*12);
		if (rval < giftamount) {
			alert("Amount specified less than gift selected!\n\n Donation amount changed to gift value.\n If you wish to change the donation level then clear the selected gift and enter a new donation amount.");
			if ($("input[name=PledgeLevelID]:first").attr("checked")) $('#rec_donation_amount').val((giftamount == 0) ? '' : giftamount);
			if ($("input[name=PledgeLevelID]:last").attr("checked")) $('#other_donation_amount').val((giftamount == 0) ? '' : giftamount);			
			$('#donation_amount').val((giftamount == 0) ? '' : giftamount);
			$("input[name=PledgeLevelID]:last").attr("checked","checked");
			updateTotal();
		} else {
			//if ($('#donation_amount')[0].value > 0) $('#rec_donation_amount')[0].value = '';
			if (noloading != 'noloading') {
				$('#loadingpopup')[0].innerHTML='<div id="bloadingpos"><div id="bloading-outer"><div id="bloading" class="shadow">Calculating Totals... <img src="/atf/cf/{E76FD46F-EF16-484F-9548-4314617B3E8F}/loading.gif" /></div></div></div>';
			}
			var formvals = {};
			$.get("/site/apps/ka/ec/basket.asp?c=grLOK5PDLmF&b=5107469",function(data){
				$('#temp')[0].innerHTML = data;
				//set none selected to 0
				if ($("#temp #TableCartInner input").length > 2) $("#temp #TableCartInner td:contains('None selected')").parent().find('input:eq(1)').val('0');
				$("#temp #TableCartInner input").each(function(i){
					//if (($("#temp #TableCartInner input").length > 2) && ($(this).parent().parent().html().indexOf("None selected") > 0) && this.type=="text")
					//	formvals[this.name] = 0;
					//else 
						formvals[this.name] = this.value;
						if (this.name.match("ProductQty")) {
							var num = RegExp(/\d+/);
							formvals["ProductVDonation"+this.name.match(num)] = $('#donation_amount').val();
						}
				});
				//get current shopping cart and get additional donation amount
				$("#temp #Table6 input").each(function(){
					//formvals[this.name] = $('#donation_amount').val();
				});
				$('#temp')[0].innerHTML = '';
				formvals["Recalculate"] = "Update";
				//$('#cart')[0].innerHTML = "Recalculating";
				$.ajax({
					async : false,
					type : "POST",
					url : "/site/apps/ka/ec/count.asp?c=grLOK5PDLmF&b=5107469",
					data : formvals,
					success : reloadCart,
					error : reloadPage
				})
			});
		}
	}
}

function reloadPage() {
	alert("page timed out");
	postNewItem();
}

function reloadCart(){
	$.get("/site/apps/ka/ec/supporter.asp?c=grLOK5PDLmF&b=5107469",function(data){
		$('#temp')[0].innerHTML = data;
		var html = $('#temp #TableCartOuter').html();
		html = html.replace('<td class="CTtitle"><b><font class="CTtablein">Shopping Cart</font></b>',"<td><div class='section'><span class='title'>5</span><span class='ECRelatedFeatured1Label'><b>Selected Thank You Gift</b></span></div>");
		html = html.replace('<TD class=CTtitle><B><FONT class=CTtablein>Shopping Cart</FONT></B>',"<td><div class='section'><span class='title'>5</span><span class='ECRelatedFeatured1Label'><b>Selected Thank You Gift</b></span></div>");
		html = html.replace("Additional Donation","Donation");
		$('#cart')[0].innerHTML = "<table cellspacing=0 cellpadding=0>"+html+"</table>";
		$('#temp')[0].innerHTML = '';
		giftamount = ($('#cart .tdg').attr('alt') != '') ? $('#cart .tdg').attr('alt') : '';
		//hide quantity price and total
		$('#TableCartInner tr.CTodd, #TableCartInner tr.CTeven, #TableCartInner tr.CTsubtitle:eq(0)').each(function(){
			$(this).find('td:eq(4)').remove();
			$(this).find('td:eq(3)').remove();
			$(this).find('td:eq(2)').remove();
		});
		//hide total column
		$('#cart #TableCartInner tr.CTsubtitle:ge(1)').remove();
 		$('#loadingpopup')[0].innerHTML = '';
		//if an item has already been selected the hide thank yous
		if ($("#cart").html().indexOf("None selected") == -1) {
			//scrollTo(0,800);
			$('#featuredwrapper').slideUp();
			$('#listitemswrapper').slideUp();
			$('#showitems').show();
		}
		if ($('#donation_amount')[0].value == 0) $('#donation_amount')[0].value = '';
	});
}

function clearItem(nogift) {
	//post in "thank you gift not selected"
	if (nogift == 'loading') $('input#cleargifts').after($(" <span id='cleargiftsloading'><img src='/atf/cf/{E76FD46F-EF16-484F-9548-4314617B3E8F}/loading.gif' border=0/></span>"));	
	$.ajax({
		type : "POST",
		url : "/site/apps/ka/ec/count.asp?c=grLOK5PDLmF&b=5107469",
		data : "Recalculate=Update",
		success: function(data){
		   $.post("/site/apps/ka/ec/addtobasket.asp?c=grLOK5PDLmF&b=5107469",{ProductID:"681815",StoreID:""},function(){
				updateTotal();
				$('#showitems').hide();
				$('#cleargiftsloading').remove();
				if (nogift != 'nogift') {
					$('#featuredwrapper').slideDown();
					$('#listitemswrapper').slideDown();
				}
		   })
		}
	});
}

function CheckAmount(pointer){
	if (pointer.value == '') {
		return true;
	}
	var returnValue, amountValue;
	for(i = 0; i <= pointer.value.length -1; i++) 
		pointer.value = pointer.value.replace(",","");
	amountValue = jsDV_strTrim(pointer.value);
	if(amountValue != ""){
		returnValue = jsDV_isValidMoney(amountValue)
	   	if(returnValue == "-1") { 
	       	alert("Please enter a valid amount");
	       	pointer.value = "";
	       	pointer.focus();
	       	return false; 
		} 
		else {
			pointer.value = returnValue;
			return true;
		}
	}
	return true;
}
//override default field check
function CheckFormNew(thisform) {
	focus_field = "";
	warning = "";
	if (!$("input[name=PledgeLevelID]:first").attr("checked")) warning=checkField($('#donation_amount')[0],"Donation Amount",warning);
	warning=checkRadioCheckbox($('input[name=Field4812623]'),"I would like my contribution to support",warning);	
	warning=checkField(thisform.first_name,"First Name",warning);
	warning=checkField(thisform.last_name,"Last Name",warning);
	warning=checkField(thisform.email_address,"Email",warning);
	warning=checkField(thisform.address_line_1,"Address Line 1",warning);
	warning=checkField(thisform.city,"City",warning);
	warning=checkSelect(thisform.state,"State",warning);
	warning=checkField(thisform.zip,"ZIP/Postal Code",warning);
	warning=checkSelect(thisform.marketing_source,"What prompted your donation today?",warning);
	warning=checkRadioCheckbox(thisform.Field4853338,"Are you a new member?",warning);
	if ($('#nogiftchk:checked').length == 0) {
		warning=checkField(thisform.ShiptoAddress1,"Shipping Address Line 1",warning);
		warning=checkField(thisform.ShiptoCity,"Shipping City",warning);
		warning=checkField(thisform.ShiptoZip,"Shipping ZIP/Postal Code",warning);
		warning=checkSelect(thisform.ShiptoCountry,"Shipping ",warning);
	}
	if (warning!="") {
		warning="Please enter the following fields to continue:\n- "+warning+"";
		alert(warning);
		if (focus_field == $('#donation_amount')[0]) focus_field = $('#other_donation_amount')[0];
		if (warning.indexOf("I would like my contribution to support") < 0) focus_field.focus();
		return false;
	}
	

	if ((thisform.ShiptoZip != null) && (thisform.ShiptoCountry != null)) { 
		if (checkCountryZip(thisform.ShiptoZip,thisform.ShiptoCountry) == false) {
			thisform.ShiptoZip.focus();
			return false;
		}
	}
	if (thisform.email_address!=null)
		if (thisform.email_address.value!="")
			if (validEmail(thisform.email_address.value) == false)  {
				thisform.email_address.focus();
				return false;
			}
	if ((thisform.zip != null) && (thisform.country != null))
		if (checkCountryZip(thisform.zip,thisform.country) == false) {
			//alert("Please enter a valid zip code");
			thisform.zip.focus();
			return false;
		}

	if ((thisform.BillZip != null) && (thisform.BillCountry != null))
		if (checkCountryZip(thisform.BillZip,thisform.BillCountry) == false) {
			//alert("Please enter a valid zip code");
			thisform.BillZip.focus();
			return false;
		}
	
	thisform.action="supporteradd.asp?c=grLOK5PDLmF&b=5105447&en=buKLI0OHJ8JLK0POJpI0L4ONKoJ1LfN1IuKbF"; 
	$.sessionInit();
	$.sessionStart();
	//store values needed for credit card form
	$.session("donation",$('#donation_amount')[0].value);
	$.session("RecurringAmount",$('#rec_donation_amount')[0].value);	
	$.session("NumberOfPayments",60);	
	$.session("RecurringOption","Y");
	var currdate = new Date();
	$.session("RecurringDate",formatdate(new Date(currdate.setMonth(currdate.getMonth()+1))));	
	$.session("Individual","Y");
	$.session("Field4855919", $('#rec_donation_amount')[0].value);
	$.session("Field4855669",$("#cart #TableCartInner td:eq(0) font").text()); //thank you gift save for email and recurring donation form
	if ($("input[name=PledgeLevelID]:first").attr("checked")) {	
		$.session("recurring",$('#rec_donation_amount')[0].value);
		$.session("BillingScheduleID","0");
	}
	$('#estore input').each(function(){
		if (this.name != '' || this.value != undefined) $.session(this.name,this.value);
	});
	$('#estore select').each(function(){
		if (this.name != '' || this.value != undefined) $.session(this.name,this.value);
	});
	//get radio button values
	$.session("Field4812623",$("input[name=Field4812623]:checked").val());
	$.session("Field4853338",$("input[name=Field4853338]:checked").val());
	//billing info for donation form
	$.session("BillAddress1",$("input[name=address_line_1]").val());
	$.session("BillAddress2",$("input[name=address_line_2]").val());	
	$.session("BillCity",$("input[name=city]").val());
	$.session("BillState",$("select[name=state]").val());	
	$.session("BillZip",$("input[name=zip]").val());
	$.session("BillCountry",$("select[name=country]").val());	
	//override formid
	$.session("FormId","5");
	$.sessionStop();	
	return true;
}

function postNewItem(){
	//post in "thank you gift not selected"
	$.ajax({
		type : "POST",
		url : "/site/apps/ka/ec/count.asp?c=grLOK5PDLmF&b=5107469",
		data : "Recalculate=Update",
		success: function(data){
		   $.post("/site/apps/ka/ec/addtobasket.asp?c=grLOK5PDLmF&b=5107469",{ProductID:"681815",StoreID:""},function(){
			  location.href="/site/apps/ka/ec/supporter.asp?c=grLOK5PDLmF&b=5105447";
		   })
		},
		error :  function(err){
		   $.post("/site/apps/ka/ec/addtobasket.asp?c=grLOK5PDLmF&b=5107469",{ProductID:"681815",StoreID:""},function(){
			  location.href="/site/apps/ka/ec/supporter.asp?c=grLOK5PDLmF&b=5105447";
		   })
		}
	});
}

function formatdate(d) {
	try{
	return (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear();
	}catch(err){return false}
}
