$(function() {
	$( ".jbutton" ).button();
	$( "a", "#paginationControl" ).button();
	
	$( "#element_nom" ).tooltip({ bodyHandler: function() { return "Votre nom"; } });
	$( "#element_codepostal" ).tooltip({ bodyHandler: function() { return "Votre code postal"; } });
	$( "#element_email" ).tooltip({ bodyHandler: function() { return "Votre email"; } });
	$( "#element_telephone" ).tooltip({ bodyHandler: function() { return "Votre numéro de téléphone"; } });
	
	$( "#express_envoyer" ).click(function(e) {
		
		var express_nom = $( "#express_nom" ),
		express_codepostal = $( "#express_codepostal" ),
		express_email = $( "#express_email" ),
		express_telephone = $( "#express_telephone" ),
		express_allFields = $( [] )
			.add( express_nom )
			.add( express_email )
			.add( express_telephone ),
		express_tips = $( "#express_validateTips" );
		
		express_allFields.removeClass( "ui-state-error" );
		var bValid = true;
		bValid = bValid && checkLength( express_tips, express_nom, "nom", 3, 100 );
		bValid = bValid && checkLength( express_tips, express_codepostal, "adresse", 5, 200 );
		bValid = bValid && checkLength( express_tips, express_email, "email", 5, 100 );
		bValid = bValid && checkLength( express_tips, express_telephone, "telephone", 10, 15 );
		
		if( bValid ) {
			
			$.ajax({
				type: 'POST',
				url: $( '#express_form_contact' ).attr( 'action' ),
				data: { 
					nom: express_nom.val(),
					codepostal: express_codepostal.val(), 
					email: express_email.val(), 
					telephone: express_telephone.val()  
				}
			});
			
			$( "#express_contact" ).html(
				"<h4>Votre demande a bien été prise en compte</h4><p>L'équipe commerciale Viveo prendra contact avec vous très prochainement</p>"
			);
		}
	});

});

function updateTips( tips, t ) {
	tips
		.text( t )
		.addClass( "ui-state-highlight" );
}

function checkLength( tips, o, n, min, max ) {
	if ( o.val().length > max || o.val().length < min ) {
		// o.addClass( "ui-state-error" );
		updateTips( tips, "Le champ '" + n + "' n'est pas valide." );
		return false;
	} else {
		return true;
	}
}

function checkRegexp( tips, o, regexp, n ) {
	if ( !( regexp.test( o.val() ) ) ) {
		o.addClass( "ui-state-error" );
		updateTips( tips, n );
		return false;
	} else {
		return true;
	}
}
