/************************************************************************************************************/
/**** Contient toute sles fonction javascript pour le site **************************************************/
/**** Liste des fonctions (par ordre alphab�tique) :
/****	- checkCaptcha(val)
/****	- checkEmail(id)
/****	- checkTelephone(id)
/****	- checkValue(o,msg,show_acceptation)
/****	- gestionAutocompletionFindByCP(fieldInsee, fieldCP, fieldVille, divAuto)
/****	- gestionAutocompletionSelectVille(fieldInsee, fieldCp, fieldVille, divAuto, insee, cp, ville)
/****   - sendForgetPassWord(fieldId)
/****   - 
/****   - validationFormulaireContact()
/****   - validationFormulaireInscription()
/************************************************************************************************************/
var site_url ='http://www.oubouger.fr/_oubouger';
//var site_url ='http://localhost:8888/oubouger';

function checkCaptcha(val)
{
    if($('#captcha').val()=='' )
        {
            $("#errorMsg").html('Le champ Captcha est vide');
			
			$("#errorMsg").show();
            return false;
        }
    else
    {
        var html=$.ajax({
            type: "POST",
            url: site_url+"/kernel/modules/captcha/checkCaptcha.php",
            data: "code="+$('#captcha').val(),
            async: false
        }).responseText; //End Ajax
        if(!eval(html)) 
        {
        	$("#errorMsg").html('Le code de s&eacute;curit&eacute; est incorrect')
			$("#errorMsg").show();
        }
        return eval(html);
    }
}
function checkEmail(id, notCheckExist)
{
	notCheckExist = notCheckExist ? notCheckExist : false;
	var reg = new RegExp("^([a-zA-Z0-9_-])+([.]?[a-zA-Z0-9_-]{1,})*@([a-zA-Z0-9-_]{2,}[.])+[a-zA-Z]{2,4}$");
	if( $('#'+id).val() == '' )
	{
		$('#' + id + '_img').html('<img src="_oubouger/static/images/form_exclamation.gif" border="0" />');
		$('#' + id).addClass('required');
        $("#errorMsg").html('Le champ Email est vide');
		$("#errorMsg").show();
		return false;
	}
	else if( !reg.test( $('#'+id).val() ) ) 
	{
		$('#' + id + '_img').html('<img src="_oubouger/static/images/form_exclamation.gif" border="0" />');
		$('#' + id).addClass('required');
        $("#errorMsg").html('Votre Email n\'est pas au bon format');
		$("#errorMsg").show();
		return false;
	} else { // email correct
		var html=$.ajax({
            type: "POST",
            url: site_url+"/kernel/ajax/checkEmail.php",
            data: "email="+$('#'+id).val(),
            async: false
        }).responseText; //End Ajax
        if(!eval(html) && !notCheckExist) 
        {
        	$('#' + id).addClass('required');
        	$("#errorMsg").html('Cet email existe d&eacute;j&agrave; parmi nos membres');
			$("#errorMsg").show();
			return false;
        }
		else
		{
			$('#' + id + '_img').html('<img src="_oubouger/static/images/form_acceptation.gif" border="0" />');
			$('#' + id).removeClass("required");
			$("#errorMsg").html('');
			$("#errorMsg").hide();
			return true;
		}
	}
}
function checkLogin(id)
{
	if( $('#'+id).val() == '' )
	{
		$('#' + id + '_img').html('<img src="_oubouger/static/images/form_exclamation.gif" border="0" />');
		$('#' + id).addClass('required');
        $("#errorMsg").html('Le champ Login est vide');
		$("#errorMsg").show();
		return false;
	}
	var html = $.ajax({
		type: "POST",
		url: site_url+"/kernel/ajax/checkLogin.php",
		data: "login="+$('#'+id).val(),
		async: false
	}).responseText; //End Ajax
	if(!eval(html))
	{
		$('#' + id).addClass('required');
		$("#errorMsg").html('Ce login est d&eacute;j&agrave; utilis&eacute;');
		$("#errorMsg").show();
		return false;
	}
	else
	{
		$('#' + id + '_img').html('<img src="_oubouger/static/images/form_acceptation.gif" border="0" />');
		$('#' + id).removeClass("required");
		$("#errorMsg").html('');
		$("#errorMsg").hide();
		return true;
	}
}
function checkTelephone(id) 
{
	var reg = new RegExp('^([0-9 -.]){10,14}$');
	if( $('#'+id).val() == '' )
	{
		$('#' + id + '_img').html('<img src="_oubouger/static/images/form_exclamation.gif" border="0" />');
		$('#' + id).addClass('required');
        $("#errorMsg").html('Le champ T&eacute;l&eacute;phone est vide');
		$("#errorMsg").show();
		return false;
	}
	else if( !reg.test($('#'+id).val()) )
	{
		$('#' + id + '_img').html('<img src="_oubouger/static/images/form_exclamation.gif" border="0" />');
		$('#' + id).addClass('required');
        $("#errorMsg").html('Votre T&eacute;l&eacute;phone n\'est pas au bon format');
		$("#errorMsg").show();
		return false;
	}
	
	$('#' + id + '_img').html('<img src="_oubouger/static/images/form_acceptation.gif" border="0" />');
	$('#' + id).removeClass("required");
	$("#errorMsg").html('');
	$("#errorMsg").hide();
	return true;
}
/** Méthode permettant de controler la valeur saisie d'une zone d'un formulaire */
function checkValue(o,msg, show_acceptation)
{
	value = $('#'+o).val();
    if( value == '')
    {
		$('#' + o + '_img').html('<img src="_oubouger/static/images/form_exclamation.gif" border="0" />');
		$('#' + o).addClass('required');
        $("#errorMsg").html(msg);
		$("#errorMsg").show();
		return false;
	}
	
	if(show_acceptation)
	{
		$('#' + o + '_img').html('<img src="_oubouger/static/images/form_acceptation.gif" border="0" />');
	}
	$('#' + o).removeClass("required");
	$("#errorMsg").html('');
	$("#errorMsg").hide();
	return true;
}
/** Verif CP + Ville */
function checkCPValue(o,msg, show_acceptation)
{
	value = $('#'+o).val();
    if( value == '')
    {
		$('#' + o + '_img').html('<img src="_oubouger/static/images/form_exclamation.gif" border="0" />');
		$('#' + o).addClass('required');
        $("#errorMsg").html(msg);
		$("#errorMsg").show();
		return false;
	}
	if(show_acceptation)
	{
		$('#' + o + '_img').html('<img src="_oubouger/static/images/form_acceptation.gif" border="0" />');
	}
	$('#' + o).removeClass("required");
	$("#errorMsg").html('');
	$("#errorMsg").hide();
	return true;
}
/** Méthode permettant la gestion de l'autocomplétion pour les codes postaux */
var doAction = true;
function gestionAutocompletionFindByCP(fieldId, fieldCP, fieldVille, divAuto)
{
	$('#'+fieldCP).bind('keyup blur', function(event){
		if (event.type == 'keyup' || (doAction == true && event.type == 'blur')){
			var text = $('#'+fieldCP).val();
			if(text.length>=3) {
				$.ajax({
					type: "GET",
					url: site_url+"/kernel/ajax/searchVille.php",
					data: "fieldId="+fieldId+"&fieldCp="+fieldCP+"&fieldVille="+fieldVille+"&divAuto="+divAuto+"&cp="+text,
					success: function( data ) {
						$('#'+divAuto).html(data);
						$('#'+divAuto).show();
						doAction = false;
					}
				});
			}
		}
	});
}
/** Méthode permettant la gestion du retour de l'autocomplétion pour les codes postaux */
function gestionAutocompletionSelectVille(fieldId, fieldCp, fieldVille, divAuto, id, cp, ville) {
    	$('#'+fieldId).val(id);
    	$('#'+fieldCp).val(cp);
    	$('#'+fieldVille).html('<input type="hidden" name="'+fieldVille+'" id="ville_name" value="'+ville+'"/>'+ville);
    	$('#'+divAuto).html('');
    	$('#'+divAuto).hide();
}
/** Méthode permettant l'envoi du mot de passe qui a été oublié  **/
function sendForgetPassWord(fieldId)
{
    var email=$('#'+fieldId).val();
    if(email == '')
        $('#errorMsg').html('Email vide !');
    //else if(!isValidEmailAddress(email))
    //        writeError("Email invalide !");
    else
    {
        $('#errorMsg').html('');
        $.ajax({
			type: "GET",
            url: site_url+"/kernel/ajax/sendForgetPassword.php",
            data: "email="+email,
            success: function(msg){
				if(msg == 'notFound')
				{
					$('#errorMsg').html('Aucun compte enregistr&eacute; avec cette adresse email.');
					$('#okMsg').hide();
					$('#errorMsg').show();
                }
				else
                {
                    $('#okMsg').html(msg);
                    $('#errorMsg').hide();
                    $('#okMsg').show();
                }
			}
        }); //End Ajax
    }
}

