/*

Copyright Loïc Dreux <loic.dreux@gmail.com>

Ce logiciel est basé sur wp-contact-form-7 de Takayuki Miyoshi 
email: takayukister at gmail.com
url: http://ideasilo.wordpress.com/

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/


/*
 * Chargement de la carte et chargement du formulaire
 */
function sunelioDevisLoad() {
	// Chargement de la carte
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(50.641623, 3.048019), 8);
		map.setMapType(G_SATELLITE_MAP);
		map.addControl(new GLargeMapControl());
		//map.enableScrollWheelZoom();
		map.enableContinuousZoom();
		map.addControl(new GMapTypeControl());
	}
	
	//jQuery('form').submit(function() { alert('bak'); });
	jQuery('form').submit(function() { return sunelioDevisSubmit(); }); 
}

/*
 * Vérification du formulaire
 */
function sunelioDevisSubmit() {
	var res = true;
	
	// Vérification de l'adresse
	if (jQuery('input#adresse_valide').attr('value') != jQuery('input#adresse').attr('value')) {
		sunelioLocate();
		return false;
	} else if (! sunelioValidateAdresse()) {
		res = false;
	}
	if (! sunelioValidateSituationfamiliale()) {
		res = false;
	}
	if (! sunelioValidateCiv()) {
		res = false;
	}
	if (! sunelioValidateNom()) {
		res = false;
	}
	if (! sunelioValidatePrenom()) {
		res = false;
	}
	if (! sunelioValidateTelephone()) {
		res = false;
	}
	if (! sunelioValidateEmail()) {
		res = false;
	}
	if (! sunelioValidateCommentaires()) {
		res = false;
	}

	// On retourne le résultat
	//return false;
	return res;
}

/*
 * Remet à Zéro le formulaire
 */
function sunelioDevisReset() {
	sunelioDevisClearResponseOutput();
	
	// Chargement de la carte
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(50.641623, 3.048019), 8);
		map.setMapType(G_SATELLITE_MAP);
	}
}

/*
 * Supprimer les messages d'erreur
 */
function sunelioDevisClearResponseOutput() {
	// On nettoie les erreurs
	jQuery('img.ajax-loader').css({ visibility: 'hidden' });
	jQuery('div#adresse_error').css({ visibility: 'hidden' }).html('');
	jQuery('p#p_adresse_nonreconnu').css({ visibility: 'hidden' });
	jQuery('situationfamiliale_error').css({ visibility: 'hidden' });
}

/*
 * Localisation de l'adresse dans la carte google
 */
function sunelioLocate() {
	// On supprime les erreurs Google Maps
	jQuery('input#pasdevisualisationmaison').removeAttr('checked');
	jQuery('input#adresse_valide').attr('value', jQuery('input#adresse').attr('value'));
	
	// On vérifie la compatilité du navigateur.
	if (GBrowserIsCompatible()) {
		// Récupération de la map, du geocoder et de l'adresse.'
		var map = new GMap2(document.getElementById("map"));
		var geocoder = new GClientGeocoder();
		var address = jQuery('input#adresse').attr('value');
		
		// On recherche l'adresse
		geocoder.getLatLng(address, function (point) {
			jQuery('input#pasdevisualisationmaison').removeAttr('disabled');
			
			// En cas d'erreur
			if (!point) {
				jQuery('input#pasdevisualisationmaison').attr('checked', 'checked');
				jQuery('input#latitude').attr('value', '');
				jQuery('input#longitude').attr('value', '');
			}
			// En cas de succès
			else {
				jQuery('input#latitude').attr('value', point.y);
				jQuery('input#longitude').attr('value', point.x);
				map.setCenter(point, 17, G_HYBRID_MAP);
				var markerOptions = {draggable: true, bouncy: false};
				var marker = new GMarker(point, markerOptions);
				/*GEvent.addListener(marker, "mouseup", function () {
					document.getElementById("coordinates").innerHTML = ("Coordonn\xe9es : " + marker.getLatLng());
				});*/
				GEvent.addListener(marker, "mouseup", function (point) {
					marker.closeInfoWindow();
					//alert(point.x + "-" + point.y);
					jQuery('input#latitude').attr('value', point.y);
					jQuery('input#longitude').attr('value', point.x);
					//alert(jQuery('input#latitude').attr('value') + "-" + jQuery('input#longitude').attr('value'));
				});
				map.addOverlay(marker);
				var options = {
				              	maxWidth : 100
				};
				marker.openInfoWindowHtml("Situez votre habitation<br />en d\xe9pla\xe7ant le curseur", options);
				map.addControl(new GLargeMapControl());
				//map.enableScrollWheelZoom();
				map.enableContinuousZoom();
				map.addControl(new GMapTypeControl());
			}
		});
	}
	return true;
}

