jQuery(document).ready(function($) {	
	$("#registration").dialog({
			bgiframe: false,
			autoOpen: false,
			resizable: false,
			draggable: false,
			width: 700,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.8
			}
	});

	$("#registerMe").click(function () {		
		var fake_email = $("#fake_email").val();									 
		jQuery("#registration").dialog('open'); 		
		$("input[name='nws_letter_email']").val(fake_email);
		return false;		
	});
	
	$("#ruolo_spec").change(function () {
		$(".ruolo_spec_ateco,.ruolo_spec_altro").hide();
		if($(this).val()=='RSPP'||$(this).val()=='ASPP') $(".ruolo_spec_ateco").show();
		if($(this).val()=='Altro') $(".ruolo_spec_altro").show(); 		
	});
	
	$("input[name=nws_letter_sm[]]").click(function () {
		if($(this).val()=="Industria") $(".sm_industria").toggle();
		if($(this).val()=="Servizi") $(".sm_servizi").toggle();
		if($(this).val()=="Pubblica Amministrazione") $(".sm_pa").toggle();
	});
	//remove validation mark
	$(".required,.email").mousedown(function(){$(this).removeClass("lb_error");});	
	$("#sendForm").click(function () {if(validForm()) $("#nwsletter").submit();});
	$("#closeForm").click(function () {jQuery("#registration").dialog('close');});
}); 


function validForm() {
	var outcome = true;
	var cb_sm = false;
	var msg = new Array();
	var obj = $(":input:visible[name!='']");
	$(".lb_validation").html("");
	$(obj).each(function(i, selected){									 							 
		//if element has class required check for length > 0
		if(($(selected).hasClass('required'))&&($(selected).val().length==0)) {
			$(selected).addClass("lb_error");
			msg[0] = "* Completare tutti i campi obbligatori";
			outcome = false;
		}
		//if element has class mail, control mail validity
		if(($(selected).hasClass('email'))&&!isValidEmail($(selected).val())) {
			$(selected).addClass("lb_error");
			msg[1] = "* Indirizzo email non valido";
			outcome = false;				
		}
		//if at least one nws_letter_sm[] is checked
		if($(selected).attr("name")=="nws_letter_sm[]"&&$(selected).attr("checked")) cb_sm = true;			
	}); 
	
	//if privacy auth was given
	if(!$("#privacy").attr("checked")) {
		msg.push("* Autorizzazione al trattamento dei dati personali necessaria");
		outcome = false;				
	}
		
	if(!cb_sm) {
		msg.push("* Indicare almeno un settore merceologico");
		outcome = false;	
	}
	if(msg.length>0) {
		msg = msg.join("<br />");	
		$(".lb_validation").html(msg);
	}	
	return outcome;
}
/** 
/* Check for valid email address
/* @param strEmail mail to be checked
/* @return true if valid, false if not
*/
function isValidEmail(strEmail){
	var validRegExp = /^[A-Za-z0-9_.-]+@[A-Za-z0-9_.-]+[.][A-Za-z]{2,6}$/;
   	// search email text for regular exp matches
	if (strEmail.search(validRegExp) == -1) 
		return false;	
    else
    	return true; 
}

