/**
 * Fichier : espace.js
 * Description : fonctions JS spécifiques à mon espace
 * Auteur : Hamza Iqbal - hiqbal[at]actualys.com
 * Copyright: Actualys
 ******************************************/

/**
 * Initialisation
 ******************************************/
$(document).ready( function()
{
        if($('#presentation_avantages').size()) presentationAvantagesSlider();

	if($('#inscription_fiche_perso').size())
	{
		carrouselListeAvatars();
		switchAvatar();
                displayPhpError();
	}
	
	if($('#inscription_membre').size()) {
            verifFormInscription();
            dateInputSwitch('user_registration_birthday');
        }

	if($('#recap_fiche_perso').size()){
            carrouselListeAvatars();
	    switchAvatar();
            modificationInfosMembre();
        }

	if($('#mon_agenda_simplifie').size()) evenementsAgendaSimplifie();

        if($('#choix_evenement').size()){
            displayPhpError();
            carrouselListeEvenements();
	    switchEvent();
            carrouselListeEcards();
            verifFormEvenement();
            dateInputSwitch('user_event_dt_event');
        }

});

/**
 * Coda Slider présentation des avantages
 ******************************************/
var presentationAvantagesSlider = function()
{
	$('#presentation_avantages_slider').codaSlider(
	{
		autoSlide: true,
		autoSlideInterval: 4000,
		autoSlideStopWhenClicked: true,
		dynamicArrows: false
	});
};

/**
 * Carrousel liste d'avatars
 ******************************************/
var carrouselListeAvatars = function()
{
    $('#liste_avatars').jcarousel({
        vertical: true,
        scroll: 1,
        width: '46px',
        height: '150px'
    });
}

/**
 * Carrousel liste d'avatars
 ******************************************/
var carrouselListeEvenements = function()
{
    $('#liste_events').jcarousel({
            vertical: true,
            scroll: 1,
            width: '46px',
            height: '150px'
    });
}

/**
 * Carrousel liste d'avatars
 ******************************************/
var carrouselListeEcards = function()
{
    $('#liste_ecards').jcarousel({
            vertical: false,
            scroll: 1,
            width: '396px',
            height: '132px'
    });
}

/**
 * Changement d'avatar en AJAX
 ******************************************/
var switchAvatar = function()
{
	var photo_membre = $('#photo_membre img');

        /* Si php retourne une page d'erreur à l'inscription, on récupère l'avatar précédemment sélectionné */
        if($("#user_registration_avatar").val()!=''){
            photo_membre.attr('src',$("#user_registration_avatar").val());
        }
        /**/

	var avatars = $('#liste_avatars li a');

	avatars.click(function()
	{
		var src_img = $(this).find('img').attr('src');
		var id_avatar = $(this).next().attr('value');

		photo_membre.attr('src', src_img.replace('-mini',''));

		return false;
	});
}

/**
 * Changement d'image �v�nement
 ******************************************/
var switchEvent = function()
{
	var events = $('#liste_events li a');
	var photo_evenement = $('#photo_evenement img');

	events.click(function()
	{
		var src_img = $(this).find('img').attr('src');
		var id_event = $(this).next().attr('value');

		photo_evenement.attr('src', src_img.replace('-mini',''));

		return false;
	});
}

/**
 * Vérifie le formulaire d'inscription
 ******************************************/
var verifFormInscription = function()
{
	var form = $("#inscription_membre");

	var champ_num_carte = form.find('#user_registration_card_nr');
	var cont_champ_num_carte = champ_num_carte.parent();

        if($('#champ_num_carte > ul.error_list').size()==0){
            cont_champ_num_carte.hide();
        }

	$('#user_registration_has_card_1').click(function() {cont_champ_num_carte.show();});
	$('#user_registration_has_card_2').click(function() {
            cont_champ_num_carte.hide();
            champ_num_carte.val('');
            $.fn.colorbox({height: "220px", width:"350px", href: 'user/nocardclub'});
        });

        form.find('input.btn').click(function(){
            if($('#user_registration_birthday_day').val()=='jj')
                $('#user_registration_birthday_day').val('');
            if($('#user_registration_birthday_month').val()=='mm')
                $('#user_registration_birthday_month').val('');
            if($('#user_registration_birthday_year').val()=='aaaa')
                $('#user_registration_birthday_year').val('');
        });

    form.validate(
	{
		rules:
		{
			'user_registration[firstname]': "required",
			'user_registration[lastname]': "required",
			'user_registration[username]': "required",
			'user_registration[password]': {
                            required: true,
                            minlength: 6
                        },
                        
			'user_registration[password_confirm]':
			{
                            required: true,
                            equalTo: "#user_registration_password"
			},
			'user_registration[email]':
			{
                            required: true,
                            email: true
			},
			'user_registration[birthday][day]': "required",
			'user_registration[birthday][month]': "required",
			'user_registration[birthday][year]': "required",
			'user_registration[card_nr]':
			{
				required: "#user_registration_has_card_1:checked"
			}
		},

		messages:
		{
			'user_registration[firstname]': "Ton prénom est obligatoire",
			'user_registration[lastname]': "Ton nom est obligatoire",
			'user_registration[username]': "Ton pseuso est obligatoire",
			'user_registration[password]': {
                            required : "Ton mot de passe est obligatoire",
                            minlength: "Ton mot de passe doit faire au moins 6 caractères"
                        },
			'user_registration[password_confirm]':
			{
				required: "La confirmation du mot de passe est obligatoire",
				equalTo: "Vérifie bien tes mots de passe."
			},
			'user_registration[email]':
			{
				required: "Ton adresse e-mail est obligatoire",
				email: "Ton adresse e-mail n'est pas correcte"
			},
			'user_registration[birthday][day]': "Ta date de naissance est obligatoire",
			'user_registration[birthday][month]': "Ta date de naissance est obligatoire",
			'user_registration[birthday][year]': "Ta date de naissance est obligatoire",
			'user_registration[card_nr]':
			{
				required: "Le numéro de carte Carrefour Kid's Club est obligatoire"
			}
		},
                errorPlacement: function(error, element) {
                    error.appendTo( element.next("span") );
                    error.css('display','inline')
                }


		/*submitHandler: function()
		{
			alert("ok");
		}*/
	});
};

