/* VERSIONS
/* 1_0_5 (20xxMMdd): 
/* 1_0_4 (20xxMMdd): 
/* 1_0_3 (20090717): form.validate now validates. Legacy Support for forms without .validate
/* 1_0_2 (20xxMMdd): // Planned [AHCTPAC across all forms]
/* 1_0_1 (20090116): Bug fixes to Watermarks.
					 Tested Compatibility with:
					 --jQuery 1.3 (previously 1.2.6)
					 --Validate 1.5.1 (previously 1.3)
					 --Masked Input 1.2.1 (previously 1.2)
/* 1_0_0 (20081212): Initial Release! It's been a fun few months!
----------------------------------------------------------------------------- */


/* 
-----------------------------------------------------------------------------
 =jQuery Calls
----------------------------------------------------------------------------- */
$(document).ready(function(){
	
	/* 
	-----------------------------------------------------------------------------
	 =Default Form Validation Calls, Messages, Rules
	----------------------------------------------------------------------------- */
	
	var formValidator = $("form.validate").validate({	
		messages: {
			classyear: {
				min: "Invalid class year",
				max: "Invalid class year"
			},
			total: {
				min: "Invalid value",
				max: "Invalid value"
			},
			zip: {
				minlength: "Invalid zip code"
			},
			CVV: {
				min: "Invalid value",
				max: "Invalid value"
			}
		},
        invalidHandler: function () {
            try {
                $("#formvalidationsummary").text("There was a problem validating the form: " + formValidator.numberOfInvalids() + " validation error(s) found.");
            } catch(ex) { }
        }
	});
	
	
	/* Basic Form Validation */
	$(".basic").validate({	
		messages: {
			zip: {
				minlength: "Invalid zip code"
			}
		}
	});
	// nothing to see here, folks
	
	/* Inquiry Form Validation */
	$(".inquiry").validate({	
		messages: {
			classyear: {
				min: "Invalid class year",
				max: "Invalid class year"
			},
			zip: {
				minlength: "Invalid zip code"
			}
		}
	});
	// nothing to see here, folks

	// Giving, Credit Card Validation
	$(".giving, .cc").validate({	
		messages: {
			classyear: {
				min: "Invalid class year",
				max: "Invalid class year"
			},
			total: {
				min: "Invalid value",
				max: "Invalid value"
			},
			zip: {
				minlength: "Invalid zip code"
			},
			CVV: {
				min: "Invalid value",
				max: "Invalid value"
			}
		}
	});
	
	/* 
	-----------------------------------------------------------------------------
	 =Misc. Functions
	----------------------------------------------------------------------------- */
	
	/* Change some HTML for validation styling */
	$("div#content form fieldset div").each(function(i) {
		if($(this).children().hasClass("required")){ $(this).addClass("required");  } 
	});
	$("div#content form fieldset div ul.checkwrap li").each(function(i) {
		if($(this).children().hasClass("required")){ $(this).parent().parent().addClass("required");  } 
	});
	$("div#content form fieldset").each(function() {
		if($(this).children(".required").length >= 1) $(this).addClass("required");
	 });

	/* Forms with submit buttons which have .processing
	 * will, on a successful submit, have the submit
	 * button changed to a "Processing" Span */
	 $("div#content form").submit(function() {
		if($(this).valid()) {
			// Don't submit the emailAddress field onsubmit
			if($("#emailAddressDiv").length > 0)
				$("#emailAddressDiv").remove();
			
			$("input.submit.processing").replaceWith("<span class=\"processing\">Processing...</span>");
			return true;
		} else return false;
	});

	// Hide AHCTPAC Field If Applicable
	if($("#emailAddressDiv").length != 0) {
		$("#emailAddressDiv").hide();
	}

	$(window).load(function() {
		if($("fieldset span.processing").length >= 1)
			$("fieldset span.processing").replaceWith("<input type=\"submit\" value=\"Submit\" class=\"submit button processing\" />")
		$(".zip").keyup();		// Trigger the keyup of all .zip fields to autofill countries.
	});
	
	/* 
	-----------------------------------------------------------------------------
	 =Watermarks
	----------------------------------------------------------------------------- */
	
	if($("#donor").length) $("#donor").Watermark("Anonymous");
	else if($(".donor").length) $(".donor").Watermark("Anonymous");	
	// Should be fairly obvious...
	
	if($("#dob").length) $("#dob").unmask().mask("99/99/9999",{placeholder:"_"}).Watermark("mm/dd/yyyy");
	else if($(".dob").length) $(".dob").unmask().mask("99/99/9999",{placeholder:"_"}).Watermark("mm/dd/yyyy");
	else if($(".fulldate").length) $(".fulldate").unmask().mask("99/99/9999",{placeholder:"_"}).Watermark("mm/dd/yyyy");
	// Date of Birth field accepts dates in this format
	
	if($(".classyear").length) $(".classyear").unmask().mask("9999",{placeholder:"y"});
	else if($(".classYear").length) $(".classYear").unmask().mask("9999",{placeholder:"y"});
	else if($(".ClassYear").length) $(".ClassYear").unmask().mask("9999",{placeholder:"y"});
	// Requires classyear to be four digits
	
	/* 
	-----------------------------------------------------------------------------
	 =Credit Card Form Special Provisions		(any form which accepts cc's)
	----------------------------------------------------------------------------- */
	
	/* Modify forms with a credit card fieldset */
	if($("#ccnum").length == 1) {
		$(window).load(function() {
			$("#divccnumprelim").show();
			$("#divccnum").hide();
			if($("span#ccnumprelim").length >= 1) {
				var cc= $("span#ccnumprelim").text();
				$("#ccnumprelim").replaceWith("<input type=\"text\" name=\"ccnumprelim\" id=\"ccnumprelim\" class=\"required creditcard\" onblur=\"javascript:popCCNum(this.value);\" />");								
				$("input[id=ccnumprelim]").val(cc);
				popCCNum($("#ccnumprelim").val());
			}
			applyMasks();
		});
		
		$("form.cc").submit(function() {
			if($(this).valid())
				$("input#ccnumprelim").replaceWith("<span id=\"ccnumprelim\">"+$("input#ccnumprelim").val()+"</span>");
		});
	}
	
	function applyMasks() {	
		// Define Credit Card Placeholders...
		// http://en.wikipedia.org/wiki/Credit_card_number#Prefixes
        $.mask.definitions['v']="[4]";		// All Visas begin with '4' [v]
        $.mask.definitions['m']="[5]";		// All Mastercards begin with a
        $.mask.definitions['c']="[12345]";	// number from 51-55 [m, c]
        $.mask.definitions['a']="[3]";		// All AmEx begin with either a
        $.mask.definitions['x']="[47]";		// 34 or a 37 [a, x]
        $.mask.definitions['d']="[6]";		// All Discover Cards begin with 6
        $.mask.definitions['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:"_"});
			}
		});
	}
	
