// JavaScript Document/*===============================================================================================================
	Owner:	Hill's Pet Nutrition
	Title:		3 Bag Challenge Registration Javascript Document
	Author:	Steve Kiernan
	Date: 		12/24/09
	Disc:		This document is responsible for the client-side functionality used during the 3BagChallenge registration
					process...	(i.e.  Form Validation, AJAX, jQuery) 
	Note(s):	The following jQuery Libraries/Plug-ins are REQUIRED...
						- jquery-1.3.2.js (or jquery-1.3.2.min.js)
						- jquery.form.js (version: 2.36)
						- jquery.validate.js (version: 1.5.5)
					The javascript calls need to be loaded into the HTML in the following order within the <head></head> tags.
						<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
						<script type="text/javascript" src="jquery.form.js"></script>
						<script type="text/javascript" src="jquery.validate.js"></script>
						<script type="text/javascript" src="3BagRegForm.js"></script>
===============================================================================================================*/
$(document).ready(function() {
	var emailParam = $.getUrlVar('email');
	if (emailParam) {
		//Load the form and append email param (HTML form generated by java)
		$("#form_container").load("registerParticipant.do?email="+emailParam, function(){
			//Initialize client-side validation
			init();
		});
	}
	else {
		//Load the form (HTML form generated by java)
		$("#form_container").load("registerParticipant.do", function(){
			//Initialize client-side validation
			init();
		});
	}
});

function init() {
	getUserType();
	classimizeInputs();
	initValidation();
	swfBannerReferer();
	//$('#continue').click(function(){
		$('#continue').attr('onsubmit', "pageTracker._linkByPost(this);");  							 
	//});
}

function getUserType() {
	//var userType = $("select#UserType").val();
	var userType = $("#userType :selected").val();
	showCustomFields(userType);
}

function swfBannerReferer() { //an external media banner can pass parameters to this form, we need to check for the existance of these parameters and populate the form with the value of those parameters
	var firstNameParam = $.getUrlVar('fName');
	var lastNameParam = $.getUrlVar('lName');
	var emailParam = $.getUrlVar('swf_email');
	if (firstNameParam) { //if one param exists, assume they will all 3 exist
		//insert the external param values into the registration  form
		$('#firstName').val(firstNameParam);
		$('#lastName').val(lastNameParam);
		$('#email').val(emailParam);
	}
}

function hideCustomFields() {
	var items = $("#customFields_container").children("div");
	for (i=0; i<items.length; i++) {
		items[i].className = "item hide";
	}
}

function resetLoaderAnim() {
	var currState = $("#school_loader").attr("class");
	if (currState) {
		if (currState == "loaded") {
			$("#school_loader").removeClass("loaded").addClass("loading");
		}
	}
}

//==== START: ADD CLASSNAMES TO INPUT FIELDS =====================================================//
//Add a classname to specific input fields that will allow us to target them via CSS (i.e. buttons, checkboxes, etc..)
//This is primarily necessary because IE6 doesn't recognize attribute selectors in CSS2
function classimizeInputs() {
	var inputs = document.getElementsByTagName('input');
	var inputsLen = inputs.length;
	var i = 0;
	for ( i=0;i<inputsLen;i++ ) {
		if (inputs[i].getAttribute('type') == "radio") {
			inputs[i].className += ' radio';
		}
		if (inputs[i].getAttribute('type') == "checkbox") {
			inputs[i].className += ' checkbox';
		}
		if(inputs[i].type == "image" || inputs[i].type == "button" || inputs[i].type == "submit" || inputs[i].type == "reset") {
			inputs[i].className = " button";
		}
	}
}
//==== END: ADD CLASSNAMES TO INPUT FIELDS =====================================================//