/**
 * Affiche/Masque et vérifie le formulaire
 * de modification des données du membre
 ******************************************/
var modificationInfosMembre = function()
{
        $('#user_registration_card_nr, #label_num_carte').hide();
        $('#user_registration_has_card_1').click(function() {$('#user_registration_card_nr, #label_num_carte').show();});
	$('#user_registration_has_card_2').click(function() {$('#user_registration_card_nr, #label_num_carte').hide();});
        
        /* on renseigne le champs password confirm */
        $('#user_registration_password, #user_registration_password_confirm').focus(function(){
            if($(this).val() == '¤|_|-')
                $('#user_registration_password, #user_registration_password_confirm').val('');
        });
        $('#user_registration_password, #user_registration_password_confirm').blur(function(){
            if($('#user_registration_password, #user_registration_password_confirm').val()=='')
                $('#user_registration_password, #user_registration_password_confirm').val('¤|_|-');
        });

	var infos_membre = $('#infos_membre');
            var photo_membre = $('#photo_membre');
	var form_modification = $('#modification_infos_membre');
            var avatar_modification = $('#choix_photo');
	var button_print = $('#print_button');
            form_modification.hide();
            avatar_modification.hide();

	infos_membre.find('.btn_modifier a').click(function()
	{
		infos_membre.hide();
                    photo_membre.hide();
                    button_print.hide();
		form_modification.show();
                    avatar_modification.show();
                                
		return false;
	});

	form_modification.find('.btn_annuler').click(function()
	{
		infos_membre.show();
                photo_membre.show();
                button_print.show();
		form_modification.hide();
                avatar_modification.hide();
		return false;
	});

	form_modification.validate(
	{
		rules:
		{
			'user_registration[firstname]': "required",
			'user_registration[lastname]': "required",
			'user_registration[password]':
                        {
                                required: false
                        },
			'user_registration[password_confirm]':
			{
				required: false,
				equalTo: "#user_registration_password"
			},
			'user_registration[email]':
			{
				required: true,
				email: true
			},
			'user_registration[birthday][day]': "required",
			'user_registration[birthday][month]': "required",
			'user_registration[birthday][year]': "required"
		},

		messages:
		{
			'user_registration[firstname]': "Le prénom est obligatoire",
			'user_registration[lastname]': "Le nom est obligatoire",
			'user_registration[password]': "Le mot de passe est obligatoire",
			'user_registration[password_confirm]':
			{
				required: "La confirmation du mot de passe est obligatoire",
				equalTo: "Les deux mots de passes ne sont pas identiques"
			},
			'user_registration[email]':
			{
				required: "L'adresse e-mail est obligatoire",
				email: "L'adresse e-mail n'est pas correcte"
			},
			'user_registration[birthday][day]': "Le jour est obligatoire",
			'user_registration[birthday][month]': "Le mois est obligatoire",
			'user_registration[birthday][year]': "L'année est obligatoire"
		}

	});
};


/**
 * Personnalisation de la couleur de la
 * fiche membre
 ******************************************/
var personalisationCouleur = function(url_switch_style)
{
	var couleurs = $('#liste_couleurs li a');
	var recap_fiche_perso = $('#recap_fiche_perso');

	couleurs.click(function()
	{ 
                var code_couleur = $(this).attr('id');

		couleurs.removeClass('actif');
		$(this).addClass('actif');

                recap_fiche_perso.removeAttr('class').addClass(code_couleur);

                $('#hidden_div').load(url_switch_style, {'css': code_couleur});

		return false;
	});
};

/**
 * Tableau des évenements de l'agenda
 ******************************************/