/*
 * Vérification de l'adresse
 */
function sunelioValidateAdresse() {
	// On vérifie le champs
	if (jQuery('input#adresse').attr('value') == '') {
		jQuery('#error_adresse').html('Renseigner le champ Adresse');
		return false;
	}
	
	if ((! jQuery('input#latitude').attr('value')) && (! jQuery('input#longitude').attr('value')) && (! jQuery('input#pasdevisualisationmaison').attr('checked'))) {
		jQuery('#error_adresse').html("L'adresse n'est pas valide");
		return false;
	}
	
	return true;
}

/*
 * Vérification de la situation familiale
 */
function sunelioValidateSituationfamiliale() {
	jQuery('#error_situationfamiliale').html('');
	
	// Champ non sélectionné
	if(jQuery(':input[@name="situationfamiliale"]:checked').val() == undefined) {
		jQuery('#error_situationfamiliale').html('Sélectionner une situation familiale');
		return false;
	}
	return true;
}

/*
 * Vérification de la civilité
 */
function sunelioValidateCiv() {
	jQuery('#error_civ').html('');
	
	// Champ non sélectionné
	if(! jQuery(':input[@name="civ"][@checked]').val()) {
		jQuery('#error_civ').html('Sélectionner votre civilité');
		return false;
	}
	return true;
}

/*
 * Vérification du nom.
 * Le champ nom est obligatoire et limité à 50 caractères.
 */
function sunelioValidateNom() {
	jQuery('#error_nom').html('');
	
	// Champ vide
	if (jQuery('input#nom').attr('value') == '') {
		jQuery('#error_nom').html('Renseigner le champ Nom');
		return false;
	}
	// Champ trop long
	var regexp = new RegExp("^.{1,50}$","");
	if (! regexp.test(jQuery('input#nom').attr('value'))) {
		jQuery('#error_nom').html('Le champ nom est limité à 50 caractères');
		return false;
	}
	
	return true;
}

/*
 * Vérification du champ prénom.
 * Le champ nom est obligatoire et limité à 50 caractères.
 */
function sunelioValidatePrenom() {
	jQuery('#error_prenom').html('');
	
	// Champ vide
	if (jQuery('input#prenom').attr('value') == '') {
		jQuery('#error_prenom').html('Renseigner le champ Prénom');
		return false;
	}
	// Champ trop long
	var regexp = new RegExp("^.{1,50}$","");
	if (! regexp.test(jQuery('input#prenom').attr('value'))) {
		jQuery('#error_nom').html('Le champ Prénom est limité à 50 caractères');
		return false;
	}
	
	return true;
}

/*
 * Vérification de l'email
 */
function sunelioValidateTelephone() {
	jQuery('#error_telephone').html('');
	
	// Champ vide
	if (jQuery('input#telephone').attr('value') == '') {
		jQuery('#error_telephone').html('Renseigner le champ Téléphone');
		return false;
	}
	
	// Vérification du format
	var regexp = new RegExp("^(?:\\+[0-9]{2}|0)[0-9](?: ?[0-9]{2}){4}$","");
	if (! regexp.test(jQuery('input#telephone').attr('value'))) {
		jQuery('#error_telephone').html("Le champ Téléphone n'est pas au format XX XX XX XX XX");
		return false;
	}
	
	return true;
}

/*
 * Vérification de l'email
 */
function sunelioValidateEmail() {
	jQuery('#error_email').html('');
	
	// Champ vide
	if (jQuery('input#email').attr('value') == '') {
		jQuery('#error_email').html('Renseigner le champ Email');
		return false;
	}
	
	// Vérification du format
	var regexp = new RegExp("^[\\w\\.\\-\\_]+@[\\w\\.\\-\\_]+\\.\\w{2,3}$","");
	if (! regexp.test(jQuery('input#email').attr('value'))) {
		jQuery('#error_email').html("Le champ Email n'est pas valide");
		return false;
	}
	
	return true;
}

/*
 * Vérification du champ commentaires
 */
function sunelioValidateCommentaires() {
	jQuery('#error_commentaires').html('');
	
	// Champ trop long
	var regexp = new RegExp("^.{0,255}$","");
	if (! regexp.test(jQuery('input#commentaires').attr('value'))) {
		jQuery('#error_commentaires').html('Le champ Commenatires est limité à 255 caractères');
		return false;
	}
	
	return true;
}