//==== START: SHOW CUSTOM FIELDS FUNCTION ===================================================//
function showCustomFields(userType) {
	hideCustomFields(); //Hide all custom fields before displaying new ones... (acts as a reset)
	resetLoaderAnim(); //Reset the loading animation used when fetching json requests to populate the schools dropdown
	
	//Pet Owner | Other | Select One (default value)
	if(userType == 1 || userType == 2 || userType == "") {
		//do nothing... this is the default form display       
	}
	//Veterinarian | Veterinary Technician
	if(userType == 46 || userType == 36) {
		$("#clinicName_wrapper").removeClass("hide").addClass("show");
		$("#numOfVets_wrapper").removeClass("hide").addClass("show");
		$("#schoolName_wrapper").removeClass("hide").addClass("show");
		$("#gradYear_wrapper").removeClass("hide").addClass("show");
		$("#hillsAcctNum_wrapper").removeClass("hide").addClass("show");
	}
	//Veterinary Student | Veterinary Technician Student
	if(userType == 26 || userType == 21) {
		$("#schoolName_wrapper").removeClass("hide").addClass("show");
		$("#gradYear_wrapper").removeClass("hide").addClass("show");
	}
	//Academician
	if(userType == 41) {
		$("#schoolName_wrapper").removeClass("hide").addClass("show"); //show vet schools
		$("#academicRole_wrapper").removeClass("hide").addClass("show");
		$("#specialty_wrapper").removeClass("hide").addClass("show");
	}
	//Office Manager
	if(userType == 31) {
		$("#clinicName_wrapper").removeClass("hide").addClass("show");
		$("#numOfVets_wrapper").removeClass("hide").addClass("show");
		$("#position_wrapper").removeClass("hide").addClass("show");
		$("#hillsAcctNum_wrapper").removeClass("hide").addClass("show");
	}
	//Pet Store Owner | Business Partner
	if(userType == 12 || userType == 11) {
		$("#storeName_wrapper").removeClass("hide").addClass("show");
		$("#storeType_wrapper").removeClass("hide").addClass("show");
		$("#hillsAcctNum_wrapper").removeClass("hide").addClass("show");
	}
	
	//The following user types require the "School Name" select box. 
	//Determine how to populate the school drop-down based off selected user type.
	if(userType == 46 || userType == 41 || userType == 36 || userType == 26 || userType == 21) {
		if(userType == 46 || userType == 41 || userType == 26) { //Veterinarian | Academician | Veterinary Student 
			//alert('pop()vet');
			populateSchools("VET");
		}
		else { //Veterinary Technician | Veterinary Technician Student
			//alert('pop()tech');
			populateSchools("VTECH");
		}
	}
}
//==== END: SHOW CUSTOM FIELDS FUNCTION =====================================================//

//==== START: POPULATE SCHOOL SELECTBOX  =====================================================//
function populateSchools(param){
	//alert('param = ' + param);
	$.ajax({
		type: "GET",
		url: "schoolTypeList.do?schoolType=" + param,
		cache: false,
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		beforeSend: function(x) {
			if(x && x.overrideMimeType) {
				x.overrideMimeType("application/json; charset=utf-8");
			}
			if(!document.getElementById("school_loader")){
				$("#schoolName").wrap("<div id='school_loader' class='loading'></div>");
			}
			$("#schoolName").hide();
		},
		success: function(data){
			//alert("json[array].length = " + data.length);
			var selectedSchool = $("select#schoolName").val();
			var optElms = "<option value=''>Select One</option>";      
			for (var i = 0; i < data.length; i++) {
				optElms += "<option value='" + data[i].key + "'>" + data[i].value + "</option>";
			}      
			$("#school_loader").removeClass("loading").addClass("loaded");
			$("select#schoolName").html(optElms);
			if (selectedSchool > 0) {
				$("select.#schoolName").val(selectedSchool);
			}
			$("select#schoolName").show();
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			alert("XMLHttpRequest="+XMLHttpRequest.responseText+"\ntextStatus="+textStatus+"\nerrorThrown="+errorThrown);
		}
	});
}
//==== END: POPULATE SCHOOL SELECTBOX =====================================================//


//==== START: JQUERY VALIDATOR - CUSTOM METHODS =====================================================//
//Valid US phone number
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
	phone_number = phone_number.replace(/\s+/g, ""); 
	return this.optional(element) || phone_number.length > 9 &&
	phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid US phone number");
//==== END: JQUERY VALIDATOR - CUSTOM METHODS =====================================================//

function showLoaderAnim() {
	$("#userProfile").animate({
		opacity: 0.4
	}, 500 );
	$("#form_container").append('<div style="position:absolute; top:50px; left:0; width:100%; z-index:9999;"><center><br /><img src="/believe/images/img_forms_ajaxLoader_red.gif" alt="loading" border="0" /><br /><br /><span style="color:#F20017; font-weight:bold; font-size:14px;">...transmitting data</span></center></div>');
}
function hideLoaderAnim() {
	$("#userProfile").animate({
		opacity: 1.0
	}, 500 );
}