var evenementsAgendaSimplifie = function()
{
	var tableau = $('table#liste_evenements');

	tableau.find('tr:last').addClass('dernier');
        tableau.find('a.confirm_delete').colorbox({height:160, width:380});
};

/**
 * Switcher de champs à la saisie d'une date
 * Définir des valeurs par defaut
 ********************************************/
var dateInputSwitch = function(fieldname){
    if($('#'+fieldname+'_day').val()=='')
        $('#'+fieldname+'_day').val('jj');
    if($('#'+fieldname+'_month').val()=='')
        $('#'+fieldname+'_month').val('mm');
    if($('#'+fieldname+'_year').val()=='')
        $('#'+fieldname+'_year').val('aaaa');

   $('#'+fieldname+'_day, #'+fieldname+'_month, #'+fieldname+'_year').focus(function(){
        if($(this).val()=='jj' || $(this).val()=='mm' || $(this).val()=='aaaa'){
            $(this).val('');
        }
   });


   $('#'+fieldname+'_day, #'+fieldname+'_month, #'+fieldname+'_year').blur(function(){
       if($(this).attr('id')==''+fieldname+'_day' && $(this).val()==''){
           $(this).val('jj');
       } else if($(this).attr('id')==''+fieldname+'_month' && $(this).val()==''){
           $(this).val('mm');
       } else if($(this).val()=='') {
           $(this).val('aaaa');
       }
   })

    $('.datetext').keyup(function(){
        var jours_mois = $(this).val();
        if(jours_mois.length==2){
            $(this).next('input').focus();
        }
    })
}


/**
 * Vérifie le formulaire evenement
 ******************************************/
var verifFormEvenement = function()
{
	
    if($('#user_event_dt_event_day').val()=='')
        $('#user_event_dt_event_day').val('jj');
    if($('#user_event_dt_event_month').val()=='')
        $('#user_event_dt_event_month').val('mm');
    if($('#user_event_dt_event_year').val()=='')
        $('#user_event_dt_event_year').val('aaaa');
		
    var form = $("#creation_evenement");

    form.find('div#actions').find('input.btn').click(function(){
        if($('#user_event_dt_event_day').val()=='jj')
            $('#user_event_dt_event_day').val('');
        if($('#user_event_dt_event_month').val()=='mm')
            $('#user_event_dt_event_month').val('');
        if($('#user_event_dt_event_year').val()=='aaaa')
            $('#user_event_dt_event_year').val('');
    });

    form.validate(
	{
		rules:
		{
			'user_event[title]': "required",
			'user_event[location]': "required",
			'user_event[hour]': "required",
			'user_event[dt_event][day]': {
                            required: function(element){
                                if($('#user_event_dt_event_day').val()=='' || $('#user_event_dt_event_day').val()=='jj')
                                    return true;
                                else
                                    return false;
                            }

                        },
			'user_event[dt_event][month]': "required",
			'user_event[dt_event][year]': "required"
			/*'user_event[guests]': {
                            required: function(){
                                    var temp = $('#user_event_guests').val();
                                    var aaa = temp.replace(' ', '');
                                    var tmp_array = aaa.split(',');
                                    for(var i=0;i<tmp_array.length-1;i++){
                                        email: true
                                    }
                                }*/
                        

		},

		messages:
		{
			'user_event[title]': "Le nom de ta fête est obligatoire",
			'user_event[location]': "Le lieu de ta fête est obligatoire",
			'user_event[hour]': "L'heure de ta fête est obligatoire",
			'user_event[dt_event][day]': "La date de ta fête est obligatoire",
			'user_event[dt_event][month]': "La date de ta fête est obligatoire",
			'user_event[dt_event][year]': "La date de ta fête est obligatoire"
			/*'user_event[guests]': "Un email st faux"*/
		},
                errorPlacement: function(error, element) {
                    error.appendTo( element.next("span") );
                }
	});
};

var displayPhpError = function(){
    $('ul.error_list').parent().find('textarea').addClass('error');
    $('ul.error_list').parent().find('input').addClass('error');
}

/**
 * Enregistrmenet de l'avatar � l'inscription
 */
function saveEventPicture(){
    var img = $('#photo_evenement').find('img').attr('src');
    $('#user_event_picture').val(img);
    return true;
}

function saveAvatar(){
    var img = $('#photo_membre').find('img').attr('src');
    $('#user_registration_avatar').val(img);
    return true;
}

/**
 * Vérification avant de valider le formulaire d'édition
 ***/
function checkBeforeUpdate(url_updateAvatar){
    if($('#user_registration_password').val()=='¤|_|-'){
        $('#user_registration_password, #user_registration_password_confirm').val('');
    }
    updateAvatar(url_updateAvatar);
}

/**
 * Mise à jour de l'avatar
 */
function updateAvatar(url_updateAvatar){
    $('#hidden_div').load(url_updateAvatar, {'img': $('#photo_membre').find('img').attr('src')},
        function() {
            return true;
	}
    );
}