$(document).ready(function() {
    $('input[type=radio][name=date]').change(function() {
		$('input[type=radio][name=date]').each(function(){
			$(this).parent().removeClass('calendar-selected-label');
		});
		$(this).parent().addClass('calendar-selected-label');
    });
});

var oldhash='#';
window.onhashchange = locationHashChanged;


var uploadattempt=false;

function locationHashChanged(){
	var stepname=window.location.hash.substring(1);
	
	if(steporder.indexOf(stepname)>curstep){
		location.hash=steporder[curstep];
		return;
	}
	if($("#step-"+stepname)){
		if(!$("#step-"+stepname).is(":visible")){		
			$(".stepblock:not(#step-"+stepname+")").each(function(){
				$(this).hide();
			});
			$("#step-"+stepname).show();
			hideerror();
			removeformhighlights();
		}
	}
	if(steporder.indexOf(stepname)!=-1){
		curstep=steporder.indexOf(stepname);
		updateprogressbar();
	}
	oldhash=window.location.hash;
}

var customHistory = [];
$(window).on('popstate', function(e) {
  var lastEntry = customHistory.pop();
  if(lastEntry){
	history.pushState(lastEntry.data, lastEntry.title, lastEntry.location);
  }
});

var nodonation=false;

function schedulenownodonation(){
	nodonation=true;
	schedulenow();
}

