﻿$(document).ready(function(){
	function updateTotal () {
		var gift_total = 0.00;
				$("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(){
		$("fieldset#gift_total_area input#giving_submit").before("<p>Total $<span id='gift_total'>0.00</span></p>");
		$("label[class^='gift_other_text']").each(function(i,j){
			$(j).css({display:"none"});
		});
	}
	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}$/))) {
							$(j).removeClass("error");
							$("#givingErrorNum" + i).remove();
							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("errorMsg")) {
								$($("input[id^='gift_other_']")[i]).attr({value:0.00});
							$(j).addClass("error").after("<span class='errorMsg' id='givingErrorNum" + i +"'>Please insert a valid dollar amount</span>");
							}
						}
						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($("span[id='givingErrorNum"+(i)+"']").length>0){check=false;}														
				});
				if (!check) {return false;}
			 });	
	}
	givingPageConfig();
	customAmt();
	notCustomAmt();
	customAmtRadio();
	changeAmt();
	submitCheck();
});