/************************************************************************************************************/
/********* Validation de formulaire **************/
/************************************************************************************************************/
function validationFormulaireContact()
{
	var libelleErreur = '';

	if( checkCaptcha($("#captcha").val()) )
	{
		if( !checkValue('nom','',false) ) libelleErreur += '<li>Le champ Nom est vide</li>'; 
		if( !checkValue('prenom','',false) ) libelleErreur += '<li>Le champ Pr&eacute;nom est vide</li>';
		if( !checkEmail('email', true) ) libelleErreur += '<li>Cet email existe d&eacute;j&agrave; parmi nos membres</li>';
		if( !checkValue('tel','',false) ) libelleErreur += '<li>Le champ T&eacute;l&eacute;phone est vide</li>';
		if( !checkValue('adresse','',false) ) libelleErreur += '<li>Le champ Adresse est vide</li>';
		if( !checkValue('objet','',false) ) libelleErreur += '<li>Le champ Objet est vide</li>';
	}
	else
	{
		libelleErreur += '<li>Le code de s&eacute;curit&eacute; n\'est pas valide !</li>';
	}
	
	if(libelleErreur != '') 
	{
		$('#errorMsg').html('<ul>'+libelleErreur+'</ul>');
		$('#errorMsg').show();
	}
	return (libelleErreur == '');
}
function validationFormulaireInscription()
{
	var libelleErreur = '';
	
	if( !checkValue('nom','',false) ) libelleErreur += '<li>Le champ Nom est vide</li>'; 
	if( !checkValue('prenom','',false) ) libelleErreur += '<li>Le champ Pr&eacute;nom est vide</li>';
	if( !checkValue('nom_association','',false) ) libelleErreur += '<li>Le champ Nom de l\'association est vide</li>';
	if( !checkEmail('email') ) libelleErreur += '<li>Cet email existe d&eacute;j&agrave; parmi nos membres</li>';
	if( !checkValue('tel','',false) ) libelleErreur += '<li>Le champ T&eacute;l&eacute;phone est vide</li>';
	if( !checkValue('adresse','',false) ) libelleErreur += '<li>Le champ Adresse est vide</li>';
	if( !checkValue('code_postal','',false) ) libelleErreur += '<li>Le champ Code Postal est vide</li>';
	
	if( !checkLogin('login') ) libelleErreur += '<li>Le champ Login est vide</li>';
	if( !checkValue('pwd','',false) ) libelleErreur += '<li>Le champ Mot de passe est vide</li>';
	if(!checkCaptcha($("#captcha").val()));
	if(libelleErreur != '') 
	{
		$('#errorMsg').html('<ul>'+libelleErreur+'</ul>');
		$('#errorMsg').show();
	}
	if ($('#errorMsg').html() != '') return false;
	return (libelleErreur == '');
}
function validationFormulaireEvenement()
{
	var libelleErreur = '';
	
	if(!checkValue('titre', '', false)) libelleErreur += '<li>Le champ Titre est vide</li>';
	if(!checkValue('code_postal', '', false)) libelleErreur += '<li>Le champ Code postal est vide</li>';
	if(!checkValue('ville_name', '', false)) libelleErreur += '<li>Vous devez s&eacute;l&eacute;ctionner une ville</li>';
	if(!checkValue('adresse', '', false)) libelleErreur += '<li>Le champ Adresse est vide</li>';
	if(!checkValue('categorie', '', false)) libelleErreur += '<li>Vous devez s&eacute;lectionner une cat&eacute;gorie</li>';
	if(!checkValue('date_debut', '', false)) libelleErreur += '<li>Vous devez s&eacute;lectionner une date de d&eacute;but</li>';
	if(!checkValue('date_fin', '', false)) libelleErreur += '<li>Vous devez s&eacute;lectionner une date de fin</li>';
	if(!checkValue('description', '', false)) libelleErreur += '<li>Le champ Description est vide</li>';
	if(libelleErreur != '')
	{
		$('#errorMsg').html('<ul>'+libelleErreur+'</ul>');
		$('#errorMsg').show();
	}
	if ($('#errorMsg').html() != '') return false;
	return (libelleErreur == '');
}
/************************************************************************************************************/
/********* Gestion googleMaps ajout/edition événements **************/
/************************************************************************************************************/
function show_map()
{
	if ($('#code_postal').val() != '' && $('#ville_name').val() != '' && $('#adresse').val() != ''){
		initializeGMapEvent(true)
	}
}
function loadMap(show_map, latitude, longitude)
{
	if (show_map == true){
		var latlng = new google.maps.LatLng(latitude, longitude);
		var myOptions = {
			zoom: 14,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		var map = new google.maps.Map(document.getElementById("map_event"), myOptions);			
		var marker = new google.maps.Marker({
			position: latlng, map: map, draggable: true
		});
		var contentString = $('#titre').val() + "<br/>"+ $('#adresse').val()+"<br/>"+
							$('#code_postal').val()+ ' '+ $('#ville_name').val();
		infowindow = new google.maps.InfoWindow({
			content: contentString
		});
		google.maps.event.addListener(marker, 'dragend', function(){
			var newLatLng = marker.getPosition();
			$('#lat').val(newLatLng.lat());
			$('#lng').val(newLatLng.lng());
		});
		google.maps.event.addListener(marker, 'click', function() {
			infowindow.open(map,marker);
		});
	}
}
function initializeGMapEvent(show_map)
{
	var geocoder = new google.maps.Geocoder();
	var adresse = $('#adresse').val() + ', ' + $('#code_postal').val() + ' ' + $('#ville_name').val();
	if ($('#lat').val() == '' && $('#lng').val() == ''){
		geocoder.geocode({'address': adresse}, function(results, status){
			if (status == google.maps.GeocoderStatus.OK){
				$('#lat').val(results[0].geometry.location.lat());
				$('#lng').val(results[0].geometry.location.lng());
				loadMap(show_map, results[0].geometry.location.lat(), results[0].geometry.location.lng())
			}
		});
	}
}
/************************************************************************************************************/
/********* Document - Ready **************/
/************************************************************************************************************/
$(document).ready(function(){
	if (0 != $("#map_canvas").size()) {
		initializeGoogleMapV3();
	}
	
	$('#tagsphere').tagSphere({	height: 200, width: 180,  slower: 0.85,	radius: 60,	timer: 50 });
});