function schedulenow(){
	
	if($("#confirmationagree").length){
		if(!$("#confirmationagree").is(":checked")){	
			showerror("Please check the box to agree");
			return;
		}
	}
	
	showloader();
	if (window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}
	else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function(){
	  if (xmlhttp.readyState==4 && xmlhttp.status==200){
		  hideloader();
			if(gebid('psbtn')){
				gebid('psbtn').disabled=false;
			}
		  var ans=xmlhttp.responseText;
		  if(ans=="done"){
			  steporder.push('done');
			  hideprogressbar();
			  nextstep();
		  }
		  else{
			if(ans=="carderror"){
				showerror('Error! Your donation could not be processed.<br /><br /><button onclick="showdonationstep();" class="btn btn-success">Click here to reenter card details</button><br /><br /><button onclick="schedulenownodonation();" class="btn btn-success">Click here to schedule without donation</button>');
				return;
			}
			showerror('Error! Pickup could not be scheduled! This is usually caused when you leave this form idle for too long because the time slots may have already filled up. You will need to go back to check time slots. Your information is still in the form, but will need to be verified. <a href="#" onclick="curstep=-1;nextstep();showimages();return(false);">Click here to verify information</a><br />');
		  }
		}
	}
	var params = "action=schedule";
	params+="&date="+encodeURIComponent(getRadioValue('date'));
	params+="&datecheck="+encodeURIComponent(getRadioCheckedId('date'));
	if($("#contactsameaddress").is(":checked")){
		params+="&sameaddress=true";
	}
	if($("#marketingagree").is(":checked")){
		params+="&marketingagree=true";
	}
	if(customdonationinuse()){
		gebid('donationnotes').value="$"+gebid('donationnotes').value+", "+$('input[name=donationamount]:checked').val();
	}
	var formelem=["pickupaddressline1","pickupaddressline2","pickupcity","pickupstate","pickupzipcode","name","contactname","phone","phonealt","email","donoraddressline1","donoraddressline2","donorcity","donorstate","donorzipcode","itemlist","notes","donationnotes","zonecode"];
	if(typeof extratransmitfields=='object'){
		formelem=formelem.concat(extratransmitfields);
	}
	for(var fei=0;fei<formelem.length;fei++){
		if(gebid(formelem[fei])){
			params+="&"+formelem[fei]+"="+encodeURIComponent(gebid(formelem[fei]).value);
		}
	}
	if(nodonation==false){
		var amounttocollect=parseFloat(getRadioValue('donationamount'));
		if($('#includesurcharge').prop('checked')){
			var thisdonationamount=amounttocollect;
			var thissurchargeamount=thisdonationamount*surchargepercent/100+surchargeflatfee;
			thissurchargeamount=Math.round(thissurchargeamount*100)/100;
			amounttocollect+=thissurchargeamount;
		}
		confirmeddonationamount=amounttocollect;
		params+="&donation="+encodeURIComponent(amounttocollect);
	}
	var address='checks.php'
	xmlhttp.open("POST",address, true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	if(gebid('psbtn')){
		gebid('psbtn').disabled=true;
	}
	xmlhttp.send(params);
}

function customdonationinuse(){
	if($('input[name=donationamount]:checked').val()=='cash' || $('input[name=donationamount]:checked').val()=='check' || $('input[name=donationamount]:checked').val()=='on-site-credit-card'){
		return(true);
	}
	return(false);
}

function verifyaffirmations(){
	var go=true;
	$('[id^=affirmation_]').each(function(){
		if(!$(this).is(":checked")){
			go=false;
		}
	});
	if(!go){
		showerror("Please check each box");
		return;
	}
	nextstep();
}

function showstep(stepname){
	if(curstep==0){
		$(".btn-backonestep").each(function(){
			$(this).hide();
		});
	}
	else{
		$(".btn-backonestep").each(function(){
			$(this).show();
		});
	}
	if(stepname=='donate' && typeof showadyen == 'function'){
		showadyen();
	}
	if (stepname=="donate" && typeof specialdays !== 'undefined'){
	    checkspecialdonations();
	}
	if(stepname=="photoupload"){
		showimagerequirementprompt();
	}
	if(stepname=="done"){
		if(typeof codewhenscheduled=='function'){
			codewhenscheduled();
		}
	}
	hideloader();
	location.hash=stepname;
	$(".stepblock:not(#step-"+stepname+")").each(function(){
		$(this).hide();
	});
	$("#step-"+stepname).show();
	hideerror();
	removeformhighlights();
	if(stepname=="confirmation"){
		prepareconfirmation();
	}
	window.scrollTo(0,0);
	if(typeof showstepcallback=='function'){
		showstepcallback(stepname);
	}
}

function prepareconfirmation(){
	var ans='';
	ans+="<table class='confirmationtable'>";
	ans+='<tr><td>Name:&nbsp&nbsp</td><td>'+$("#name").val()+"</td></tr>";
	ans+='<tr><td>E-mail:&nbsp&nbsp</td><td>'+$("#email").val()+"</td></tr>";
	ans+='<tr><td>Phone:&nbsp&nbsp</td><td>'+$("#phone").val()+"</td></tr>";
	var prefix='';
	if(!$("#contactsameaddress").is(":checked")){
		prefix='Contact ';
	}
	ans+='<tr><td>'+prefix+'Address Line 1:&nbsp&nbsp</td><td>'+$("#donoraddressline1").val()+"</td></tr>";
	ans+='<tr><td>'+prefix+'Address Line 2:&nbsp&nbsp</td><td>'+$("#donoraddressline2").val()+"</td></tr>";
	ans+='<tr><td>'+prefix+'City :&nbsp&nbsp</td><td>'+$("#donorcity").val()+"</td></tr>";
	ans+='<tr><td>'+prefix+'State:&nbsp&nbsp</td><td>'+$("#donorstate").val()+"</td></tr>";
	ans+='<tr><td>'+prefix+'Zip:&nbsp&nbsp</td><td>'+$("#donorzipcode").val()+"</td></tr>";
	if(!$("#contactsameaddress").is(":checked")){
		prefix='Pickup ';
		ans+='<tr><td>'+prefix+'Address Line 1:&nbsp&nbsp</td><td>'+$("#pickupaddressline1").val()+"</td></tr>";
		ans+='<tr><td>'+prefix+'Address Line 2:&nbsp&nbsp</td><td>'+$("#pickupaddressline2").val()+"</td></tr>";
		ans+='<tr><td>'+prefix+'City :&nbsp&nbsp</td><td>'+$("#pickupcity").val()+"</td></tr>";
		ans+='<tr><td>'+prefix+'State:&nbsp&nbsp</td><td>'+$("#pickupstate").val()+"</td></tr>";
		ans+='<tr><td>'+prefix+'Zip:&nbsp&nbsp</td><td>'+$("#pickupzipcode").val()+"</td></tr>";
	}
	if(parseFloat(getRadioValue('donationamount'))>0){
		ans+='<tr><td>Donation:&nbsp&nbsp</td><td>$'+parseFloat(getRadioValue('donationamount')).toFixed(2)+"</td></tr>";
	}
	
	var datevalue='';
	var datavalue2='';
	var radio = document.getElementsByName('date');
    for(x=0;x<radio.length;x++) {
        if(radio[x].checked){
			datevalue=gebid('label_'+radio[x].id).innerHTML;
			if(gebid('hiddenlabel_'+radio[x].id)!=null){
				datevalue=gebid('hiddenlabel_'+radio[x].id).innerHTML;
			}
			datavalue2=gebid('actualdatehiddenlabel_'+radio[x].id).innerHTML;
		}
    }
	
	ans+='<tr><td>Date:&nbsp&nbsp</td><td>'+datevalue+"</td></tr>";
	var dispitems='';
	for(var i=0;i<myitems.length;i++){
		var et='';
		if(myitems[i].quantity!=1){
			et=' (quantity: '+myitems[i].quantity+')';
		}
		dispitems+=myitems[i].name+et+"<br />";
	}
	ans+='<tr><td>Items:&nbsp&nbsp</td><td>'+dispitems+"</td></tr>";
	
	ans+="</table>";
	$('#confirmationinner').html(ans);
}

function showdonationstep(){
	curstep--;
	showstep('donate');
}

function nextstep(){
	if(steporder.length>=curstep+1){
		curstep++;
		curstepp1=curstep+1;
		totalcount=steporder.length;
		$(".top-progress").each(function(){
			var progresspercent=parseInt(curstepp1*100/totalcount);
			$(this).html('Step '+curstepp1+' of '+totalcount);
			$(this).attr('aria-valuenow', progresspercent).css('width',progresspercent+'%');
		});
		showstep(steporder[curstep]);
		if(cookieerror){
			showerror("It seems that your browser is blocking cookies for this website. Pickup scheduling cannot function if cookies are disabled.");
		}
	}
}

function previousstep(){
	if(curstep>=1){
		curstep--;
		curstepp1=curstep+1;
		totalcount=steporder.length;
		$(".top-progress").each(function(){
			var progresspercent=parseInt(curstepp1*100/totalcount);
			$(this).html('Step '+curstepp1+' of '+totalcount);
			$(this).attr('aria-valuenow', progresspercent).css('width',progresspercent+'%');
		});
		showstep(steporder[curstep]);
	}
}

function updateprogressbar(){	
	curstepp1=curstep+1;
	totalcount=steporder.length;
	$(".top-progress").each(function(){
		var progresspercent=parseInt(curstepp1*100/totalcount);
		$(this).html('Step '+curstepp1+' of '+totalcount);
		$(this).attr('aria-valuenow', progresspercent).css('width',progresspercent+'%');
	});
}

function hideprogressbar(){
	$(".progress").each(function(){
		$(this).hide();
	});
}

function removeformhighlights(){
	$(".standard-input").each(function(){
		$(this).removeClass('input-error');
	});
}

function highlightforminput(id){
	$("#"+id).addClass('input-error');
}

function hideerror(){
	$(".top-error").each(function(){
		$(this).html('');
		$(this).hide();
	});
}

function showerror(errortext){
	$(".top-error").each(function(){
		$(this).html(errortext);
		$(this).show();
		if($(this).is(":visible")){
			$('html, body').animate({
				scrollTop: $(this).offset().top
			}, 5);
			$(this).effect( "shake",{times:2,distance:5});
		}
	});
}

function checkspecialdonations() {
	if(specialdays==null){
		return;
	}
    var days=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
    var date=new Date($("input[name=date]:checked").val().split("|||")[0]);
    var dayindex=date.getDay();
    var day=days[dayindex];
    dayindex++;
    var hide=false;
    if(typeof specialdays !== 'undefined' &&specialdays!=null && specialdays.length!=0){
        if(specialdays.includes(dayindex)){
            hide=true;
        }
    }
    if(hide){
        $(".donation-amount").css('display','none');
        $(".donation-amount-special").css('display','');
        if($(".donation-amount-special input:checked").length == 0){
            $(".donation-amount-special input")[0].click();
        }
        $('#specialdaysnotice').css('display','');
        $("#specialdaysnotice").html(day+" requires a donation");
    }else{
        $(".donation-amount").css('display','');
        $('#specialdaysnotice').css('display','none');
    }
}

function deleteimage(i){
	showloader();
	$.ajax({
		data: {	action:"deleteimage",id:i},
		type: 'POST',
		url: 'uploader.php',
		success: function(results) { 
			hideloader();
			$('#innerimages').html(results);
		}
	});
}

function showimages(){
	showloader();
	$.ajax({
		data: {	action:"showimages"},
		type: 'GET',
		url: 'uploader.php',
		success: function(results) { 
			hideloader();
			$('#innerimages').html(results);
		}
	});
}

var itemsthatneedimages=[];

function showimagerequirementprompt(){
	var countextrap='';
	if(itemsthatneedimages.length>0){
		for(var i=0;i<myitems.length;i++){
			var needsimage=false;
			if(itemsthatneedimages.indexOf(myitems[i].name)>-1){
				needsimage=true;
			}
			for(var j=0;j<itemsthatneedimages.length;j++){
				if(myitems[i].name.indexOf(itemsthatneedimages[j])>-1){
					needsimage=true;
				}
			}
			if(needsimage){
				if(countextrap==''){
					countextrap=' The following item(s) require a photo: '+myitems[i].name;
				}
				else{
					countextrap+=', '+myitems[i].name;
				}
			}
		}
	}
	$("#imagepromptsubzone").html(countextrap);
}
function verifyimages(count){
	var countextraerror='';
	if(count==0){
		if(itemsthatneedimages.length>0){
			for(var i=0;i<myitems.length;i++){
				var needsimage=false;
				if(itemsthatneedimages.indexOf(myitems[i].name)>-1){
					needsimage=true;
				}
				for(var j=0;j<itemsthatneedimages.length;j++){
					if(myitems[i].name.indexOf(itemsthatneedimages[j])>-1){
						needsimage=true;
					}
				}
				if(needsimage){
					count=1;
					if(countextraerror==''){
						countextraerror=' The following item(s) require a photo: '+myitems[i].name;
					}
					else{
						countextraerror+=', '+myitems[i].name;
					}
				}
			}
		}
	}
	if(count==0){
		nextstep();
		return;
	}
	var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
	if(uploadattempt){
		console.log("Upload attempted");
		if(iOS){
			nextstep();
			return;
		}
	}
	showloader();
	$.ajax({
		data: {	action:"getimagecount"},
		type: 'GET',
		url: 'uploader.php',
		success: function(results) {
			hideloader();
			var realcount=parseInt(results);
			if(realcount>=count){
				nextstep();
				return;
			}
			
			if(count==1){
				showerror('Please upload at least one image.'+countextraerror);
			}
			else{
				showerror('Please upload at least '+count+' images.'+countextraerror);
			}
		}
	});
}

function verifycontactinformation(){
	hideerror();
	removeformhighlights();
	var go=true;
	formchecklist=['name','email','phone','donoraddressline1','donorcity','donorstate','donorzipcode'];
	if(typeof extrarequiredcontactfields == 'object'){
		formchecklist=formchecklist.concat(extrarequiredcontactfields);
	}
	for(var i=0;i<formchecklist.length;i++){
		if($("#"+formchecklist[i]).val()==''){
			highlightforminput(formchecklist[i]);
			go=false;
		}
	}
	if(!go){
		showerror('Some required fields were not completed. Please fill in those fields and try again.');
		return;
	}
	$("#email").val($("#email").val().trim());
	if(!validateEmail($("#email").val())){
		highlightforminput('email');
		showerror('The e-mail address entered is not valid.');
		return;
	}
	
	if($("#contactsameaddress").is(":checked")){
		showloader();
		$.ajax({
			data: {	action:"verifyaddress",
					pickupaddressline1:$("#donoraddressline1").val(),
					pickupaddressline2:$("#donoraddressline2").val(),
					pickupcity:$("#donorcity").val(),
					pickupstate:$("#donorstate").val(),
					pickupzipcode:$("#donorzipcode").val(),
					zonecode:$("#zonecode").val()
				},
			type: 'POST',
			url: 'communication.php',
			success: function(results) { 
				hideloader();
				var data=JSON.parse(results);
				if(data.status=='error'){
					showerror(data.message);
					return;
				}
				updateavilabledates(data);
				nextstep();
			}
		});
	}
	else{
		if(steporder.indexOf('address')==-1){
			steporder.splice(steporder.indexOf('contactinformation')+1, 0, 'address'); 
		}
		nextstep();
	}
}
function validateEmail(email) {
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}

function verifyzonecode(){
	$('#zonecodebutton').hide();
	hideerror();
	removeformhighlights();
	var go=true;
	showloader();
	$.ajax({
		data: {	action:"verifyzonecode",
				zonecode:$("#zonecode").val()
			},
		type: 'POST',
		url: 'communication.php',
		success: function(results) { 
			$('#zonecodebutton').show();
			hideloader();
			var data=JSON.parse(results);
			if(data.status=='error'){
				showerror(data.message);
				return;
			}
			nextstep();
		}
	});
}

function verifyaddress(){
	hideerror();
	removeformhighlights();
	var go=true;
	if($("#pickupaddressline1").val()==''){
		highlightforminput("pickupaddressline1");
		go=false;
	}
	if($("#pickupcity").val()==''){
		highlightforminput("pickupcity");
		go=false;
	}
	if($("#pickupstate").val()==''){
		highlightforminput("pickupstate");
		go=false;
	}
	if($("#pickupzipcode").val()==''){
		highlightforminput("pickupzipcode");
		go=false;
	}
	if(!go){
		showerror('Some required fields were not completed. Please fill in those fields and try again.');
		return;
	}
	showloader();
	$.ajax({
		data: {	action:"verifyaddress",
				pickupaddressline1:$("#pickupaddressline1").val(),
				pickupaddressline2:$("#pickupaddressline2").val(),
				pickupcity:$("#pickupcity").val(),
				pickupstate:$("#pickupstate").val(),
				pickupzipcode:$("#pickupzipcode").val(),
				zonecode:$("#zonecode").val()
			},
		type: 'POST',
		url: 'communication.php',
		success: function(results) { 
			hideloader();
			var data=JSON.parse(results);
			if(data.status=='error'){
				showerror(data.message);
				return;
			}
			updateavilabledates(data);
			nextstep();
		}
	});
}

function verifydate(){
	if(!$('input[name=date]:checked').val()){
		showerror("Please select a date");
		return;
	}
	nextstep();
}

function updateavilabledates(data){
	$('.calendar-pick').each(function(){
		$(this).find('label').each(function(){
			$(this).removeClass('calendar-available-label');
			$(this).removeClass('calendar-selected-label');
			$(this).addClass('calendar-unavailable-label');
		});
		$(this).find('input[type=radio]').each(function(){
			$(this).attr('disabled', true);
			$(this).attr('checked', false);
		});
	});
	for(i=0;i<data.dates.length;i++){
		$('#pickdiv-'+data.dates[i]).find('input[type=radio]').each(function(){
			$(this).attr('disabled', false);
		});
		$('#pickdiv-'+data.dates[i]).find('label').each(function(){
			$(this).removeClass('calendar-unavailable-label');
			$(this).addClass('calendar-available-label');
		});
	}
}

function showitemadderchild(id){
	hideitemadders();
	$("#itemadder-"+id).removeClass('itemadder-hidden');
	$("#itemadder-"+id).addClass('itemadder-visible');
	$("#itemwarningzone").slideUp();
}

function hideitemadders(){
	$(".itemadder-all").each(function(){
		if($(this).attr('id')!='itemadder-main'){
			$(this).removeClass('itemadder-visible');
			$(this).addClass('itemadder-hidden');
		}
	});
}

var myitems;
var minweight=1;
var itemcounterror="Please add enough items";

function verifyitems(){
	var totalweight=0;
	for(var i=0;i<myitems.length;i++){
		totalweight+=parseFloat(myitems[i].weight);
	}
	if(totalweight<minweight){
		showerror(itemcounterror);
		return;
	}
	if($("#additemsagree").length){
		if(!$("#additemsagree").is(":checked")){	
			showerror("Please check the box to agree");
			return;
		}
	}
	nextstep();
}

function itemtextareatojson(){
	if($("#itemjson").val()){
		myitems=JSON.parse($("#itemjson").val());
	}
	else{
		myitems=JSON.parse("[]");
	}
}
function itemjsontotextarea(){
	$("#itemjson").val(JSON.stringify(myitems));
}
function itemlisttotext(){
	var itemlistonly=[];
	for(var i=0;i<myitems.length;i++){
		var thisname=myitems[i].name;
		if(myitems[i].quantity>1){
			thisname+=' (quantity: '+myitems[i].quantity+')';
		}
		itemlistonly.push(thisname);
	}
	$("#itemlist").val(itemlistonly.join("\r\n"));
}

function additemwithprompt(name,quantity,weight,p){
	$("#itemwarningzone").html(p+"<br /><button class='btn btn-success' onclick='additem(\"" +name+ "\",\""+quantity+ "\",\""+weight+"\");$(\"#itemwarningzone\").hide();'>Add this</button><br /><br /><button class='btn btn-danger' onclick='$(\"#itemwarningzone\").slideUp();'>Do not add</button>");
	$("#itemwarningzone").show();
	$("#verifyitembutton")[0].scrollIntoView({ behavior: "smooth", block: "end"});
}

function additemwithdescriptionprompt(name,quantity,weight,p){
	$("#itemwarningzone").html(p+"<br /><input placeholder='Item description' id='itemdescriptionbox' class='form-control' /><br /><button class='btn btn-success' onclick='additem(\"" +name+ " (\"+$(\"#itemdescriptionbox\").val()+\")\",\""+quantity+ "\",\""+weight+"\");$(\"#itemwarningzone\").hide();'>Add this</button><br /><br /><button class='btn btn-danger' onclick='$(\"#itemwarningzone\").slideUp();'>Do not add</button>");
	$("#itemwarningzone").show();
	$("#verifyitembutton")[0].scrollIntoView({ behavior: "smooth", block: "end"});
	$("#itemdescriptionbox").focus();
}

function additemwithdescriptionpromptraw(name,quantity,weight,p){
	$("#itemwarningzone").html(p+"<br /><input placeholder='Item description' id='itemdescriptionbox' class='form-control' /><br /><button class='btn btn-success' onclick='additem(\"\"+$(\"#itemdescriptionbox\").val()+\"\",\""+quantity+ "\",\""+weight+"\");$(\"#itemwarningzone\").hide();'>Add this</button><br /><br /><button class='btn btn-danger' onclick='$(\"#itemwarningzone\").slideUp();'>Do not add</button>");
	$("#itemwarningzone").show();
	$("#verifyitembutton")[0].scrollIntoView({ behavior: "smooth", block: "end"});
	$("#itemdescriptionbox").focus();
}

function additemwithdescriptionandquantityprompt(name,quantityprompt,weight,p){
	var quantityprompt2=quantityprompt+" <input type=\"number\" id=\"itemcount\" value=\"1\" min=\"1\" />";
	$("#itemwarningzone").html(p+"<br /><input placeholder='Item description' id='itemdescriptionbox' class='form-control' /><br />"+quantityprompt2+"<br /><button class='btn btn-success' onclick='additem(\"" +name+ " (\"+$(\"#itemdescriptionbox\").val()+\")\",parseInt($(\"#itemcount\").val()),parseInt($(\"#itemcount\").val())*parseInt("+weight+"));$(\"#itemwarningzone\").hide();'>Add this</button><br /><br /><button class='btn btn-danger' onclick='$(\"#itemwarningzone\").slideUp();'>Do not add</button>");
	$("#itemwarningzone").show();
	$("#verifyitembutton")[0].scrollIntoView({ behavior: "smooth", block: "end"});
	$("#itemdescriptionbox").focus();
}

function additemwithdescriptionandquantitypromptraw(name,quantityprompt,weight,p){
	var quantityprompt2=quantityprompt+" <input type=\"number\" id=\"itemcount\" value=\"1\" min=\"1\" />";
	$("#itemwarningzone").html(p+"<br /><input placeholder='Item description' id='itemdescriptionbox' class='form-control' /><br />"+quantityprompt2+"<br /><button class='btn btn-success' onclick='additem(\"\"+$(\"#itemdescriptionbox\").val()+\"\",parseInt($(\"#itemcount\").val()),parseInt($(\"#itemcount\").val())*parseInt("+weight+"));$(\"#itemwarningzone\").hide();'>Add this</button><br /><br /><button class='btn btn-danger' onclick='$(\"#itemwarningzone\").slideUp();'>Do not add</button>");
	$("#itemwarningzone").show();
	$("#verifyitembutton")[0].scrollIntoView({ behavior: "smooth", block: "end"});
	$("#itemdescriptionbox").focus();
}

function additemwithpromptandquantity(name,quantityprompt,weight,p){
	var quantityprompt2=quantityprompt+" <input type=\"number\" id=\"itemcount\" value=\"1\" min=\"1\" />";
	$("#itemwarningzone").html(p+"<br />"+quantityprompt2+"<br /><br /><button class='btn btn-success' onclick='additem(\"" +name+ "\",parseInt($(\"#itemcount\").val()),parseInt($(\"#itemcount\").val())*parseInt("+weight+"));$(\"#itemwarningzone\").hide();'>Add this</button><br /><br /><button class='btn btn-danger' onclick='$(\"#itemwarningzone\").slideUp();'>Do not add</button>");
	$("#itemwarningzone").show();
	$("#verifyitembutton")[0].scrollIntoView({ behavior: "smooth", block: "end"});
}

function donotadditemwithprompt(p){
	$("#itemwarningzone").html(p+"<br /><br /><button class='btn btn-danger' onclick='$(\"#itemwarningzone\").slideUp();'>Go back to adding items</button>");
	$("#itemwarningzone").show();
	$("#verifyitembutton")[0].scrollIntoView({ behavior: "smooth", block: "end"});
}

function additem(name,quantity,weight){
	var added=false;
	for(var i=0;i<myitems.length;i++){
		if(myitems[i].name==name){
			added=true;
			myitems[i].quantity+=parseFloat(quantity);
			myitems[i].weight+=parseFloat(weight);
			i=myitems.length;
		}
	}
	if(!added){
		myitems[myitems.length]={name:name,quantity:parseFloat(quantity),weight:parseFloat(weight)};
	}
	$("#itemwarningzone").slideUp();
	hideitemadders();
	itemjsontotextarea();
	renderitems();
}

function deleteitem(idx){
	myitems.splice(idx, 1);
	itemjsontotextarea();
	renderitems();
	$("#itemwarningzone").slideUp();
}

function increaseitem(idx){
	var averageweight=(myitems[idx].weight)/(myitems[idx].quantity);
	myitems[idx].quantity+=1;
	myitems[idx].weight=averageweight*myitems[idx].quantity;
	itemjsontotextarea();
	renderitems();
	$("#itemwarningzone").slideUp();
}

function decreaseitem(idx){
	if(myitems[idx].quantity<=1){
		deleteitem(idx);
		return;
	}
	var averageweight=(myitems[idx].weight)/(myitems[idx].quantity);
	myitems[idx].quantity-=1;
	myitems[idx].weight=averageweight*myitems[idx].quantity;
	itemjsontotextarea();
	renderitems();
	$("#itemwarningzone").slideUp();
}

var hideaddsubtract=false;
function renderitems(){
	var ans='';
	for(var i=0;i<myitems.length;i++){
		var et='';
		if(myitems[i].quantity!=1){
			et=' (quantity: '+myitems[i].quantity+')';
		}
		var addsubtract="<button class='btn btn-xs btn-warning' style='float:right;height:25px;width:25px;margin:3px;' onclick='decreaseitem("+i+");'>-</button><button class='btn btn-xs btn-info' style='float:right;height:25px;width:25px;margin:3px;' onclick='increaseitem("+i+");'>+</button>";
		if(hideaddsubtract){
			addsubtract="";
		}
		ans+="<div class='iteminlist'><button class='btn btn-xs btn-danger' style='margin:3px;' onclick='deleteitem("+i+");'>Delete</button>"+myitems[i].name+et+addsubtract+"</div>";
	}
	$("#itemzone").html(ans);
	itemlisttotext();
}

var cookieerror=false;

function checkcookies(){
	$.ajax({
		data: {	action:"checkcookies"},
		type: 'POST',
		url: 'communication.php',
		success: function(results) { 
			var data=JSON.parse(results);
			if(data.status=='error'){
				cookieerror=true;
				showerror(data.message+'<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />');
				return;
			}
		}
	});
}

function verifypayment(){
	if(parseFloat($('input[name=donationamount]:checked').val())>0){
		$('#payment-form').trigger('submit');
	}
	else{
		nextstep();
	}
}


function preparestripe(id){
	var stripe = Stripe(id);
	var elements = stripe.elements();
	var style = {
	  base: {
		color: '#32325d',
		lineHeight: '24px',
		fontFamily: '\"Helvetica Neue\", Helvetica, sans-serif',
		fontSmoothing: 'antialiased',
		fontSize: '16px',
		'::placeholder': {
		  color: '#aab7c4'
		}
	  },
	  invalid: {
		color: '#fa755a',
		iconColor: '#fa755a'
	  }
	};
	var card = elements.create('card', {style: style});
	card.mount('#card-element');
	
card.addEventListener('change', function(event) {
  var displayError = document.getElementById('card-errors');
  if (event.error) {
    displayError.textContent = event.error.message;
  } else {
    displayError.textContent = '';
  }
});

$(document).on('submit','#payment-form',function(event){
  event.preventDefault();
	showloader();
  stripe.createToken(card).then(function(result) {
    if (result.error) {
      // Inform the user if there was an error
      var errorElement = document.getElementById('card-errors');
      errorElement.textContent = result.error.message;
	  hideloader();
    } else {
      // Send the token to your server
		$.ajax({
			data: {	action:"cardtoken",token:JSON.stringify(result.token)},
			type: 'POST',
			url: 'communication.php',
			success: function(results) { 
				nextstep();
				hideloader();
			}
		});
    }
  });
});
}
function showloader(){
	$(".spinner").each(function(){
		$(this).show();
	});
}
function hideloader(){
	$(".spinner").each(function(){
		$(this).hide();
	});
}

function gebid(id){
	return(document.getElementById(id));
}


function getRadioValue(radioName) {
    var radio = document.getElementsByName(radioName);
    for(x=0;x<radio.length;x++) {
        if(radio[x].checked){
			return(radio[x].value);
		}
    }
	return("");
}



function getRadioCheckedId(radioName) {
    var radio = document.getElementsByName(radioName);
    for(x=0;x<radio.length;x++) {
        if(radio[x].checked){
			return(radio[x].id);
		}
    }
}