function checkEmail(emailAddress){
//	$.get('http://www.cityofpalmdale.org/SpamCheck.asmx/IsValidEmail', {inputEmail: val}, function(data){
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}

function clickBanner(id){
	$.get('redirect.php',  { bid: id, redirUrl: "none" });
}
	
$(function(){
	$('#registerNewsletter').submit(function(){
		return false;
		}
	);

	$(".registerNewsletter").click(function(event) {
				event.preventDefault();
				$("#dialog").dialog({
					resizable:false,
					autoOpen: false,
					width: 400,
					modal: true,
					buttons : {
						"Inscriviti": function() {
							$("#dialog > i").remove();
							if(checkEmail($('#nl_email').val())){
								$.post('register.php',  { action: 'newsletter', email: $('#nl_email').val()}, function(data){
									$(data).find('error').each(function(){
										 $("<div id=\"dialog-message\" title=\"Registrazione newsletter\"><p>"+$(this).text()+"</p></div>").dialog(
										 {
												modal: true,
												buttons: {
													Ok: function() {
														$( this ).dialog( "close" );
													}
												}
											}
										 );								
									});
									
								});
								$(this).dialog("close");
							}
							else{
								$(this).prepend('<i class="fRed">L\'email inserito è vuoto o non è valido.</i>');
							}
						},
						"Annulla" : function() {
							$(this).dialog("close");
						}
					}
				}).dialog("open");
			});		 	
			
			
$('form').submit(function(){
		$('.error, .fRed, .ui-state-error').removeClass('ui-state-error error fRed');
		
		var errors = '<ul class="alignLeft"><h4>le seguente campi sono necessari:</h4>';
		var hasError = false;
		
		$(this).find(':input').each(function(){
			if(!$(this).hasClass('optional')){
				if($(this).val() == '' && $(this).siblings('label').text() != ''){
						$(this).addClass('error ui-state-error');
						if($(this).attr('id') == 'recaptcha_response_field'){
							errors += '<li>Recaptcha è obbligatorio</li>';
						}else{
							errors += '<li>'+$(this).siblings('label:first').text().replace(':', '')+' è obbligatorio</li>';
						}
						hasError = true;
				}
				else{
					if($(this).attr('name') == 'email' && !checkEmail($(this).val())){
						$(this).addClass('error ui-state-error');
						errors += '<li>'+$(this).siblings('label:first').text().replace(':', '')+' è formattato sbagliato</li>';
						hasError = true;
					}
					if($(this).hasClass('password') && $(this).val().length < 6){
						errors += '<li>La lunghezza della password deve essere tra 6-10 caratteri.</li>';
						hasError = true;
					}					
					if($(this).attr('name') == 'repassword'){
						if($(this).val() != $('#password').val()){
							errors += '<li>Le due password non coincidono</li>';
							hasError = true;
						}
					}					
				}
			}
		});
		
		$(this).find(':checkbox').each(function(){
			if(!$(this).hasClass('optional')){
				if(!$(this).is(":checked") && $(this).siblings('label').text() != ''){
						$(this).siblings('label').addClass('fRed ui-state-error');
						errors += '<li>'+$(this).siblings('label:first').text().replace(':', '')+' è obbligatorio</li>';
						hasError = true;
				}
			}
		});
	
		var radios = $(this).find(':radio').get();
		radiosArr = new Array();
		for(i = 0; i < radios.length; i++){	radiosArr[i] = radios[i]['name']; }
		radiosUnique = $.unique(radiosArr);

		$(radiosUnique).each(function(){
			if(!$("input[name='"+this+"']").is(":checked")){
				$("input[name='"+this+"']").addClass('error');		
				errors += '<li>'+$("input[name='"+this+"']").siblings('label:first').text().replace(':', '')+' è obbligatorio</li>';
				hasError = true;
			}
		});		

		if(hasError){
			$(this).append('<div id="formErrors" title="Errore:">'+errors+'</ul></div>');
			$( "#formErrors:ui-dialog" ).dialog( "destroy" );	
			$( "#formErrors" ).dialog({
				width: 400,
				modal: true,
				buttons: {
					Ok: function() {
						$( this ).dialog( "close" );
					}
				}
			});
			return false;
		}
		return true;
	});			
});

