$(document).ready(function(){
	function updateTotal(total) {
		var gift_total = 0.00;
		if (total != null) {
			gift_total = total;
		} else {
			$("input[name^='GIFT_AMOUNT']:checked").each(function(i) {
				gift_total = (parseFloat($(this).attr("value")) + parseFloat(gift_total)).toFixed(2);
			});
		}		
		
		$("#gift_total").text("$"+gift_total);
	}
	
	function changeAmt() {
		$("input[name^='GIFT_AMOUNT']")
			.change(function() {updateTotal();})
			.click(function() {updateTotal();})
			.select(function() {updateTotal();})
			.keypress(function() {updateTotal();});
	}
	
	function givingPageConfig(){	
		$("#gift-total").prepend("<h4>Gift Total: <span id='gift_total'>$0.00</span></h4>");
		
		$("label[class*='gift_other_text']").each(function(i,j){
			$(this).css("display","none");
		});
		
		$("input[id^='gift_other_']").each(function(i){
			$(this).attr({value:0.00});
		});
	}
	
	function customAmt() {
		$("input[id^='gift_value_']").each(function(i,j){
			$(j).blur(function(k) {
				if($(j).attr("value").match(new RegExp(/^([0-9]?){10}\.?([0-9]?){2}$/))) {
					$("#givingErrorNum" + i).empty();
					if($(j).attr("value")!=""){
						$($("input[id^='gift_other_']")[i]).attr({checked: 'checked',value:($(j).attr("value"))});
					}
					else {
						$($("input[id^='gift_other_']")[i]).attr({value:0.00});
					}
				}
				else {
					if(!$("#givingErrorNum" + i).hasClass("error")) {
						$($("input[id^='gift_other_']")[i]).attr({value:0.00});
						$(j).after(" <em class='error' id='givingErrorNum" + i +"'>Please enter a valid dollar amount</em>");
					}
				}
				updateTotal();
			})
		});
	}
	
	function customAmtRadio() {
		$("input[id^='gift_other_']").each(function(i,j) {
			$(j)
				.change(function(k) {
					$($("label[class*='gift_other_text']")[i]).show().focus();
				})
				.click(function(k) {
					$($("label[class*='gift_other_text']")[i]).show().focus();
				})
		});
	}
	
	function notCustomAmt() {
		$("input[name^='FUND']").each(function(a,b) {
			$("input[name='GIFT_AMOUNT"+(a+1)+"']:not([id^='gift_other'])").each(function(i,j) {
				$(j)
					.change(function(k) {
						$($("label[class*='gift_other_text']")[a]).hide();
					});
			});
		});
	}
	
	function submitCheck() {
		$("form[id='gift_form']").bind("submit", function(e) {
			var check = true;
			$("input[name^='GIFT_AMOUNT']:checked").each(function(i) {
					if($(this).attr("value").match(new RegExp(/^([0-9]?){10}\.?([0-9]?){2}$/))) {}
					else{check = false;}
			});
			 $("input[id^='gift_other_']:checked").each(function(i, j) {
				if($("em[class*='error']").length>0){check=false;}														
			});
			
			if (!check) {return false;}
		});	
	}
	
	givingPageConfig();
	customAmt();
	notCustomAmt();
	customAmtRadio();
	changeAmt();
	submitCheck();
	
	$("input[type='reset']").click(function() {
		updateTotal("0.00");						  
	});
});