/* 
 * /JS/FORMS.JS
 * Alexander Bradley, Landon Durnan, Jason Chen, Jennifer Leong, Jason Sofonia
 * Written from August - December 08
 * Please email abradley@silverpoint.net with questions
 */


/**************************************************************************************
 **************************************************************************************
 *************************************jQuery*******************************************
 **************************************************************************************
 **************************************************************************************/
$(document).ready(function(){
	
	/* Basic Form Validation */
	$("#basicForm").validate({	
		messages: {
			zip: {
				minlength: "Invalid zip code"
			}
		}
	});
	// nothing to see here, folks
	
	/* Inquiry Form Validation */
	$("#inquiryForm").validate({	
		messages: {
			classyear: {
				min: "Invalid Class Year",
				max: "Invalid Class Year"
			},
			zip: {
				minlength: "Invalid zip code"
			}
		}
	});
	// nothing to see here, folks

	// Giving Validation
	$("#givingForm").validate({	
		messages: {
			classyear: {
				min: "Invalid Class Year",
				max: "Invalid Class Year"
			},
			total: {
				min: "Invalid Value",
				max: "Invalid Value"
			},
			zip: {
				minlength: "Invalid zip code"
			}
		}
	});
	
	// Credit Card Validation
	$("#creditcardForm").validate({	
		messages: {
			classyear: {
				min: "Invalid Class Year",
				max: "Invalid Class Year"
			},
			total: {
				min: "Invalid Value",
				max: "Invalid Value"
			},
			zip: {
				minlength: "Invalid zip code"
			}
		}
	});
	
	/* Change some HTML for validation styling */
	$("form div").each(function (i) {
		if($(this).children().hasClass("required")){ $(this).addClass("required");  } 
	});
	$("form div ul.checkwrap li").each(function (i) {
		if($(this).children().hasClass("required")){ $(this).parent().parent().addClass("required");  } 
	});
	
	
	/* Forms with .form will, on a successful submit, have
	 * the submit button changed to a "Processing" Span */
	$("form").submit(function() {
		if($("input[type=submit]").hasClass("processing")) {
			if($(this).valid()) {
				$("form > fieldset > input[type=submit]").replaceWith("<span class=\"processing\">Processing...</span>");
				return true;
			} else return false;
		}
	});
	
	$(window).load(function() {
		if($("fieldset span.processing").length>=1)
			$("fieldset span.processing").replaceWith("<input type=\"submit\" value=\"Submit\" class=\"submit button\" />")
	});
	
	/* Modify forms with a credit card fieldset */
	if($("#ccnum").length == 1) {
		$(window).load(function() {
			$("#divccnumprelim").show();
			$("#divccnum").hide();
			applyMasks();
		});
		
		$("form.cc").submit(function() {
			if($(this).valid())
				$("input#ccnumprelim").replaceWith("<span id=\"ccnumprelim\">"+$("input#ccnumprelim").val()+"</span><span id=\"modify\" style=\"cursor: pointer; margin: 0 .3em;\">[modify]</span>");
		});
		
		$("span#modify").click(function() {
			var cc= $("span#ccnumprelim").text();
			$("#ccnumprelim").replaceWith("<input type=\"text\" name=\"ccnumprelim\" id=\"ccnumprelim\" class=\"required creditcard\" onblur=\"javascript:popCCNum(this.value);\" />");								
			$("span#modify").remove();
			$("input[id=ccnumprelim]").val(cc);
			applyMasks();
		});
	}
	
	// Hide AHCTPAC Field If Applicable
	// Don't submit the emailAddress field onsubmit
	if($("#emailAddressDiv").length != 0) {
		$("#emailAddressDiv").hide();
		
		if($("form.form").valid())
			$("#emailAddressDiv").remove();
	}
	
	// Setup Masked Input, Watermark Plugins
	
		$("#donor, .donor").Watermark("Anonymous");
		// Should be fairly obvious...
		
		$(".dob, .datemask, #dob, .fulldate").unmask().mask("99/99/9999",{placeholder:"_"}).Watermark("mm/dd/yyyy");
		// Date of Birth field accepts dates in this format
	
		$(".year, #classyear, #classYear, #ClassYear").unmask().mask("9999",{placeholder:"y"});
		// Requires classyear to be four digits
	
	function applyMasks() {	
		// Define Credit Card Placeholders...
		// http://en.wikipedia.org/wiki/Credit_card_number#Prefixes
		$.mask.addPlaceholder('v',"[4]");		// All Visas begin with '4' [v]
		$.mask.addPlaceholder('m',"[5]");		// All Mastercards begin with a
		$.mask.addPlaceholder('c',"[12345]");	// number from 51-55 [m, c]
		$.mask.addPlaceholder('a',"[3]");		// All AmEx begin with either a 
		$.mask.addPlaceholder('x',"[47]");		// 34 or a 37 [a, x]
		$.mask.addPlaceholder('d',"[6]");		// All Discover Cards begin with 6
		$.mask.addPlaceholder('s',"[0245]");	// and second digit is 0,2,4,5 [d, s]
		
		// First, set CC Length to 16 (generic)...
		$("#ccnumprelim").unmask().mask("9999-9999-9999-9999",{placeholder:"_"});
		// Then, be sure if it changes to 15 for AmEx if you select an AmEx card
		$("#cctype").change(function() {
			if($("form.cc #cctype").val()==1) { // Mastercard
				$("#ccnumprelim").unmask().mask("mc99-9999-9999-9999",{placeholder:"_"});
			} else if($("form.cc #cctype").val()==2) { // Visa
				$("#ccnumprelim").unmask().mask("v999-9999-9999-9999",{placeholder:"_"});
			} else if($("form.cc #cctype").val()==3) { // AmEx
				$("#ccnumprelim").unmask().mask("ax99-999999-99999",{placeholder:"_"});
			} else if($("form.cc #cctype").val()==4) { // Discover Card
				$("#ccnumprelim").unmask().mask("ds99-9999-9999-9999",{placeholder:"_"});
			} else if($("form.cc #cctype").val()==5) { // Diner's Club
				$("#ccnumprelim").unmask().mask("m999-9999-9999-9999",{placeholder:"_"});
			}
		});
	}			// End Masked Input

/**************************************************************************************
 **************************************************************************************
 ***********************************Zip Codes******************************************
 **************************************************************************************
 **************************************************************************************/
 
/* These functions should really never require modification -- ab */
	$(".zip").keyup(function() {
		var fsParent= $(this).parent().parent(); // returns fieldset which contains current element.		
		var zip= $(this).val();
	
		// Modifies the label for the zip field
		if(isValidUS(zip)) {
			$(this).prev().text("Zip Code");							// Label of $(this) = text()
			zip= zip.substring(0,3);									// Extract first 3 characters of $(".zip").val()
			
			if(zip >= 350 && zip <= 369) state= "Alabama";
			else if(zip >= 995 && zip <= 999) state= "Alaska";
			else if(zip >= 850 && zip <= 865) state= "Arizona";
			else if((zip >= 716 && zip <= 729) || zip == 755) state= "Arkansas";
			else if(zip == 967) state= "American Samoa";
			else if(zip >= 900 && zip <= 966) state= "California";
			else if(zip >= 800 && zip <= 816) state= "Colorado";
			else if(zip >= 60 && zip <= 69) state= "Connecticut";
			else if(zip >= 200 && zip <= 205) state= "Washington DC";
			else if(zip >= 197 && zip <= 199) state= "Delaware";
			else if((zip >= 320 && zip <= 349) && (zip != 343 && zip !=345 && zip!=348)) state= "Florida";
			else if(zip >= 300 && zip <= 319) state= "Georgia";
			else if(zip == 969) state= "Guam";
			else if(zip >= 967 && zip <= 968) state= "Hawaii";
			else if(zip >= 832 && zip <= 838) state= "Idaho";
			else if(zip >= 600 && zip <= 629) state= "Illinois";
			else if(zip >= 460 && zip <= 479) state= "Indiana";
			else if(zip >= 500 && zip <= 528) state= "Iowa";
			else if(zip >= 660 && zip <= 679) state= "Kansas";
			else if(zip >= 400 && zip <= 427) state= "Kentucky";
			else if(zip >= 700 && zip <= 714) state= "Louisiana";
			else if(zip >= 39 && zip <= 49) state= "Maine";
			else if(zip == 969) state= "Marshall Islands";
			else if(zip >= 206 && zip <= 219) state= "Maryland";
			else if((zip >= 10 && zip <= 27) || zip == 55) state= "Massachusetts";
			else if(zip >= 480 && zip <= 499) state= "Michigan";
			else if(zip >= 550 && zip <= 567) state= "Minnesota";
			else if(zip >= 386 && zip <= 397) state= "Mississippi";
			else if(zip >= 630 && zip <= 658) state= "Missouri";
			else if(zip >= 590 && zip <= 599) state= "Montana";
			else if(zip >= 680 && zip <= 693) state= "Nebraska";
			else if(zip >= 889 && zip <= 898) state= "Nevada";
			else if(zip >= 30 && zip <= 38) state= "New Hampshire";
			else if(zip >= 70 && zip <= 89) state= "New Jersey";
			else if(zip >= 870 && zip <= 884) state= "New Mexico";
			else if((zip >= 90 && zip <= 149) || zip == 4 || zip == 63) state= "New York";
			else if(zip >= 269 && zip <= 289) state= "North Carolina";
			else if(zip >= 580 && zip <= 588) state= "North Dakota";
			else if(zip >= 430 && zip <= 458) state= "Ohio";
			else if(zip >= 730 && zip <= 749) state= "Oklahoma";
			else if(zip >= 970 && zip <= 979) state= "Oregon";
			else if(zip >= 150 && zip <= 196) state= "Pennsylvania";
			else if(zip >= 6 && zip <= 9) { 
				if(zip==8) state="Virgin Islands";
				else state= "Puerto Rico";
			}
			else if(zip >= 28 && zip <= 29) state= "Rhode Island";
			else if(zip >= 290 && zip <= 299) state= "South Carolina";
			else if(zip >= 570 && zip <= 577) state= "South Dakota";
			else if(zip >= 370 && zip <= 385) state= "Tennessee";
			else if((zip >= 750 && zip <= 799) || zip == 885) state= "Texas";
			else if(zip >= 840 && zip <= 847) state= "Utah";
			else if(zip >= 50 && zip <= 59) state= "Vermont";
			else if((zip >= 220 && zip <= 246) || zip == 201) state= "Virginia";
			else if(zip >= 980 && zip <= 994) state= "Washington";
			else if(zip >= 530 && zip <= 549) state= "Wisonsin";
			else if(zip >= 247 && zip <= 268) state= "West Virginia";
			else if(zip >= 820 && zip <= 831) state= "Wyoming";
			else state= "";
				
			fsParent.children("div").children(".state").val(state); 				// Sets $(".state").val() to var state from if/else
			fsParent.children("div").children(".state").prev().text("State");		// $.prev() sets label for $(".state") to text()
			fsParent.children(".zip").prev().text("Zip Code");						// $.prev() sets label for $(".zip") to text()
			
			if (state!="") setSelectedIndex(fsParent.children("div").children(".country"), "USA");
			else setSelectedIndex(fsParent.children("div").children(".country"), "");
			
		} else if(isValidCA(zip)) {
			$(this).prev().text("Postal Code");
			
			if(zip%1 != 0) {
				zip= zip.toUpperCase();
				fsa= zip.substring(0,1);
				nuna= zip.substring(0,3);
				
				title="Province";
				switch(fsa) {
					case "A": { state="Newfoundland and Labrador"; break; }
					case "B": { state="Nova Scotia"; break; }
					case "C": { state="Prince Edward Island"; break; }
					case "E": { state="New Brunswick"; break; }
					case "G": { state="Qu\351bec"; break; }
					case "H": { state="Qu\351bec"; break; }
					case "J": { state="Qu\351bec"; break; }
					case "K": { state="Ontario"; break; }
					case "L": { state="Ontario"; break; }
					case "M": { state="Ontario"; break; }
					case "N": { state="Ontario"; break; }
					case "P": { state="Ontario"; break; }
					case "R": { state="Manitoba"; break; }
					case "S": { state="Saskatchewan"; break; }
					case "T": { state="Alberta"; break; }
					case "V": { state="British Columbia"; break; }
					case "X": { 
						if (nuna=="X0A" || nuna=="X0B" || nuna=="X0C")
							state= "Nunavut";
						else state= "Northwest Territories";
						
						title="Territory";
						break;
					}
					case "Y": { state="Yukon Territory"; title="Territory"; break; }
				}

				fsParent.children("div").children(".state").prev().text(title);
				fsParent.children("div").children(".state").val(state);
				
				if (state!="") setSelectedIndex(fsParent.children("div").children(".country"), "Canada");
				else setSelectedIndex(fsParent.children("div").children(".country"), "");
			}
		} else {
				setSelectedIndex(fsParent.children(".country"), "");
				fsParent.children(".zip").prev().text("Zip Code");
				fsParent.children("div").children(".state").prev().text("State");
				fsParent.children("div").children(".state").val("");
		}
	});
});


