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();
		
				//Initialize Validation				
				var container = $('div.errorContainer');
				
				container.hide();
				
				$.validator.addMethod("zipUS", function(value, element, param) {
					//var json = $().getZipData(value);
					
					if(value.length != 5) {
						return false;
					}
					
					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("searchType", function(value, element, param) {
					//var json = $().getZipData(value);
					
					if(value.length == 5 && parseInt(value) > 0 ) {
						var zipData = $().getZipData(value);
						
						if(zipData.city.length == 0)
							return false;
						
						$("#city").val(zipData.city);
						$("#city").attr("readonly","readonly");
						$("#state").val(zipData.state);
						$("#state").attr("readonly","readonly");
					} else if(value.length == 2) {
						$("#state").val(value.toUpperCase());
					} 
					
					//check if state exists
					var state = $("#state").val();
					if(state.length == 0) {
						$("#city").val(value);
					}
						
					if(value.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": 1,
									"maxlength": 15,
									"searchType": true
								},
								
								title: "required",
								firstName: "required",
								lastName: "required",
								email: {
									"required" : true,
									"emailTypo" : true,
									"email" : true
								},
								phone: {
									"required": true,
									"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"
								}
								/*,
								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 a city/state/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 Phone No (between 2 and 10 characters).",
								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."
							},
						    
						    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(3);
								$("#submit").attr("disabled",true); 
								$("#dialog").dialog();
								form.submit();								
							}


				});
				
				$("#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 keyword = $("#userkw").val();
						var data = $().getDataForPost(1);
												
						var action = window.location.toString();
						$.post(action, data, function(data) {
							
							var city = $("#city").val();
							var state = $("#state").val();
							var zip = $("#zip").val();
							
							$("#whereLocation").css("display", "inline");
							if(zip.length == 5) {
								$("#resultLocation").html(city +", " + state);
							} else if(city.length > 0) {
								$("#resultLocation").html(city);
							} else if(state.length > 0) {
								$("#resultLocation").html(state);
							} else {
								$("#whereLocation").css("display", "none");
							}
							
							//alert(data);
							var count = parseInt(data.replace(/OK/gi, ""));
							if(count > 0) {
								$("#indlist").css("display", "inline");
								$("#resultCount").html(count);
							} else {
								$("indlist").css("display", "none");
							}
							//alert(count);
							
						}, "text");
						
						$("#resultKeyword").html(capitalizeMe(keyword));
						
						
						//move fix to firstName
						$("input[fix]").each(function(){
							var value = $(this).val();
							var pairId = $(this).attr("fix");
							var pairObject = $("#" + pairId);
							
							var type = $(this).attr("type");
							if(type == "text") {
								pairObject.val(value);
							} else if(type=="checkbox") {							
								pairObject.attr("checked", $(this).attr("checked"));
							}
						});
						
						var zipString = $("#zip").val();
						if(zipString.length != 5 || parseInt(zipString) ==0 ) {
							$("#zip").val("");
						}
													
						$("#step1").hide();
						$("#step2").fadeIn();
					}
					
				});
				
				$("#step1").find("input[type!=button]").each(function(){
					$(this).attr("validateStep1", "true");
				});
				
				$("#step1").find("select").each(function(){
					$(this).attr("validateStep1", "true");
				});
				
				$("#step2").find("input[type!=button]").each(function(){
					$(this).attr("validateStep2", "true");
				});
				
				$("#step2").find("select").each(function(){
					$(this).attr("validateStep2", "true");
				});
				
				$("#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;
					});
					
					if(canProceed) {
						$("#step2").hide();
						$("#step3").fadeIn();
						
						var data = $().getDataForPost(2);
						
						var action = window.location.toString();
						$.post(action, data, function(data) {
							//alert(data);
							var count = parseInt(data.replace(/OK/gi, ""));
							$("#resultCount").html(count);							
							//alert(count);
						}, "text");
						
						var email = $("#email").val();
						$("#verifyEmail").val(email);
					}					
					
				});
				
				$("#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() {
					
					$("#step3").hide();
					$("#step2").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();
				$("#zipFix").focus();
				
			},
			
			FU_doPostUploadTasks : function() {
				
				var lis = $("#demo-list").find("li");
				var count = lis.length;
				
				if(count > 1) {
					
					for(var x = 0; x < (count-1); x++) {
						var li = $("#demo-list > li:eq(" + x + ")");
						li.remove();
					}
					
				}
				
				var li = $("#demo-list").find("li");
				var fileName = li.find("span.file-title").html();
				
				//alert(fileName);
				
				$("#resumeFilename").val(fileName);
				
			},
			
			getDataForPost : function(step) {
				
				//submit partial..						
				var campaignId = $("#campaignId").val();
				var keyword = $("#userkw").val();
				var zipcode = $("#zipFix").val();
				
				$("#locating1").html(capitalizeMe(keyword));
				$("#locating2").html(capitalizeMe(keyword));
			
				var title = $("#title").val();
				var state = $("#state").val();
				var email = $("#email").val();
				var birthday = $("#birthdayBox").getDateboxValue();
				 
				var distance = $("#distance").val();
				
				var data = {
					campaignId: campaignId,
					keyword: keyword,
					step:step,
					state: state,
					title: title,
					birthday: birthday,
					zipFix: zipcode
				}
				
				$("input[validateStep" + step + "]").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 = email;
				data.email = "";
				return data;
			}
	});
	
})(jQuery);

var jQ = jQuery.noConflict();

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