/*----------------------------------------------------------------------------*/
// Formulaire d'inscription des participants à une formation
/*----------------------------------------------------------------------------*/
(function($, w, undefined) {

    var changeEvent = $.browser.msie ? 'click' : 'change';

    var idParticipant = false;
    var isParticipantSelected = $('select#ctl00_cphContentBody_ClientType option:selected').val() == '98ad9d56-cc7b-4bb7-82ac-a2852bce49de';

    var isParticipantRole = false;
    // bind events
    $(document).ready(function() {
        $('a.BtnSupprimerFormation').live('click', ConfirmerSuppressionFormation);
        $('div.SuppressionFormation a.Oui').live('click', SuppressionFormation);
        $('div.SuppressionFormation a.Non').live('click', function() { $.colorbox.close(); });

        $('a.BtAjout').live('click', ShowChoixParticipants);
        $('a.BtSuppression').live('click', SupprimerParticipant);

        $('select.ListeParticipants').live(changeEvent, ChoixParticipant);
        $('.AjoutParticipantForm a').live('click', SubmitParticipant);

        $('a.BtEtapeSuivante').live('click', SubmitFullForm);

        $('a.BtnEdit').live('click', EditerPrix);
        $('a.BtnReset').live('click', ReinitPrix);

        if (isParticipantSelected) {
            $('div.Removable').remove();
            $('div.Removable').remove();
        }
        LoadBasket();
    });


    /* +---------------------------------------------------
    | WS
    |   retourne l'url du webservice
    +--------------------------------------------------- */
    function WS() {
        return '/WebServices/BasketManagementService.asmx/' + arguments[0];
    }

    /* +---------------------------------------------------
    | GetLayout
    |   retourne les objets du layout
    +--------------------------------------------------- */
    function GetLayout() {
        var $root = arguments[0].parents('div.Formulaire');
        var $liste = $root.find('div.GroupeChamps');

        return {
            $root: $root,
            $liste: $liste
        };
    }

    /* +---------------------------------------------------
    | $GetTmpl
    |   retourne un clone du template
    +--------------------------------------------------- */
    function $GetTmpl() {
        return $('div#Templates div.' + arguments[0]).clone(true);
    }

    /* +---------------------------------------------------
    | ParticipantAllFilled
    |   faire apparaitre le bouton d'ajout si tous les participants sont choisis
    +--------------------------------------------------- */
    function ParticipantAllFilled($root) {
        var filled = true;

        // faire le tour des select pour vérifier leur valeur
        $root.find('select.ListeParticipants').each(function() {
            if ($(this).val() == 'choisir') {
                filled = false;
                return false;
            }
        });

        // s'ils sont tous sélectionné, on affiche le bouton
        if (filled) {
            $root.find('a.BtAjout').fadeIn('fast');
        }

        return filled;
    }


    /* +---------------------------------------------------
    | ParticipantAlreadyChosen
    |   vérifier si le participant a déjà été sélectionné
    +--------------------------------------------------- */
    function ParticipantAlreadyChosen($root, val) {
        var nb = 0;

        // faire le tour des select pour vérifier leur valeur
        $root.find('select.ListeParticipants').each(function() {
            if ($(this).val() == val) {
                ++nb;
            }
        });

        // s'ils sont tous sélectionné, on affiche le bouton
        if (nb > 1) {
            return true
        }

        return false;
    }

    /* +---------------------------------------------------
    | LoadBasket
    |   affiche les formations
    +--------------------------------------------------- */
    function LoadBasket() {
        $.ajax({
            type: 'GET',
            url: WS('FetchBasket'),
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function(response) {
                if (response != undefined) {
                    // s'il y a des formations
                    if (response.d.Trainings.length) {
                        var $html = $('<div>');
                        $("#ListeVendeurs").children("li.PremierItem").remove();
                        for (var i in response.d.VendorList) {
                            $("#ListeVendeurs").append('<li><a href="#" onclick="retirerVendeur(this); return false;" class="BtRetrait">' + response.d.VendorList[i] + '<span>[x]</span></a></li>');
                        }

                        for (var i in response.d.Trainings) {
                            // créer la formation
                            var data = response.d.Trainings[i];
                            var $formation = $GetTmpl('AjoutFormationComplete').removeClass().addClass('FormationComplete').data('GUID', data.TrainingId);
                            $formation.find('.TitreFormation').html(data.Name);
                            $formation.find('.PrixFormation').children("span.Prix").html(data.SubTotalAmount);
                            $formation.find('.Reservations input').val(data.ReservationAmount);



                            if (response.d.IsAdmin == true) {
                                $formation.find('.PrixFormation').children("input.PrixInitial").val(data.SubTotalAmount.substr(1));
                                $formation.find("input.PrixPropose").val(data.DealPrice.substr(1));
                                if (data.DealPrice != null && data.DealPrice.substr(1) != data.SubTotalAmount.substr(1)) {
                                    $formation.find("span.NouveauPrix").html(data.DealPrice);
                                    $formation.find("span.Prix").addClass("Modifie");
                                }
                            } else {
                                $('#BtnEdit').remove();
                                $('#BtnReset').remove();
                                $('input.PrixPropose').remove();
                            }

                            // ajouter les participants
                            var $liste = $formation.find('div.GroupeChamps');
                            for (var j in data.ParticipantIdList) {

                                // load template
                                var participantID = data.ParticipantIdList[j];
                                var $participant = $GetTmpl('AjoutParticipant');

                                // customize
                                $participant
									.removeClass().addClass('Participant')
									.find('.PositionParticipant').html(Number(j) + 1).end()
									.find('.ListeParticipants').attr('name', 'participant_' + (Number(j) + 1)).val(participantID).end();

                                // append
                                $liste.append($participant);
                            }
                            if (response.d.IsEmployer == false && response.d.IsAdmin == false) {
                                isParticipantRole = true;
                                $formation.find('div.Removable').remove();
                                $formation.find('div.Removable').remove();
                            }
                            // ajout de la formation
                            $html = $html.append($formation);


                        }
                        // display on page
                        $('div#IntialLoading').replaceWith($html.unwrap());
                    } else {
                        $('div#IntialLoading').html(InsMsg.NoFormation);
                    }

                } else {
                    $('div#IntialLoading').html(InsMsg.Error);
                }
            },
            error: function(response) {
                $('div#IntialLoading').html(InsMsg.Error);
            }
        });

        return false;
    }



    /* +---------------------------------------------------
    | ConfirmerSuppressionFormation
    |   demande une confirmation de suppression
    +--------------------------------------------------- */
    function ConfirmerSuppressionFormation() {

        // cloner le tmpl
        $GetTmpl('SuppressionFormation')
			.attr('id', 'SuppressionFormationActive')
			.data('FormationObj', $(this).parents('div.FormationComplete'))
			.appendTo('body')
		;

        // afficher le form
        $.colorbox({
            inline: true,
            href: '#SuppressionFormationActive',
            transition: 'fade',
            opacity: 0.7,
            onCleanup: function() {
                $('#SuppressionFormationActive').remove();
            }
        });

        return false;
    }

    /* +---------------------------------------------------
    | SuppressionFormation
    |   supprimer la formation
    +--------------------------------------------------- */
    function SuppressionFormation() {
        var $this = $(this);
        var $form = $this.parents('#SuppressionFormationActive');
        var $formation = $form.data('FormationObj');

        $form.html('<img src="/includes/js/plugins/colorbox/images/loading.gif" alt="" />');
        $.colorbox.resize();

        $.ajax({
            type: 'POST',
            url: WS('DeleteTraining'),
            data: JSON.stringify({ training: { TrainingId: $formation.data('GUID')} }),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(response) {
                if (response != undefined) {
                    $.colorbox.close();

                    $formation.fadeOut('normal', function() {
                        $(this).remove();
                    });

                } else {
                    $form.html(InsMsg.Error);
                    $.colorbox.resize();
                }
            },
            error: function(response) {
                $form.html(InsMsg.Error);
                $.colorbox.resize();
            }
        });

        return false;

    }

    /* +---------------------------------------------------
    | ShowChoixParticipants
    |   affiche le bloc de choix de partipant
    +--------------------------------------------------- */
    function ShowChoixParticipants() {
        var $this = $(this);
        var o = GetLayout($this);

        // cacher le bouton d'ajout
        $this.hide();

        // load template
        var $ajout = $GetTmpl('AjoutParticipant');

        // customize
        $ajout
			.removeClass().addClass('Participant')
			.find('.PositionParticipant').html(o.$liste.children(".Participant").length + 1).end()
			.find('.ListeParticipants').attr('name', 'participant_' + (o.$liste.children(".Participant").length + 1)).end();
        ;

        // append
        o.$liste.append($ajout);

        return false;
    }

    /* +---------------------------------------------------
    | SupprimerParticipant
    |   supprimer le participant
    +--------------------------------------------------- */
    function SupprimerParticipant() {
        var $this = $(this);
        var o = GetLayout($this);

        // faire disparaitre le bloc
        $this.parents('div.Participant').fadeOut('fast', function() {
            var $this = $(this);

            // supprimer du DOM
            $this.remove();

            // vérifier le bouton d'ajout
            ParticipantAllFilled(o.$root)

            // rafraichir les numéros dans la liste
            o.$liste.find('div.Participant').each(function(i) {
                $(this).find('.PositionParticipant').html(i + 1);
                $(this).find('.ListeParticipants').attr('name', 'participant_' + (i + 1));
            });
        });

        return false;
    }

    /* +---------------------------------------------------
    | ChoixParticipant
    |   actions selon le choix du dropdown de choix de participants
    +--------------------------------------------------- */
    function ChoixParticipant() {
        var $this = $(this);
        var o = GetLayout($this);
        var val = $this.val();

        switch (val) {

            // pas de choix on cache le bouton d'ajout                        
            case 'choisir':
                o.$root.find('a.BtAjout').hide();
                break;

            // ajouter un participant                        
            case 'ajouter':

                // cloner le tmpl
                var $form = $GetTmpl('AjoutParticipantForm').attr('id', 'AjoutParticipantFormActive');
                $('body').append($form);

                // afficher le form
                $.colorbox({
                    inline: true,
                    href: '#AjoutParticipantFormActive',
                    transition: 'fade',
                    opacity: 0.7,
                    onCleanup: function() {
                        $('#AjoutParticipantFormActive').remove();
                        $('#AjoutParticipantLoading').remove();

                        // si on vient d'ajouter un participant
                        if (idParticipant) {
                            $this.val(idParticipant).trigger(changeEvent);
                            idParticipant = false;
                        } else {
                            $this.val('choisir').trigger(changeEvent);
                        }
                    }
                });
                break;


            // choisir un participant existant                        
            default:

                // si déjà sélectionné
                if (ParticipantAlreadyChosen(o.$root, val)) {
                    $this.val('choisir').trigger(changeEvent);
                    display(InsMsg.AlreadySignedUp);
                } else {
                    ParticipantAllFilled(o.$root)
                }
                break;
        }

        return false;
    }



    /* +---------------------------------------------------
    | SubmitParticipant
    |   faire l'ajout du participant
    +--------------------------------------------------- */
    function SubmitParticipant() {
        var $this = $(this);
        var $form = $this.parents('div.AjoutParticipantForm');

        // isEmpty
        function isEmpty(text) {
            text = text.replace(/^\s*|\s*$/g, '');
            text = text.replace(/^\t*|\t*$/g, '');
            return (text == '') ? true : false;
        };

        // isEmail
        function isEmail(text) {
            text = text.replace(/^\s*|\s*$/g, '');
            text = text.replace(/^\t*|\t*$/g, '');
            return (/^\w+([\.\+-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(text) == 0) ? false : true;
        };


        // trap errors
        var errors = [];
        $form.find('input,label').removeClass('Erreur');
        $form.find('#AjoutParticipantError').remove();
        $.colorbox.resize();

        $form.find('input').each(function() {
            var $this = $(this);

            if (isEmpty($this.val())) {
                errors.push('Vous devez inscrire un ' + $this.attr('title'));
                $this.prev('label').andSelf().addClass('Erreur');
            } else if ($this.attr('name') == 'ParticipantCourriel' && !isEmail($this.val())) {
                errors.push('Vous devez inscrire un courriel valide');
                $this.prev('label').andSelf().addClass('Erreur');
            }
        });

        // if errors
        if (errors.length) {

            // show errors msg

        } else {

            // data
            var data = {
                FirstName: $form.find('input[name=ParticipantPrenom]').val(),
                LastName: $form.find('input[name=ParticipantNom]').val(),
                Username: $form.find('input[name=ParticipantCourriel]').val(),
                EmployerId: $('select.ManualEmployerList').val()
            };
            $form.hide();
            $form.parent().append('<div id="AjoutParticipantLoading"><img src="/includes/js/plugins/colorbox/images/loading.gif" alt="" id="" /></div>');
            $.colorbox.resize();

            $.ajax({
                type: 'POST',
                url: WS('RegisterParticipant'),
                data: JSON.stringify({ participantsInformations: data }),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function(response) {
                    if (response != undefined) {
                        idParticipant = response.d;
                        $('select.ListeParticipants').append('<option value="' + idParticipant + '">' + data.FirstName + ' ' + data.LastName + '</option>');
                        $form.remove();
                        $.colorbox.close();
                    } else {
                        $form.html(InsMsg.Error);
                        $.colorbox.resize();
                    }
                },
                error: function(response) {
                    if (response != undefined) {
                        $('#AjoutParticipantLoading').remove();
                        $form.show();
                        $form.find('input[name="ParticipantCourriel"]').prev('label').andSelf().addClass('Erreur');
                        $form.append('<div id="AjoutParticipantError">' + InsMsg.DuplicateEmail + '</div>');
                        $.colorbox.resize();
                    } else {
                        $form.html(InsMsg.Error);
                        $.colorbox.resize();
                    }
                }
            });
        }
        return false;
    }

    /* +---------------------------------------------------
    | Modification du prix
    +--------------------------------------------------- */
    function EditerPrix() {
        var $parent = $(this).parents("p.PrixFormation");
        var prixInitial = $parent.children("span.Prix").html().substr(1);

        // cloner le tmpl
        $GetTmpl('EditionPrix')
			.attr('id', 'EditionPrix')
			.appendTo('body');

        // afficher le form
        $.colorbox({
            inline: true,
            href: '#EditionPrix',
            transition: 'fade',
            opacity: 0.7,
            onCleanup: function() {
                $('#EditionPrix').remove();
                $('a.AppNouveauPrix').unbind('click');
            }
        });

        // application du nouveau prix
        $('a.AppNouveauPrix').bind('click', function() {
            var nouveauPrix = $(this).parents(".EditionPrix").children("input").val();

            validationPrix = /^\$?\d+(\.(\d{2}))?$/;
            if (!validationPrix.test(nouveauPrix)) {
                $(this).parents(".EditionPrix").children("label").addClass("Erreur");
                $(this).parents(".EditionPrix").children(".TxtBox").addClass("Erreur");
            }
            else {
                $parent.children("input.PrixPropose").val(nouveauPrix);
                $parent.children("span.NouveauPrix").html("$" + nouveauPrix);
                $parent.children("span.Prix").addClass("Modifie");
                $.colorbox.close();
            }
            return false;
        });

        return false;
    }

    /* +---------------------------------------------------
    | Réinitialisation du prix
    +--------------------------------------------------- */
    function ReinitPrix() {
        var $parent = $(this).parents("p.PrixFormation");
        var prixInitial = $parent.children("input.PrixInitial").val();
        $parent.children("input.PrixPropose").val(prixInitial);
        $parent.children("span.NouveauPrix").html("");
        $parent.children("span.Prix").removeClass("Modifie");
        return false;
    }

    /* +---------------------------------------------------
    | SubmitFullForm
    |   submit final
    +--------------------------------------------------- */
    function SubmitFullForm() {
        var data = [];
        var error = false;
        var $btn = $(this);

        var vendorList = [];

        $('#ListeVendeurs').children('li').each(function() {
            var $this = $(this);
            $this.children('a').children('span').remove();
            var anchor = $(this).children('a');
            vendorList.push($(anchor).html())
        });

        // pour chaque formation
        $('div.FormationComplete').each(function() {
            var $this = $(this);
            var idFormation = $this.data('GUID');
            var listeParticipants = [];

            var nbReservations = 0;
            if ($('div.Reservations input').length) {
                nbReservations = Number($this.find('div.Reservations input').val());
                if (isNaN(nbReservations)) {
                    nbReservations = 0;
                }
            }

            $this.find('div.Participant select').each(function() {
                var val = $(this).val();
                if (val != 'choisir' && val != 'ajouter') {
                    listeParticipants.push($(this).val());
                }
            });

            if (listeParticipants.length == 0 && isParticipantSelected) {
                listeParticipants.push($('select#ctl00_cphContentBody_ClientList option:selected').val());
            }

            if (isParticipantRole) {
                listeParticipants.push('00000000-0000-0000-0000-000000000000');
            }

            // s'il n'y a pas de participants ET aucune réservation
            if (!listeParticipants.length && nbReservations <= 0) {
                error = true;
                return false;
            }


            var dealPrice = $this.find('.PrixPropose').val();

            data.push({
                DealPrice: Number(dealPrice),
                TrainingId: idFormation,
                ParticipantIdList: listeParticipants,
                ReservationAmount: nbReservations.toString()
            });
        });

        if (!error && data.length) {
            $.ajax({
                type: 'POST',
                url: WS('ProcessFormation'),
                data: JSON.stringify({ basketTrainingList: { VendorList: vendorList, FormationList: data} }),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function(response) {
                    if (response != undefined) {
                        eval($btn.attr('href').substr(11));
                    } else {
                        display(InsMsg.Error);
                    }
                },
                error: function(response) {
                    display(InsMsg.Error);
                }
            });
        } else {
            display(InsMsg.AtLeastOne);
        }

        return false;
    }
})(jQuery, window);
