function capitalizeMe(obj) {
        var val = obj;
        newVal = '';
        val = val.split(' ');
        for(var c=0; c < val.length; c++) {
                newVal += val[c].substring(0,1).toUpperCase() +
val[c].substring(1,val[c].length) + ' ';
        }
        return newVal;
}

(function($) {
		
		$.extend($.fn, {
			
			getCheckboxValues : function(id) {
				
				var values = new Array();
				$("input[id=" + id +"]").each(function(){
					if($(this).attr("checked"))
						values[values.length] = $(this).val();
				});
				
				return values.join(",");
			},
			
			getZipData : function(zip) {
				
				if(typeof rootLink == "undefined")
					rootLink = "";
					
				var suffix = "ws/getStateFromZip.php?zip=" + zip;
				
				var url = window.location.toString();
				var cutIndex = url.lastIndexOf("/");
				url = url.substring(0, cutIndex);
				if(suffix.charAt(0) == "/") {
					suffix = suffix.substring(1);
				}
				var finalUrl = url + "/" + rootLink + suffix;
				//alert(url);
				
				var json = $.ajax({url:finalUrl, async: false, cache:true}).responseText;
				if(json.charAt(0) != "{") {
					finalUrl = url + "/" + suffix;
					var json = $.ajax({url:finalUrl, async: false, cache:true}).responseText;
				}
				
				var evalString = " json = " + json + ";";
				eval(evalString);
				
				return json;
			},
			
			getTypoData : function() {
				
				if(typeof rootLink == "undefined")
					rootLink = "";
					
				var suffix = "ws/typos.php";
				
				var url = window.location.toString();
				var cutIndex = url.lastIndexOf("/");
				url = url.substring(0, cutIndex);
				if(suffix.charAt(0) == "/") {
					suffix = suffix.substring(1);
				}
				var finalUrl = url + "/" + rootLink + suffix;
				//alert(url);
				
				var json = $.ajax({url:finalUrl, async: false, cache:true}).responseText;
				if(json.charAt(0) != "a") {
					finalUrl = url + "/" + suffix;
					var json = $.ajax({url:finalUrl, async: false, cache:true}).responseText;
				}
				
				var array = new Array();
				eval(json);
				
				return array;
				
			},
			
			initRendering : function() {
		
		
				//User Interface
				$('#tabs').tabs();				
				//hover states on the static widgets
				$('#dialog_link, ul#icons li').hover(
					function() { $(this).addClass('ui-state-hover'); }, 
					function() { $(this).removeClass('ui-state-hover'); }
				);
				
				
				
				$("#step2").hide();
				$("#step3").hide();
				$("#step4").hide();
		
				//Initialize Validation				
				var container = $('div.errorContainer');
				
				container.hide();
				
				$.validator.addMethod("zipUS", function(value, element, param) {
					//var json = $().getZipData(value);
					
					var zipData = $().getZipData(value);
					$("#city").val(zipData.city);
					//$("#city").attr("readonly","readonly");
					$("#state").val(zipData.state);
					//$("#state").attr("readonly","readonly");
						
					if(zipData.city.length == 0)
						return false;
				  	return true;
				});
				
				$.validator.addMethod("emailTypo", function(value, element, param) {
					
					
					if(typeof $.typoData == "undefined") {
						var typoData = $().getTypoData();
						//alert(typoData); 
						$.typoData = typoData;
					} else {
						var typoData = $.typoData;
					}
					
					for(var typo in typoData) {
						
						if(value.indexOf(typo) >= 0) {
							$(element).attr("errorCache", typoData[typo]);
							
							return false;						
						} 
					}
					
					return true;
				} );

				
				// validate the form when it is submitted
				var validator = $("#registration").validate({
							rules: {
								//jobtype: "required",
								//education: "required",
								//interest: "required",
								firstNameFix: "required",
								lastNameFix: "required",
								emailFix: "required",
								zipFix: {
									"required":true,
									"minlength": 5,
									"maxlength": 5,
									"digits": true,
									"zipUS": true
								},
								
								title: "required",
								firstName: "required",
								lastName: "required",
								email: {
									"required" : true,
									"emailTypo" : true,
									"email" : true
								},
								phone: {
									"required": true,
									"minlength": 10,
									"maxlength": 10
								},
								address1: {
									"required" : true,
									minlength: 2
								},
								city: "required",
								state: "required",
								zip: {
									"required":true,
									"minlength": 5,
									"maxlength": 5,
									"digits": true,
									"zipUS": true
								},
								birthday: {
									"required": true,
									"date": true
								},
								resume: {
									"required": false,
									"accept": "doc|docx|pdf|txt"
								},
								gradyear: {
									"required": true
								}
								/*
								progcategory: {
									"required": true
								},
								
								subprogcategory: {
									"required": true
								} 
								//*/
								/*,
								verifyEmail: {
									"required" : true,
									"email" : true
								}*/
								//terms: "required"
							},
							messages : {
								//title : "",
								firstNameFix : "Please enter your First Name.",
								lastNameFix : "Please enter your Last Name.",
								emailFix : "Please enter your Email Address.",
								zipFix : "Please enter your zip code.",
								interest : "Please select an interest.",
								title : "Please select a title!",
								firstName : "Please enter your First Name.",
								lastName : "Please enter your Last Name.",
								email : "Please enter your Email Address.",
								phone : "Please enter your complete Phone No (10 digits).",
								address1 : "Please enter your address (at least 3 characters).",
								city : "Please enter a city.",
								state : "Please select your state.",
								zip : "Please enter your zip code.",
								birthday : "Please select your birthday.",
								resume : "Please select a Document (doc, docx, txt, pdf).",
								terms : "You must agree to the terms of service!",
								verifyEmail : "Please verify your Email Address.",
								progcategory : "Please select a category",
								subprogcategory : "Please select a sub-category",
								gradyear : "Please select a graduation year"
							},
						    
						    highlight : function(element, errorClass) {
						    	$(element).attr("style", "border: 2px red solid");
						    	
						    	if($(element).attr("id") == "birthday") {
						    		$("#birthdayBox").attr("style", "border: 2px red solid;padding:3px;");
						    		$("#birthday").hide();
						    	}
						    },
						    
						    unhighlight : function(element, errorClass) {
						    	$(element).attr("style", "");
						    	
						    	
						    	if(!$(element))
						    		return;
						    	
						    	if($(element).attr("id") == "birthday") {
						    		$("#birthdayBox").attr("style", "");
						    		$(element).parent().find("span#error").html("");
						    		$("#birthday").hide();
						    	} else {
						    		$(element).parent().find("span").html("");
						    	}
						    },
						    
						    
						    errorPlacement: function(error, element) {
						     	var td = element.parent();
						     	var span = td.find("span");
						     	
						     	if(span.length == 0) {
						     		td.append("<span></span>");
						     		span = td.find("span");
						     	}
						     	
						     	var extraBr = "";
						     	if(element.attr("id") == "birthday") {
						     		//extraBr = "<br/>";
						     		span = td.find("span#error");
						     	}
						     	
						     	var message = error.html();
						     	
						     	if($(element).attr("errorCache") != "" &&
						     			typeof $(element).attr("errorCache") != "undefined" ) {
						     		message = $(element).attr("errorCache");
						     		$(element).attr("errorCache", "");
						     	}
						     		     	
						     	span.html(extraBr + "<br/> &nbsp; &nbsp; &nbsp; * - " + message);
						   },
						   
						   submitHandler: function(form) { 
						   	
//						   		var email = $("#email").val();
//						   		$("#verifyEmail").val(email);
//								$("#email").val("");			
//								$("form#registration").find("#step").val(2);
//								$("#dialog").dialog();
							    $().presubmit();
							    $("#submit").attr("disabled",true);
								form.submit();
							    //return false;
							}


				});
				
				$("#nextPage1").click(function() {
										
					var canSubmit = true;
					$("*[validateStep1=true]").each(function(){
						var thisId = $(this).attr("id");
						var result = validator.element("#"+thisId);
						if(result == false)
							canSubmit = false;
					});
								
						
					if(canSubmit) {
						
						var gradyear = $("#gradyear").val();
						if(gradyear == "none" ||
								gradyear == "2010 or later" ||
								gradyear == "1973 or earlier") {
						
							$().forceSubmit();
							
						} else {
							
							//submit partial..						
							var campaignId = $("#campaignId").val();
							var keyword = $("#keyword").val();
						
							var title = $("#title").val();
							var state = $("#state").val();
							var birthday = $("#birthdayBox").getDateboxValue();
							
							var data = {
								campaignId: campaignId,
								kw: keyword,
								keyword: keyword,
								step:1,
								state: state,
								title: title,
								birthday: birthday,
								gradyear: gradyear
							}
							
							$("input[validateStep1]").each(function(){
								var name = $(this).attr("name");
								var value = $(this).val();
								var type = $(this).attr("type");
								
								if(type == "checkbox") {
									if($(this).attr("checked"))
										eval("data." + name + " = \"" + value + "\";");
								} else {
									eval("data." + name + " = \"" + value + "\";");
								}
							});
							
							data.verifyEmail = data.email;
							data.email = "";
							
							
							var action = window.location.toString();
							$.post(action, data);
														
							$("#step1").hide();
							$("#step2").fadeIn();
							$("#zip").focus();
							
						} //end if-else
						
					} //end if-else
					
				});
				
				$("#step1").find("input[type!=button]").each(function(){
					$(this).attr("validateStep1", "true");
				});
				
				$("#step1").find("select").each(function(){
					$(this).attr("validateStep1", "true");
				});
				
				$().addValidation(2);
				$().addValidation(3);
				
				$("#nextPage2").click(function() {
					
										
					//VALIDATE
					var canProceed = true;
					$("*[validateStep2=true]").each(function(){
						var thisId = $(this).attr("id");
						var result = validator.element("#"+thisId);
						if(result == false)
							canProceed = false;
					});
					
					var ed_interestyes = $("#edinterestyes").attr("checked");
					var age = $("#birthdayBox").getAge();
					if(ed_interestyes && $("#tr_consent_call").css("display") == "none" 
						&& age >= 19) {
						$("#edinterestyes").click();
						canProceed = false;
					}
					
					
					if(canProceed) {
						
						var campaignId = $("#campaignId").val();
						var keyword = $("#keyword").val();
					
						var title = $("#title").val();
						var state = $("#state").val();
						var birthday = $("#birthdayBox").getDateboxValue();
						
						var data = {
								campaignId: campaignId,
								kw: keyword,
								keyword: keyword,
								step:2,
								state: state,
								title: title,
								birthday: birthday			
							}
						
						$("input[validateStep2]").each(function(){
							var name = $(this).attr("name");
							var value = $(this).val();
							var type = $(this).attr("type");
							
							if(type == "checkbox") {
								if($(this).attr("checked"))
									eval("data." + name + " = \"" + value + "\";");
							} else if(type == "radio") {
								if($(this).attr("checked"))
									eval("data." + name + " = \"" + value + "\";");
							} else {
								eval("data." + name + " = \"" + value + "\";");
							}
						});
						
						$("select[validateStep2]").each(function(){
							var name = $(this).attr("name");
							var value = $(this).val();
							var type = $(this).attr("type");
							
							eval("data." + name + " = \"" + value + "\";");
							
						});
						
						//== CONDITIONS to bypass submit ==
						var ed_interestyes = $("#edinterestyes").attr("checked");
						var consent_callyes = $("#consent_callyes").attr("checked");
						var age = $("#birthdayBox").getAge();
						
						if(!ed_interestyes) {
							$().forceSubmit();
						} else if(!consent_callyes) {
							$().forceSubmit();
						} else if(age < 19) {
							$().forceSubmit();
						} else {
						//== CONDITIONS to bypass submit ==
							var action = window.location.toString();
							$.post(action, data);
							
							$("#step2").hide();
							$("#step3").fadeIn();
							
							var email = $("#email").val();
							$("#verifyEmail").val(email);
							
							
						} //end if-else
					}					
					
				});
				
				/*
				$("#nextPage3").click(function() {
					
					
					
					//VALIDATE
					var canProceed = true;
					$("*[validateStep3=true]").each(function(){
						var thisId = $(this).attr("id");
						var result = validator.element("#"+thisId);
						if(result == false)
							canProceed = false;						
					});
					
					if(canProceed) {
						
						//== CONDITIONS to bypass submit ==
						var consent_callyes = $("#consent_callyes").attr("checked");
						if(!consent_callyes) {
							$().forceSubmit();
						} else { 
							
							var campaignId = $("#campaignId").val();
							var keyword = $("#keyword").val();
						
							var title = $("#title").val();
							var state = $("#state").val();
							var birthday = $("#birthdayBox").getDateboxValue();
							var data = {
									campaignId: campaignId,
									kw: keyword,
									keyword: keyword,
									step:3,
									state: state,
									title: title,
									birthday: birthday			
								}
							
							$("input[validateStep3]").each(function(){
								var name = $(this).attr("name");
								var value = $(this).val();
								var type = $(this).attr("type");
								
								if(type == "checkbox") {
									if($(this).attr("checked"))
										eval("data." + name + " = \"" + value + "\";");
								} else if(type == "radio") {
									if($(this).attr("checked"))
										eval("data." + name + " = \"" + value + "\";");
								} else {
									eval("data." + name + " = \"" + value + "\";");
								}
							});
							
							$("select[validateStep3]").each(function(){
								var name = $(this).attr("name");
								var value = $(this).val();
								var type = $(this).attr("type");
								
								eval("data." + name + " = \"" + value + "\";");
								
							});
							
							var action = window.location.toString();
							$.post(action, data);
							
							$("#step3").hide();
							$("#step4").fadeIn();
							
							var email = $("#email").val();
							$("#verifyEmail").val(email);
						} //end if-else
					}					
					
				});
				*/
				
				$("#backPage2").click(function() {
					$("#step2").hide();
					$("#step1").fadeIn();
					
					//move firstName to fix
					//move fix to firstName
					/*$("input[fix]").each(function(){
						
						var pairId = $(this).attr("fix");
						var pairObject = $("#" + pairId);
						var value = pairObject.val();
						
						var type = $(this).attr("type");
						if(type == "text") {
							$(this).val(value);
						} else if(type=="checkbox") {							
							$(this).attr("checked", pairObject.attr("checked"));
						}
					})*/
				});
				
				$("#backPage3").click(function() {
					
					$("#consent_callno").click();
					$("#step3").hide();
					$("#step2").fadeIn();
					
					
				});
				
				$("#backPage4").click(function() {
					
					$("#step4").hide();
					$("#step3").fadeIn();
					
					
				});
				
				$("#submit").click(function() {
					$("#subscribe").val("1");
				});
				
				$("#submitNoEmail").click(function() {
					$("#subscribe").val("0");
				});
			
				//==========================
				//change birthday html
				//==========================
				var birthdayTd = $("#birthday").parent(); 
				birthdayTd.prepend("<span id=\"birthdayBox\"></span>");
				$("#birthday").hide();
				birthdayTd.append("<span id=\"error\"></span>");
				$("#birthdayBox").renderDatebox("birthday");
				$("#birthday").val("");
				//==========================

				$("input[digitsOnly=true]").keypress(function (e)  { 
				  //if the letter is not digit then display error and don't type anything
				  if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57))
				  {
					//display error message
					$("#errmsg").html("Digits Only").show().fadeOut("slow"); 
				    return false;
			      }	
				});
				
				$("form#registration > div > table > tbody > tr > td").attr("valign", "top")
				
				$("#dialog").hide();
			
				var keyword = $("#keyword").val();
				$("span.keyword").html(capitalizeMe(keyword));
				
				
				$("#tr_consent_call").hide();
				$("#tr_start_attend").hide();
				
				$("#edinterestyes").click(function() {
					var age = $("#birthdayBox").getAge();
					//alert(age);
					if(age >= 19) {
						var phoneno = $("#phone").val();
						$("#consent_phoneno").html(phoneno);
						$("#tr_consent_call").show();
					}
				});
				
				$("#edinterestno").click(function() {
					$("#tr_consent_call").hide();
					$("#tr_start_attend").hide();
					$("#consent_callno").click();
				});
				
				$("#consent_callyes").click(function() {
					$("#tr_start_attend").show();
				});
				
				$("#consent_callno").click(function() {
					$("#start_attend").val("");
					$("#tr_start_attend").hide();
				});
				
				
				//CATEGORY
				$("#programcategory").html( $().createSelectbox("progcategory", _main_category, "Category") );
				
				$("#progcategory").change(function() {
					var main_key = $(this).val();
					if(parseInt(main_key) == 0) {
						$("#row_subcategory").hide();
						return;
					}
					
					$("#subcategory").html( $().createSelectbox("subprogcategory", _sub_category[main_key], "Sub-Category") );
					$("#row_subcategory").show();
				});
				
				$("#row_subcategory").hide();
				//CATEGORY
				
				
				$("#firstName").focus();
				//$("#step2").show();
				//alert("start");
			},
			
			presubmit : function() {
				
				var email = $("#email").val();
		   		$("#verifyEmail").val(email);
				$("#email").val("");			
				$("form#registration").find("#step").val(4);
				//$("#submit").attr("disabled",true);
				
				//http://www.jobslocally.org/lander2/JLO-GG.html
				//$("#googleweboptimizer").attr("src", __googleweboptimizer_link);
				$("#dialog").dialog();
				//$().sleep(10);
			},
			
			sleep : function(naptime) {
				 naptime = naptime * 1000;
				         var sleeping = true;
				         var now = new Date();
				         var alarm;
				         var startingMSeconds = now.getTime();
				         //alert("starting nap at timestamp: " + startingMSeconds + "\nWill sleep for: " + naptime + " ms");
				         while(sleeping){
				             alarm = new Date();
				             alarmMSeconds = alarm.getTime();
				             if(alarmMSeconds - startingMSeconds > naptime){ sleeping = false; }
				        }      
			},
			
			forceSubmit : function() {
				
				//alert("submitted!");
				$().presubmit();				
				$("#submit").click();
				$("#submit").attr("disabled",true);				
			},
			
			createSelectbox : function(name, options, recordName) {
				
				var result = "<select id=\"" + name + "\" name=\"" + name + "\" > ";
				var x=0;
				result += "<option value=\"\" >Please select a " + recordName + "</option>";
				for ( var i in options )
				{
				    result += "<option value=\"" + i + "\" >" +  options[i] + "</option>";
				}
				result += "</select>";
				
				return result;
			},
			
			addValidation : function(x) {
				
				var stepId = "#step" + x;
				
				$(stepId).find("input[type!=button]").each(function(){
					$(this).attr("validateStep" + x, "true");
				});
				
				$(stepId).find("select").each(function(){
					$(this).attr("validateStep" + x, "true");
				});
				
				/*
				
				
				var setId = function() {
					var name = $(this).attr("name");
					var id = $(this).attr("id");
					
					if(id)
						return;
					
					var val = $(this).val();
					
					var value = val.toLowerCase();
					value = value.replace(/[ ][-][ ]/gi,"to");
					value = value.replace(/[-]/gi,"to");
					value = value.replace(/[+]/gi,"plus");
					value = value.replace(/[ ]/gi,"");
					value = value.replace("'","");
					
					var newId = name + "_" + value;
					$(this).attr("id", newId);
				};
				
				$(stepId).find("input[type=radio]").each(setId);
				$(stepId).find("input[type=checkbox]").each(setId);
				
				//set validation for radio.
				$.gbRadioNames = new Array();
				
				$(stepId).find("input[type=radio]").each(function() {
					var name = $(this).attr("name");
					var id = $(this).attr("id");
					$.gbRadioNames[name] = name;
				});
				
				var names = $.gbRadioNames;
				for ( var name in names ) {
					//alert(name); 
				    $("input:radio[name=" + name+ "]:eq(0)").attr("validateStep" + x, "true");
				} 
				*/
			}
	});
	
})(jQuery);

var jQ = jQuery.noConflict();

jQ(document).ready(function() {
	
	jQ().initRendering();
	
});
