//
//custom estore with donation
//
var giftamount = 0;
var totaldon = 0;
var tabdata = '';

if (document.location.href.indexOf("supporter.asp") > 0) {
	//remove existing shopping cart
	$('#TableCartOuter').remove();

	//force width of page
	$('#estore table:eq(0)').attr("width","700");
	
	//display loading message
	var loading = $("<div id='loading'><h1 style='padding:20px'>Loading ...</h1></div>");
	$('#estore').after($(loading));
	
	//change billing info header to new format
	$('#TableInner tr.CTsubtitle td font:contains("Billing Address")').html("<div class='section'><span class='stitle'>5</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='stitle'>6</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=luLRJaMQKpH&b=5152819&Caller=%2Fsite%2Fapps%2Fka%2Fec%2Fsupporter%2Easp%3Fc%3DluLRJaMQKpH%26b%3D5152819\",\"loginwin\",\"menubar=no,scrollbars=yes,resizable=yes,width=625,height=400\")'>Click here</a> to login if already registered";
	}
	
	//add a tag to the "please complete form" sentence so formatting can be added
	$('font:contains("Please complete the form below")').attr('id','complete_form');			
	$('#complete_form').parent().parent().hide();
	//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=Field4864124]:eq(0)').attr("checked","checked");
	
	//align checkbox right
	$('#CheckAddress').parent().parent().attr("style","text-align:right !important");
	$('#TableInner font').each(function(){
		if (this.innerHTML == "State:") {
			$(this).parent().html("State:*");
			return;
		}
	});
	
	//override submit button	
	$(document).ready(function(){
		//set onblur for comments
		$('textarea[name=Field4868723]').blur(function(){
			checkLength(this,250);
		});
	});
	
	//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("Field4850682")) {
				case RECodeRadio : support = "CPBN Radio";break;
				case RECodeTV : support = "CPBN Television";break;
				case RECodeBoth : support = "Both CPBN 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();
			$('#estore .CTtablein').after("<br />&nbsp;<p>Please print and retain a copy of this page for your records.  You will receive an email confirmation shortly.</p>");
		}
		
		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='stitle'>7</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='stitle'>7</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"));
				$('textarea[name=Field4850696]').val($.session("Field4850696")); //comments
				$("input[name=Field4850682]").each(function(){if (this.value == $.session("Field4850682")) {$(this).val($.session("Field4850682"));$(this).attr("checked","checked");}}); //tv or radio
				$('textarea[name=Field4884079]').val($.session("Field4884079")); //thank you gift
				$("input[name=event_source]").val($.session("Field4850682")); //source code
				$.sessionStop();
				$('#Submit1').click();
				//$('#estore').fadeIn();
			});
		}
		
		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='stitle'>8</span><span class='ECRelatedFeatured1Label'><b>Donation Completed</b></span></div>";
			orderheading += "<div><h3>Thank you for your donation to CPBN!</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=luLRJaMQKpH&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 = "<a name='choose'></a><div class='section'><span class='stitle'>1</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 gift please.  Put my entire donation toward great programs.<div id='featuredwrapper'><div id='featured'></div></div>";
			$(featured).append($(featureditems));
			//create all catalog items area
			var listitems = "<div id='listitemswrapper'><br /><br /><a name='showall'></a>";
			listitems += "<div style='float:right;padding-top:3px;font-size:12px'>Search <input name='ProductKeyword' id='ProductKeywordtabAll' value='' size='20' maxlength='250'><input tab='tab5' value='Go' class='HtmlButton' type='button' onclick='SetSearchAll(\"tab5\")'></div><div id='tabs' style='clear:both'><span id='showall'></span>";
			listitems += "<ul><li><a href='#tab1'><span class='featured'><u>FEATURED</u></span></a></li><li><a href='#tab2'><span>UConn Women's Basketball</span></a></li><li><a href='#tab3'><span>Red Carpet Series Tickets</span></a></li><li><a href='#tab4'><span>WNPR</span></a></li><li><a href='#tab5'><span>All</span></a></li></ul>";
			listitems += "<div id='tab1'><div id='listitems-tab1' class='tabdata'></div></div>";
			listitems += "<div id='tab2'><div id='listitems-tab2' class='tabdata'>Loading... <img class='loading' src='/atf/cf/{E76FD46F-EF16-484F-9548-4314617B3E8F}/loading.gif' border=0/></div></div>";
			listitems += "<div id='tab3'><div id='listitems-tab3' class='tabdata'>Loading... <img class='loading' src='/atf/cf/{E76FD46F-EF16-484F-9548-4314617B3E8F}/loading.gif' border=0/></div></div>";
			listitems += "<div id='tab4'><div id='listitems-tab4' class='tabdata'>Loading... <img class='loading' src='/atf/cf/{E76FD46F-EF16-484F-9548-4314617B3E8F}/loading.gif' border=0/></div></div>";
			listitems += "<div id='tab5'><div id='listitems-tab5' class='tabdata'>Loading... <img class='loading' src='/atf/cf/{E76FD46F-EF16-484F-9548-4314617B3E8F}/loading.gif' border=0/></div></div>";
			listitems += '<div id="tab10"></div>';
			listitems += '</div>';
			$(featured).append($(listitems));
			tabdata = $("#tabs").tabs({
				select : function(event, ui) {  
					//last tab
					if (ui.index == 1) {
						if ($('#listitems-tab2 .loading').length > 0) showAllItems("tab2",1,"","255251");
					};
					if (ui.index == 2) {
						if ($('#listitems-tab3 .loading').length > 0) showAllItems("tab3",1,"","255252");
					};
					if (ui.index == 3) {
						if ($('#listitems-tab4 .loading').length > 0) showAllItems("tab4",1,"","255255");
					};
					//last tab
					if (ui.index == 4) {
						if ($('#listitems-tab5 .loading').length > 0) showAllItems("tab5",1,"");	
					};
				}
			});

			//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));
			//
			var donation = "<div class='section'><span class='stitle'>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="Field4850682" value="'+RECodeBoth+'" type="radio" checked> Both TV and Radio&nbsp;&nbsp;&nbsp;';
			donation += '<input name="Field4850682" value="'+RECodeRadio+'" type="radio"> Radio&nbsp;&nbsp;&nbsp;';
			donation += '<input name="Field4850682" value="'+RECodeTV+'" type="radio"> TV&nbsp;&nbsp;&nbsp;';
			donation += "</div><br />";
			$(featured).append($(donation));
			
			//temp html storage
			var temp = $("<div id='temp' style='display:none'></div>");
			$(featured).append($(temp));
			showFeaturedItemsTab();
			//showAllItems("tab1",1,"","255256");
			
			//get featured catalog
			//create donation field
			var donation = "<div class='donation'>";
			donation += "<div id='recurr' style='display:none'><div class='section'><span class='stitle'>3</span><span class='ECRelatedFeatured1Label'><b>I want to be an Evergreen Friend</b> </span> - <a href='/site/lookup.asp?c=luLRJaMQKpH&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 /></div>";
			donation += "<div class='section'><span class='stitle'>4</span><span class='ECRelatedFeatured1Label'><b>One-time donation</b></span></div>";
			donation += '<div style="padding-left:5px">';
			donation += '<input name="PledgeLevelID" value="106379" onclick="SetDAmount(1000);" id="Radio1" type="radio"> $1000 (Leadership Circle)';
			donation += '<input name="PledgeLevelID" onclick="SetDAmount(500);" id="Radio1" type="radio"> $500 (Studio Society)';
			donation += '<input name="PledgeLevelID" onclick="SetDAmount(365);" id="Radio1" type="radio"> $365';
			donation += '<input name="PledgeLevelID" onclick="SetDAmount(240);" id="Radio1" type="radio"> $240';
			donation += '<input name="PledgeLevelID" onclick="SetDAmount(120);" id="Radio1" type="radio"> $120';
			donation += '<input name="PledgeLevelID" onclick="SetDAmount(60);" id="Radio1" type="radio"> $60';			
			donation += '</div>';
			donation += '<div style="padding-left:5px">';
			donation += '<input name="PledgeLevelID" onclick="SetDAmount(40);" id="Radio1" type="radio"> $40 (Basic Membership)';
			donation += '<input name="PledgeLevelID" onclick="SetDAmount(25);" id="Radio1" type="radio"> $25 (Student/Senior Level)';			
			donation += '</div>';
			donation += '<div style="padding-top:10px;padding-left:5px"><input name="PledgeLevelID" onclick="SetDAmount(\'other\');" id="Radio1" type="radio"> Other: ';
			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' />&nbsp;&nbsp;<small>(Surprise us by increasing your contribution now.  Simply change the amount in the box.)</small>";
			//donation += "&nbsp;&nbsp;&nbsp;<select id='recurring' onchange='recurringDonation(this)'><option value='single'>Single</option><option value='monthly'>Monthly</option</select>";
			donation += "</div></div>";
			$(featured).append($(donation));
			//update totals
			updateTotal('noloading');	
			//remove loading popup
			//display estore

			//$('.ui-corner-top').corners();
			
			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 < totaldon) {
		alert("The donation amount you entered is less than the minimum level for the thank-you gift you 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.");
		$('#donation_amount').val(totaldon);
		$('#other_donation_amount').val(totaldon);
		$("input[name=PledgeLevelID]:last").attr("checked","checked");		
	}
	if (amt != '') updateTotal('noloading');
}

