var errorDiv = "<div class=\"errorMsg\"></div>";

jQuery(function() {
	$ = jQuery.noConflict();
	 $("#page input[type='submit']").click(function() {
		   return validateForm();
		});
		
		$("#page input[type='text']").focus(function() {
		   if ($(this).attr("focused") != "true"){ // delete the content of field just one's (on first focus)
		   	$(this).val("");
		   	$(this).attr("focused","true");
		   }
		});
		
		$captionText = $(".wp-caption-text","#subbox_content_left");
		addLinkTitle($captionText);		
});

validateForm = function() {
	$(".errorMsg").remove();
	switch ($("html").attr("lang")){
		case "de-DE":
		errPrefix = "DE";
		break;
		default:
		errPrefix = "EN";
	}
	submitStatus = true;
	var $formElementsArr = $("form input, form textarea, form select");
	$formElementsArr.each( function() {
		var curElm = $(this);
		
		if (curElm.hasClass("required").toString() == "true") {	
			if (curElm.attr("id") == "email") {
	  		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
				if(reg.test($(curElm).val()) == false) {
					curElm.focus();
		  		showErrorMsg(curElm, String(errPrefix+3));
		  		submitStatus = false;
				}
	  	}
	  	
	  	if (curElm.val() == "") {
  			curElm.focus();
  			showErrorMsg(curElm, String(errPrefix+1));
  			submitStatus = false;
			}
	  }
	})
	
	if (submitStatus == true) {
		
		var email = $("input#email").val();
		var dataString = '&email=' + email;
		var conf = "<div id='formConfirm'><span>Please wait...</span><img id='checkmark' src='wp-content/themes/ionate/img/ajax-loader.gif' /></div>";
  	$(conf).insertAfter("input[type='submit']");
  	$("#formConfirm").hide();
  	$("#formConfirm").fadeIn("fast");
		
  $.ajax({
    type: "POST",
    url: "wp-content/themes/ionate/scripts/bin/process.php",
    data: dataString,
    success: function() {
    	confirmation = "<h3>Newsletter Form Submitted!</h3><span>We will be in touch soon.</span><img id='checkmark' src='wp-content/themes/ionate/img/check.png' />";
      $("#formConfirm").html(confirmation); 
      $("#formConfirm").fadeTo(5000, 1).fadeOut("slow", function(){$("#formConfirm").remove();});
    }
   });	
  } 
	return false;
}

showErrorMsg = function(field, errorId) {
	errorDiv = $(errorDiv).html(getErrorMsg(errorId))
	$(errorDiv).insertAfter(field);
	$(".errorMsg").fadeIn("slow");
}

getErrorMsg = function(errorId) {
	switch (errorId) {
	
	case "EN1":
		retVal = "Please fill out this field!" 	
		break;
	case "EN3":
		retVal = "Please enter a correct E-Mailaddress!" 	
		break;
	case "DE1":
		retVal = "Bitte f&uuml;lle dieses Feld aus!" 	
	break;
	case "DE3":
		retVal = "Bitte gib eine korrekte E-Mailadresse ein!" 	
		break;
	default:
		retVal = "Sorry, Deine angaben konnten nicht verarbeitet werden.<br/>Sorry, Your indicated cannot not be processed."	
	}
	
	return retVal;
}

addLinkTitle = function($ct) {
	jQuery.each( $ct, function(i){
		$(this).prev().attr("title", $(this).text());
		//console.log($(this).text());
	});
}