/* 
-----------------------------------------------------------------------------
 =Zip Code Autocomplete 		(no reason to really modify this -- 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 >= 220 && zip <= 246) || zip == 201) state= "Virginia";
			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= "Wisconsin";
			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("");
		}
	});
});

/* 
-----------------------------------------------------------------------------
 =More Misc. Functions 					(called above / in other files)
----------------------------------------------------------------------------- */
/*
function addMore(maxNum, dupeGroup, replaceString, replaceWith) {
	if (maxNum==$("."+dupeGroup).length) // If clicked when you cannot add anymore...
		return false;	// Ze clicks! Zey do nossing!
	
	var class= $("."+dupeGroup).parents("fieldset").attr("class");
	var code= $("."+dupeGroup+":eq(0)").html();
	
	// Replace the values found with unique values for each field
	var re = new RegExp(replaceString, "g");
	code= code.replace(re, replaceWith+(1+$("."+dupeGroup).length));
	
	// Adds it immediately after the last sibling
	$("."+dupeGroup+":last").after("<div class=\""+dupeGroup+"\">"+code+"</div>");

	var addsLeft= maxNum - $("."+dupeGroup).length;
	$("fieldset."+class+" .addMore").text("Add Another ("+addsLeft+" left)");
	if (addsLeft==0) { // If you cannot add anymore
		$("fieldset."+class+" .addMore").addClass("expired");
	}
	SI_clearFooter();
}
*/

function setReq() {
	$('#content fieldset > div .required:hidden')
		.closest('div')
		.hide()
			.find('.required')
			.removeClass('required error')
			.addClass('req_ph');
	$('#content fieldset > div .req_ph:not(:hidden)')
		.closest('div')
		.show()
			.find('.req_ph')
			.removeClass('req_ph')
			.addClass('required');
}

function showHideField(bool, fieldName) {
    $fieldContainDiv = $('form fieldset [name=' + fieldName + ']').closest('div');

	if (!$fieldContainDiv.length) {
	    $fieldContainDiv = $('legend:contains("' + fieldName + '")').closest('fieldset');
	    if (!$fieldContainDiv.length) {
	        $fieldContainDiv = $('p').closest('div#' + fieldName);
	        if (!$fieldContainDiv.length) {
	            return;
	        }
	    }
	}
	
	if(bool) {
		$fieldContainDiv.show('slow', SI_clearFooter);
    } else {
        $fieldContainDiv.hide('slow', SI_clearFooter);
        clearAllFieldValues($fieldContainDiv);
	}
	setTimeout(setReq, 700);
}

function showHideFieldset(bool, fieldsetName) {
    var $fieldContainDiv = null;

    $('form fieldset legend').each(function () {
        if ($(this).text() === fieldsetName) {
            $fieldContainDiv = $(this).closest("fieldset");
            return false;
        }
    });

    if ($fieldContainDiv && $fieldContainDiv.length > 0) {
        if (bool) {
            $fieldContainDiv.show().children().show();

            var fields = jsonFieldsets[fieldsetName];

            if (fields.length > 0) {
                for (var i = 0; i < fields.length; i++) {
                    showHideField(false, fields[i]);
                }
            }
        } else {
            $fieldContainDiv.hide();
        }

        SI_clearFooter();
        clearAllFieldValues($fieldContainDiv);
        setTimeout(setReq, 700);
    }
}

function clearAllFieldValues(scope) {
	$(scope).find("input:text, select, textarea").val("");
	$(scope).find("input:checked").removeAttr("checked").click().removeAttr("checked");
}


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(ph, element) {
	if (ph == null || ph == "") {
		return true;
	}
	var stripped = ph.replace(/[\s()+-]|ext\.?/gi, "");
	// 10 is the minimum number of numbers required
	return ((/\d{10,}/i).test(stripped));
}, "Invalid phone number");

function setSelectedIndex(s, v) { // s= dropdown, v= value
	$(s).children().each(function() {
		if (this.value == v)
			this.selected= true;
	});
}
// End phone number validation Script

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);
}

// Required by the Microsoft Ajax Framework:
if ((typeof Sys !== "undefined") && (typeof Sys.Application !== "undefined")) {
    Sys.Application.notifyScriptLoaded();
}