function showFeaturedItemsTab() {
	$.get("/site/apps/ka/ec/category.asp?c=luLRJaMQKpH&b=5152827&CategoryID=253141",function(data){
		$('#listitems-tab1').html("<table>"+$(data).find('#RelatedProductsInnerTable').html()+"</table>");
		$('#listitems-tab1 .CTtitle:eq(0)').remove();
		//get all catalog items
		//getCatalogItems();
		$('#listitems-tab1 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/account401739/images/cart.gif' alt='Add to cart' onclick='addtocart("+href[0].match(/\d+/g)+","+amttotal+")' /></div>";
			$(this).append(img);
		});
		$('#listitems-tab1 td.ECRelatedFeatured1OddRow a').each(function(i){
			this.href = "javascript:void(0)";
		});
		$('#loading').remove();
		$('#estore').fadeIn();	
	});
}

function showFeaturedItems() {
	$.get("/site/apps/ka/ec/category.asp?c=luLRJaMQKpH&b=5152827&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/account401739/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(tab,page,keyword,categorynode) {
	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='';
		if (categorynode == undefined) categorynode='';		
		//$('#showall').html($(" <img src='/atf/cf/{E76FD46F-EF16-484F-9548-4314617B3E8F}/loading.gif' border=0/>"));
		$.post("/site/apps/ka/ec/searchit.asp?c=luLRJaMQKpH&b=5152827",{categoryNodeIDCheckedList:categorynode,Page:page,ProductKeyPrice:"99999",priceSearchOpt:"3",ProductKeyword:keyword,IsAdvancedSearch:"Y",IsPostBack:"N",selectedFilter:"1",Reload:"Y"},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-'+tab)[0].innerHTML = "<table>"+data2+"</table>"; //$(data2).;
				if ($('#listitems-'+tab+' .CTtablein td:contains("did not match any records")').length > 0) {
					$('#listitems-'+tab)[0].innerHTML = "<table>"+$('#listitems-'+tab+' table.CTtablein').html()+"</table>";
				} else {
					$('#listitems-'+tab)[0].innerHTML = "<span id='search'>"+$('#listitems-'+tab+' form:eq(0)').html() + "</span>" + $('#listitems-'+tab+' .CTtablein td:eq(0)').html() + "<span class='listitemsinner'>"+$('#listitems-'+tab+' #TableOuter').html()+"</span>" + $('#listitems-'+tab+' .CTtablein td:eq(0)').html();
					$('#listitems-'+tab)[0].innerHTML = $('#listitems-'+tab)[0].innerHTML.replace("Search Result","");
				}
				//$('#listitems')[0].innerHTML = $.htmlClean($('#listitems').html());
			} else {
				if ($(data2).find('.CTtablein td:contains("did not match any records")').length > 0) {
					$('#listitems-'+tab)[0].innerHTML = "<span class='listitemsinner'>"+$(data2).find("#TableInner").html()+"</span>";
				} else {
					$('#listitems-'+tab)[0].innerHTML = "<span id='search'>"+$(data2).find("#SearchForm").html() + "</span>" + $(data2).find(".CTtablein td:eq(0)").html();
					$('#listitems-'+tab)[0].innerHTML += "<span class='listitemsinner'>"+$(data2).find("#TableInner").html()+"</span>" + $(data2).find(".CTtablein td:eq(0)").html();
				}
			}
			$('#listitems-'+tab+' #search table:eq(0)').remove();			
			//$('#listitems-'+tab+' #search table:eq(0) tr:eq(0)').remove();
			//$('#listitems-'+tab+' #search table:eq(0) tr:eq(0) a:eq(0)').remove();
			$('#listitems-'+tab+' 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 amtval = $(this).parent().parent().parent().find('input[name=ProductID]').val();
				//var amtval = $('#listitems-'+tab+' input[name=ProductID]:eq('+i+')').val();
				var img = "<span class='addtocart' style='cursor:pointer'><img src='https://www.kintera.com/accounttempfiles/account401739/images/cart.gif' alt='Add to cart' onclick='addtocart("+amtval+","+amttotal+",\"f\")' /></span>";
				$(this).parent().append(img);
				$(this).remove();
			});
			$('#listitems-'+tab+' input[name=ProductKeyword]').attr("id","ProductKeyword"+tab);			
			$('#listitems-'+tab+' .HtmlButton:eq(0)').attr("tab",tab);
			$('#listitems-'+tab+' .HtmlButton:eq(0)').click(function(){
				SetSearch(tab,$('#listitems-'+tab+' #ProductKeyword'+tab).val(), categorynode);
			});
			$('#listitems-'+tab+' font.CT:eq(0) a, #listitems-'+tab+' font.CT:last a').each(function(){
			//$('#listitems-'+tab+' font.CT:eq(1) a').each(function(){
				var page = $(this).attr("href").match(/\d+/);
				$(this).click(function(){
					SetPage(tab, page, keyword, categorynode);
				});
				this.href = "javascript:void(0)";					
			});
			$('#listitems-'+tab+' a').each(function(i){
				//remove href from product link
				if (this.href.indexOf("product.asp") > 0) this.href = "javascript:void(0)";
			});
			$('#listitems-'+tab+' tr').each(function(){$(this).find('td:eq(3)').remove()});
			//in IE there are blank lines from bad html - need to remove
			$('#listitems-'+tab+' *').each(function(){if (this.tagName=='') $(this).remove();});
			if (keyword != '') $('#listitems-'+tab+' tr:eq(0)').before("<tr><td><a href='javascript:void(0);' onclick='SetSearch(\"tab5\",\"\")'>Show All</a></td></tr>");
			$('#showall').hide();
		});
	}
}


