// JavaScript Document
function init_registryFormValidation(){
	if(!$("#registry-form,#code-form").length){
		return;	
	}
	
	$("#submit-btn").click(validateForm);
	$("#submit-all-btn").click(validateForm);
	
// EDIT: added missing }
}	


	function validateForm(){
		var valid = true;
		//check all texfields
		$(this).parent().find("input:text.req").each(function(i){
									  
			if($(this).val()== ""){
				$(this).addClass("invalid");
				valid = false;
			}
			else{
				if($(this).hasClass("invalid")){
					$(this).removeClass("invalid");
				}
			}
			
			if ($(this).hasClass("email") && $(this).val() !=""){
				if(!is_valid_email($(this).val())){
					$(this).addClass("invalid");
					valid = false;
				}
			}
		});
		
		//check all select fields
		$(this).parent().find("select.req").each(function(i){
									  
			if($(this).val()== "0"){
				$(this).addClass("invalid");
				valid = false;
			}
			else{
				if($(this).hasClass("invalid")){
					$(this).removeClass("invalid");	
				}
			}
		});
		
		//check all textareas fields
		$(this).parent().find("textarea.req").each(function(i){
									  
			if($(this).val()== ""){
				$(this).addClass("invalid");
				valid = false;
			}
			else{
				if($(this).hasClass("invalid")){
					$(this).removeClass("invalid");
				}
			}
		});
		
		if(valid == true){
			if($(this).parent().attr("id") == "code-form"){
				if($("#registry-form").css("display") == "block"){
					$("#registry-form").css("display", "none");
				}
				$("#message1").html("Checking Couple Code. Please wait...");
				check_code();
				
			}
			else{
				$("#coupleCode").val($("#couplecode").val());
				$(this).parent().find("form").submit();
			}
			
		}
		
		return false;
	}
}

$(document).ready(function(){
	init_registryFormValidation();				   
});

//passes value of email field
function is_valid_email(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if(reg.test(email) == false) {
      return false;
   }
   else{
	   return true;
   }
}

function check_code(){
	var code = $("#couplecode").val();
	
	$.post("check_code.php", { code: code},
   			function(returnData){
     			if(returnData.indexOf('1')>=0){
					$("#message1").html("");
					
					//colapse top part
					$("#top-part").fadeOut(500,function(){
						var coupleNote = returnData.split("|");
						$('<img />').attr('src', "images/couples/"+coupleNote[4])
    								.load(function(){
										$("#couple-note #header").html(coupleNote[1]);
										$("#couple-note #body").html('"'+coupleNote[2]+'"');
										$("#couple-note #registry-footer").html(coupleNote[3]);
										$("#photo").css("background","url(images/couples/"+coupleNote[4]+") no-repeat center center");
										$("#photo img").fadeOut(1000,function(){
												$("#registry-form").fadeIn();					  
											});				
									});
					});
						
				}
				else{
					$("#message1").html(returnData);
				}
   			});	
}