function popCCNum(val) {
	$("#ccnum").val(val.replace(/-/g,""));
}

// Phone number validation courtesy of:
// http://www.scriptygoddess.com/archives/2008/05/03/phone-number-validation-with-jquery/
$.validator.addMethod("phone", function(phone_number, element) {
var digits = "0123456789";
var phoneNumberDelimiters = "()- ext.";
var validWorldPhoneChars = phoneNumberDelimiters + "+";
var minDigitsInIPhoneNumber = 7;
s=stripCharsInBag(phone_number,validWorldPhoneChars);
return this.optional(element) || isInteger(s) && s.length >= minDigitsInIPhoneNumber;
}, "Invalid number");

function isInteger(s) {
	var i;
	for (i = 0; i < s.length; i++) {
		// Check that current character is number.
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) return false;
	}
	// All characters are numbers.
	return true;
}

function stripCharsInBag(s, bag) {
	var i;
	var returnString = "";
	// Search through string's characters one by one.
	// If character is not in bag, append to returnString.
	for (i = 0; i < s.length; i++) {
		// Check that current character isn't whitespace.
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}

function setSelectedIndex(s, v) { // s= dropdown, v= value
	$(s).children().each(function() {
		if (this.value == v)
			this.selected= true;
	});
}

function isValidUS(zip){
	/*
	supports at minimum 5 digits and maximum 9 USA zip code is not strict on the required "-" between 5 and 4
	$1 = 5 digit ZIP
	$4 = 4 digit ZIP + 4
	*/
	var reZip = /^(\d{3,5})((\D*?)(\d{0,4}))?$/; 
	
	return reZip.test(zip);
}

function isValidCA(zip){
	var reZip = /^([a-zA-Z]\d[a-zA-Z])(( |-)?)((\d)|(\d[a-zA-Z])|(\d[a-zA-Z]\d))?$/;
	
	return reZip.test(zip);
}