//==== START: INITIALIZE FORM VALIDATION RULES  =====================================================//
function initValidation() {
	var container = $("div.errorContainer");
	var options = { 
		target: '#form_container',
		beforeSubmit: function(){
			showLoaderAnim();
		},
		success: function(){
			//hideLoaderAnim();
			init();
			$("#errorDisplay").css("display", "block");
		}
	}; 
	var validator = $("#userProfile").validate({
		debug: true,
		errorContainer: container,
		errorLabelContainer: $("ol", container),
		wrapper: "li",
		meta: "validate",
		rules: {
			title: "required",
			firstName: "required",
			lastName: "required",
			address1: "required",
			city: "required",
			state: "required",
			postalCode: {
				required: true,
				digits: true,
				minlength: 5,
				maxlength: 5
			},
			phone: {
				required: false,
				digits: true,
				phoneUS: true
			},
			userTypeCode: "required",
			//////// START: Custom Field(s) Dependancies ////////////
			clinicName: {
				required: function(element) {
					return $("#userType").val() == 31 || $("#userType").val() == 36 || $("#userType").val() == 46;
				}
			},
			schoolCode: {
				required: function(element) {
					return $("#userType").val() == 21 || $("#userType").val() == 26 || $("#userType").val() == 36 || $("#userType").val() == 41 || $("#userType").val() == 46;
				}
			},
			academicRole: {
				required: function(element) {
					return $("#userType").val() == 41;
				}
			},
			petSpecialty: {
				required: function(element) {
					return $("#userType").val() == 41;
				}
			},
			storeName: {
				required: function(element) {
					return $("#userType").val() == 11 || $("#userType").val() == 12;
				}
			},
			storeType: {
				required: function(element) {
					return $("#userType").val() == 11 || $("#userType").val() == 12;
				}
			},
			hillsAccountNumber: {
				required: false,
				digits: true,
				minlength: 4,
				maxlength: 6
			},
			//////// END: Custom Field(s) Dependancies ////////////
			petType: "required",
			email: {
				required: true,
				email: true
			},
			confirmEmail: {
				required: true,
				equalTo: "#email"
			},
			password: {
				required: true,
				minlength: 6
			},
			confirmPassword: {
				required: true,
				equalTo: "#password"
			},
			optIn: "required",
			overEighteen: "required"
		},
		messages: {
			title: "Please select your <a href='javascript:void(0);' onclick='document.userProfile.title.focus(); return false;'>Preferred Title</a>",
			firstName: "Please enter your <a href='javascript:void(0);' onclick='document.userProfile.firstName.focus(); return false;'>First Name</a>",
			lastName: "Please enter your <a href='javascript:void(0);' onclick='document.userProfile.lastName.focus(); return false;'>Last Name</a>",
			address1: "Please enter your <a href='javascript:void(0);' onclick='document.userProfile.address1.focus(); return false;'>Address</a>",
			city: "Please enter your <a href='javascript:void(0);' onclick='document.userProfile.city.focus(); return false;'>City</a>",
			state: "Please select your <a href='javascript:void(0);' onclick='document.userProfile.state.focus(); return false;'>State</a>",
			postalCode: {
				required: "Please enter your <a href='javascript:void(0);' onclick='document.userProfile.postalCode.focus(); return false;'>Zip Code</a>",
				digits: "<a href='javascript:void(0);' onclick='document.userProfile.postalCode.focus(); return false;'>Zip Code:</a> Only numeric values between 0-9 are accepted",
				minlength: "<a href='javascript:void(0);' onclick='document.userProfile.postalCode.focus(); return false;'>Zip Code:</a> Please enter at least 5 digits",
				maxlength: "<a href='javascript:void(0);' onclick='document.userProfile.postalCode.focus(); return false;'>Zip Code:</a> Please do not enter more than 5 digits"
			},
			phone: {
				digits: "<a href='javascript:void(0);' onclick='document.userProfile.phone.focus(); return false;'>Phone:</a> Only numeric values between 0-9 are accepted",
				phoneUS: "<a href='javascript:void(0);' onclick='document.userProfile.phone.focus(); return false;'>Phone:</a> Please enter a valid US telephone number with no dashes (i.e. 5555555555)"
			},
			userTypeCode: "Please select your <a href='javascript:void(0);' onclick='document.userProfile.userType.focus(); return false;'>User Type</a>",
			clinicName: "Please enter your <a href='javascript:void(0);' onclick='document.userProfile.clinicName.focus(); return false;'>Clinic Name</a>",
			schoolCode: "Please select your <a href='javascript:void(0);' onclick='document.userProfile.schoolName.focus(); return false;'>School Name</a>",
			academicRole: "Please select your <a href='javascript:void(0);' onclick='document.userProfile.academicRole.focus(); return false;'>Academic Role</a>",
			petSpecialty: "Please select your <a href='javascript:void(0);' onclick='document.userProfile.petSpecialty.focus(); return false;'>Pet Specialty</a>",
			storeName: "Please enter your <a href='javascript:void(0);' onclick='document.userProfile.storeName.focus(); return false;'>Store Name</a>",
			storeType: "Please select your <a href='javascript:void(0);' onclick='document.userProfile.storeType.focus(); return false;'>Store Type</a>",
			petType: "Please select the <a href='javascript:void(0);' onclick='document.userProfile.petType.focus(); return false;'>Type of Pets</a> you own",
			hillsAccountNumber: {
				digits: "<a href='javascript:void(0);' onclick='document.userProfile.hillsAccountNumber.focus(); return false;'>Hill's Account Number:</a> Only numeric values between 0-9 are accepted",
				minlength: "<a href='javascript:void(0);' onclick='document.userProfile.hillsAccountNumber.focus(); return false;'>Hill's Account Number:</a> Please enter at least 4 digits",
				maxlength: "<a href='javascript:void(0);' onclick='document.userProfile.hillsAccountNumber.focus(); return false;'>Hill's Account Number:</a> Please do not enter more than 6 digits"
			},
			email: {
				required: "Please enter your <a href='javascript:void(0);' onclick='document.userProfile.email.focus(); return false;'>Email Address</a>",
				email: "Your <a href='javascript:void(0);' onclick='document.userProfile.email.focus(); return false;'>Email Address</a> must be in the format of name@domain.com"
			},
			confirmEmail: {
				required: "Please <a href='javascript:void(0);' onclick='document.userProfile.confirmEmail.focus(); return false;'>Confirm Your Email Address</a>",
				equalTo: "Your <a href='javascript:void(0);' onclick='document.userProfile.confirmEmail.focus(); return false;'>Confirmation Email</a> does not match"
			},
			password: {
				required: "Please enter a <a href='javascript:void(0);' onclick='document.userProfile.password.focus(); return false;'>Password</a>",
				minlength: "Your <a href='javascript:void(0);' onclick='document.userProfile.password.focus(); return false;'>Password</a> must be at least 6 characters in length"
			},
			confirmPassword: {
				required: "Please <a href='javascript:void(0);' onclick='document.userProfile.confirmPassword.focus(); return false;'>Confirm Your Password</a>",
				equalTo: "Your <a href='javascript:void(0);' onclick='document.userProfile.confirmPassword.focus(); return false;'>Confirmation Password</a> does not match"
			},
			optIn: "<a href='javascript:void(0);' onclick='document.userProfile.optIn.focus(); return false;'>Please choose whether Hill's can contact you via Email</a>",
			overEighteen: "Please confirm that you are <a href='javascript:void(0);' onclick='document.userProfile.overEighteen.focus(); return false;'>18 years or older</a>"
		},
		showErrors: function() {
			$("#errorCount").text(validator.numberOfInvalids() + " error(s) found");
			this.defaultShowErrors();
		},
		invalidHandler: function() {
			$("#errorCount").text(validator.numberOfInvalids() + " error(s) found");
		},
		submitHandler: function(form) {
			$("#errorCount").text(validator.numberOfInvalids() + " error(s) found");
			$("#userProfile").ajaxSubmit(options);
		}
	});
	$("select").change(function(){
		$(this).valid();
	});
	$("select#userType").change(function(){
		var getCurrErrStatus = $("#errorDisplay").attr("style");
		var myRegExp = /display: block/;
		getCurrErrStatus = getCurrErrStatus.match(myRegExp);
		if (getCurrErrStatus != null) {
			$("#clinicName").valid();
			$("#schoolName").valid();
			$("#academicRole").valid();
			$("#petSpecialty").valid();
			$("#storeName").valid();
			$("#storeType").valid();
			$("#userProfile").valid();
		}
	});
}
//==== END: INITIALIZE FORM VALIDATION RULES  =====================================================//
function openPopDivIE() {
	$("#open_popdiv").click(function() {
			$("select").hide();
	});
	$("#close_popdiv").click(function() {
			$("select").show();
	});
}

$.extend({
	getUrlVars: function(){
		var vars = [], hash;    
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');    
		for(var i = 0; i < hashes.length; i++) {
			hash = hashes[i].split('=');
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}    
		return vars;  
	}, getUrlVar: function(name){
		return $.getUrlVars()[name];  
	}
});