$(function(){
		$('#modificaBtn').click(function(){
			$('#modificaBtn:visible').toggleClass('hidden');
			$('#modificaBtn2:hidden').toggleClass('hidden');
			$('form[id^="modUtente"] input[type="text"], form[id^="modUtente"] input[type="radio"], form[id^="modUtente"] input[type="checkbox"], form[id^="modUtente"] textarea, form[id^="modUtente"] select').removeAttr('disabled');
		});
		
		$('#annullaBtn').click(function(){
			$('#modificaBtn:hidden').toggleClass('hidden');
			$('#modificaBtn2:visible').toggleClass('hidden');	
			$('form[id^="modUtente"] input[type="text"], form[id^="modUtente"] input[type="radio"], form[id^="modUtente"] input[type="checkbox"], form[id^="modUtente"] textarea, form[id^="modUtente"] select').attr('disabled', 'true');
		});
		
		var oldpassword= $( "#oldpassword" ),
			newpassword= $( "#newpassword" ),
			renewpassword= $( "#renewpassword" ),
			allFields = $( [] ).add( oldpassword ).add( newpassword ).add( renewpassword ),
			tips = $( ".validateTips" );

		function updateTips( t ) {
			tips
				.text( t )
				.addClass( "ui-state-highlight" );
			setTimeout(function() {
				tips.removeClass( "ui-state-highlight", 1500 );
			}, 500 );
		}
		
	  function checkOldPass(userID, oldPassword){
			var result = 0;
			$.ajax({
				type: "POST",
				url: "handleRequest.php",
				data: {who: "users", action: "chkPass", record: $('#username').val(), oldPass: oldPassword},
				async: false,
	  	  success: function(data) {
          result = $(data).find("result").text();
        }
			});
			alert(result);
			return parseInt(result);
		}
		
    function checkValidChars( o, n ){
      var illegalChars = /[\W_]/;
      if (illegalChars.test(o.val())) {
				o.addClass( "ui-state-error" );
				updateTips( "Il campo '"+ n +"' deve essere alphanumerico." );      
        return false;
      }
      return true;
		}
        
		function checkLength( o, n, min, max ) {
			if ( o.val().length > max || o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( "Lunghezza del campo " + n + " deve essere tra " +
					min + " e " + max + "." );
				return false;
			} else {
				return true;
			}
		}
	
	$( "#password-form" ).dialog({
			autoOpen: false,
			width: 360,
			modal: true,
			buttons: {
				"Cambiare Password": function() {
					var bValid = true;
					allFields.removeClass( "ui-state-error" );				
					bValid = bValid && checkLength( oldpassword, "Nuovo password", 6, 16 );
					bValid = bValid && checkLength( renewpassword, "Inserire di nuovo il password", 6, 16 );
					if($("#renewpassword").val() != $("#newpassword").val()){
						updateTips("Le due Password non sono uguali");
						bValid = false;
					}
					bValid = bValid && checkLength( newpassword, "Nuovo password", 6, 16 );
          bValid = bValid && checkValidChars( newpassword, "Nuovo password" );
					if ( bValid && oldpassword.val().length > 5){
						if(checkOldPass('', oldpassword.val()) != 1){
							updateTips("Il vecchio password inserito è sbagliato");
							return;
						}
					}
					if ( bValid ) {
						$.ajax({
							type: "POST",
							url: "handleRequest.php",
							data: {who: "users", action: "changePass", record: $('#username').val(), oldPass: oldpassword.val(), newPass: newpassword.val(), username: $(this).find('input[name="username"]').val()},
							success: function(data) {
								
								if($(data).find("result").text()=='1'){
									$("#dialog").html("La tua password è stata cambiato con successo.").dialog({ height: 120, title: "Successo." , modal: true,buttons: {
									Ok: function() {$( this ).dialog( "close" );}}});
								}else{
									$("#dialog").html("La password non è stata cambiata. Può darsi che la nuova password e uguale al vecchio. Si prega Riprovare.").dialog({ height: 120, width: 400, title: "Successo." , modal: true,buttons: {
									Ok: function() {$( this ).dialog( "close" );}}});
                }
							}
						});
						$( this ).dialog( "close" );
					}
				
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			},
			close: function() {
				allFields.val( "" ).removeClass( "ui-state-error" );
			}
		}).bind("keypress", function(e) {
             if (e.keyCode == 13) {
                 return false;
            }
     });

		$( "#Cambiare_Password" )
			.button()
			.click(function() {
					allFields.val( "" ).removeClass( "ui-state-error" );
				$( "#password-form" ).dialog( "open" );
		});
	});
	
var RecaptchaOptions = {
	custom_translations : {
		instructions_visual : "Scrivi le due parole:",
		instructions_audio : "Trascrivi ci\u00f2 che senti:",
		play_again : "Riascolta la traccia audio",
		cant_hear_this : "Scarica la traccia in formato MP3",
		visual_challenge : "Modalit\u00e0 visiva",
		audio_challenge : "Modalit\u00e0 auditiva",
		refresh_btn : "Chiedi due nuove parole",
		help_btn : "Aiuto",
		incorrect_try_again : "Scorretto. Riprova.",
	},
	lang : 'it', // Unavailable while writing this code (just for audio challenge)
	theme : 'white' // Make sure there is no trailing \',\' at the end of the RecaptchaOptions dictionary
};