function SetSearchAll(tab) {
	$('#listitems-'+tab).html("Loading... <img src='/atf/cf/{E76FD46F-EF16-484F-9548-4314617B3E8F}/loading.gif' />");
	showAllItems(tab, 1, $('#ProductKeywordtabAll').val(), '');
	tabdata.tabs('select',4);
}
function SetSearch(tab, keyword, categorynode) {
	$('#listitems-'+tab).html("Loading... <img src='/atf/cf/{E76FD46F-EF16-484F-9548-4314617B3E8F}/loading.gif' />");
	showAllItems(tab, 1, keyword, categorynode);
}
function SetPage(tab, page, keyword, categorynode) {
	$('#listitems-'+tab).html("Loading... <img src='/atf/cf/{E76FD46F-EF16-484F-9548-4314617B3E8F}/loading.gif' />");
	showAllItems(tab, page, keyword, categorynode);
}
//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>';
  			//location.href="#choose";
			//$.ajax({
			//	async : false,
			//	type : "POST",
			//	url : "/site/apps/ka/ec/addtobasket.asp?c=luLRJaMQKpH&b=5152819",
			//	data : {ProductID:id,StoreID:""},
			//	success : updateTotal,
			//	error : reloadPage
			//})
			$.post("/site/apps/ka/ec/addtobasket.asp?c=luLRJaMQKpH&b=5152819",{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");
		if (recval < totaldon) {
			alert("The donation amount you entered is less than the minimum level for the thank-you gift you 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.");
			$('#other_donation_amount').val($('#donation_amount').val());
		}
		$('#donation_amount').val($('#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, updateitem, updateqty) {
	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 (updateqty == undefined) updateqty = 0;
	if (updateqty == 'update') updateqty = $("input[name=ProductQty"+updateitem+"]").val();
	if (CheckAmount(chkval)) {
		var rval = chkval.value;
		if ($("input[name=PledgeLevelID]:first").attr("checked")) rval = (parseInt($('#rec_donation_amount').val())*12);
		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=luLRJaMQKpH&b=5152827",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');
			//if remove item selected then set quantity to 0
			if (updateitem != undefined) $("#temp #TableCartInner input[name=ProductQty"+updateitem+"]").val(updateqty);
			totaldon = 0;
			$("#temp #TableCartInner .tdg").each(function(i){
				var multqty = $(this).parent().parent().parent().parent().find('input:eq(1)').val();
				totaldon = totaldon + (parseInt($(this).attr("alt")) * parseInt(multqty));
			});
			if (totaldon > $('#donation_amount').val()) {
				$("input[name=PledgeLevelID]:last").attr("checked","checked");
				$('#donation_amount').val(totaldon);
				$('#other_donation_amount').val(totaldon);
			}
			
			var donation_flag = false;
			$("#temp #TableCartInner input").each(function(i){
				formvals[this.name] = this.value;
				if (this.name.match("ProductQty") && (this.value != 0) && (!donation_flag)) {
					var num = RegExp(/\d+/);
					formvals["ProductVDonation"+this.name.match(num)] = $('#donation_amount').val();
					donation_flag = true;
				}
			});

			$('#temp').html('');
			formvals["Recalculate"] = "Update";
			if (donation_flag) {
				$.ajax({
					async : false,
					type : "POST",
					url : "/site/apps/ka/ec/count.asp?c=luLRJaMQKpH&b=5152827",
					data : formvals,
					success : reloadCart,
					error : reloadPage
				})
			} else {
				//all items removed - reset shopping cart
				clearItem('nogift');
			}
		});
	}
}

function reloadPage() {
	alert("page timed out");
	postNewItem();
}

function reloadCart(){
	$.get("/site/apps/ka/ec/basket.asp?c=luLRJaMQKpH&b=5152827",function(data){
		$('#temp')[0].innerHTML = data;
		var html = $('#temp #Table2').html();
		html = html.replace('<td class="CTtitle"><b><font class="CTtablein">Shopping Cart</font></b>&nbsp;',"<td><div class='section'><span class='stitle'>2</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>&nbsp;',"<td><div class='section'><span class='stitle'>2</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').each(function(){
			var id = $(this).find('td:eq(0) input[type=checkbox]').val();
			if ($(this).html().indexOf("I want my entire donation") > 0) {
				$(this).find('td:eq(6)').after($("<td><span class='cartremove' style='line-height:20px;padding:5px;'>&nbsp;</span></td>"));
				$(this).find('td:eq(6)').remove();
				$(this).find('td:eq(5)').remove();
				$(this).find('td:eq(4)').remove();
				$(this).find('td:eq(3)').remove();				
				$('#cart #TableCartInner tr.CTsubtitle:nth-child(1) td:eq(6)').remove();
				$('#cart #TableCartInner tr.CTsubtitle:nth-child(1) td:eq(5)').remove();
				$('#cart #TableCartInner tr.CTsubtitle:nth-child(1) td:eq(4)').remove();
				$('#cart #TableCartInner tr.CTsubtitle:nth-child(1) td:eq(3)').remove();				
			} else {
				$(this).find('td:eq(6)').after($("<td nowrap><a href='javascript:void(0);' onclick='updateTotal(\"\","+id+")'>Remove</a></span></td>"));
			}
		});
		$('#TableCartInner tr.CTodd, #TableCartInner tr.CTeven, #TableCartInner tr.CTsubtitle:eq(0)').each(function(){
			$(this).find('td:eq(6)').remove();
			$(this).find('td:eq(5)').remove();
			$(this).find('td:eq(4)').remove();
			//$(this).find('td:eq(3)').remove(); //leave quantity field
			$(this).find('td:eq(3) input').attr("onblur","");
			$(this).find('td:eq(0)').remove();			
			$(this).find('td:eq(0)').html("<font class='CT'>"+$(this).find('td:eq(0) a').text()+"</font>");
		});
		//hide total column
		$('#cart td.CTsubtitle:eq(0)').parent().remove();
		$('#cart #TableCartInner tr.CTsubtitle:nth-child(6)').remove();
		$('#cart #TableCartInner tr.CTsubtitle:nth-child(5)').remove();
		$('#cart #TableCartInner tr.CTsubtitle:nth-child(4)').remove();
		$('#cart #TableCartInner tr.CTsubtitle:nth-child(3)').remove();
		$('#cart #TableCartInner tr.CTsubtitle:nth-child(2)').remove();		
		$('#cart #TableCartInner tr.CTsubtitle td:eq(0)').html("<strong>Name</strong>");
		//$('#cart #TableCartInner tr.CTsubtitle td:eq(2)').after($("<td><strong>Function</strong></td>"));		
 		$('#loadingpopup').html('');
		totaldon = 0;
		$('#cart .tdg').each(function(){
			var multqty = $(this).parent().parent().parent().parent().find('input').val();
			totaldon = totaldon + (parseInt($(this).attr("alt")) * parseInt(multqty));
			
		});
		//change onblur event for product quantity field
		$('#cart input').each(function(){
			if (this.name.match("ProductQty")) {
				var val = $(this).val();
				$(this).blur(function(){
					if (checkQuantity(this,'',1,999999,val)) {
						var id = this.name.match(/\d+/);
						updateTotal("",id,"update");
					} else {
						return false;
					}
				});
			}
		});
		if (totaldon > $('#donation_amount').val()) {
			$('#donation_amount').val(totaldon);
			$("input[name=PledgeLevelID]:last").attr("checked","checked");
			$('#other_donation_amount').val(totaldon);
		}
		//if ($('#donation_amount').val() == 0) $('#donation_amount').val('');
	});
}

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=luLRJaMQKpH&b=5152827",
		data : "Recalculate=Update",
		success: function(data){
		   $.post("/site/apps/ka/ec/addtobasket.asp?c=luLRJaMQKpH&b=5152827",{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 = "";
	warning=checkRadioCheckbox($('input[name=Field4850682]'),"I would like my contribution to support",warning);	
	if (!$("input[name=PledgeLevelID]:first").attr("checked")) warning=checkField($('#donation_amount')[0],"Donation Amount",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.Field4864124,"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=checkSelect(thisform.ShiptoState,"Shipping State",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=luLRJaMQKpH&b=5152819&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("Field4884079",$("#cart #TableCartInner tr:eq(1) td:eq(0) font").text()); //thank you gift(s)		
	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("Field4850682",$("input[name=Field4850682]:checked").val()); //support tv, radio, both
	$.session("Field4850696",$("textarea[name=Field4868723]").val()); //comment carried over to addl fields page
	$.session("Field4864124",$("input[name=Field4864124]:checked").val()); //new member?
	//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=luLRJaMQKpH&b=5152827",
		data : "Recalculate=Update",
		success: function(data){
		   $.post("/site/apps/ka/ec/addtobasket.asp?c=luLRJaMQKpH&b=5152827",{ProductID:"688527",StoreID:""},function(){
			  location.href="/site/apps/ka/ec/supporter.asp?c=luLRJaMQKpH&b=5152819";
		   })
		},
		error :  function(err){
		   $.post("/site/apps/ka/ec/addtobasket.asp?c=luLRJaMQKpH&b=5152827",{ProductID:"688527",StoreID:""},function(){
			  location.href="/site/apps/ka/ec/supporter.asp?c=luLRJaMQKpH&b=5152819";
		   })
		}
	});
}

function formatdate(d) {
	try{
	return (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear();
	}catch(err){return false}
}

function checkQuantity(ptrQty,ptrAmt,iqty,maxqty,orgqty) {
	if(ptrQty.value != ""){
		if(!numericCheck(ptrQty.value,0,'nomsg')){
			alert("Please enter a valid quantity");
			ptrQty.value = orgqty;
			ptrQty.focus();
			return false;
		}
		else if(ptrQty.value*iqty > maxqty){
			alert("We're sorry, this number exceeds the maximum purchase amount for this product.\nPlease enter a number less than or equal to "+(maxqty/iqty));
			ptrQty.value = orgqty;
			ptrQty.focus();
			return false; 
		} else {
			return true; 
		}
	}
}
