(function ($) {
    $(document).ready(function () {

        $('input').livequery(function () {
            $(this).input();
        });

        //Restrictions sur les champs à chiffres
        $('input.number').livequery(function () {
            $(this).keypress(function (e) {

                var char_code       = e.charCode ? e.charCode:0;
                var key_code        = char_code > 0 ? 0:e.keyCode ? e.keyCode:0;
                var code            = char_code === 0 ? key_code:char_code;
                var accepted_code   = new Array(
                    48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
                    13, 8, 9, 27
                );

                if ($.inArray(code, accepted_code) === -1 && (key_code === 0 && char_code > 0)) {
                    e.preventDefault();
                    e.stopPropagation();
                }

            });
        });

        $('input.phone').livequery(function () {
            $(this).keypress(function (e) {

                var char_code       = e.charCode ? e.charCode:0;
                var key_code        = char_code > 0 ? 0:e.keyCode ? e.keyCode:0;
                var code            = char_code === 0 ? key_code:char_code;
                var accepted_code   = new Array(
                    48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
                    43, 13, 8, 9, 27
                );

                if ($.inArray(code, accepted_code) === -1 && (key_code === 0 && char_code > 0)) {
                    e.preventDefault();
                    e.stopPropagation();
                }

            });
        });


        //Fonction de gestion des popups
        $('div.back-popup').livequery(function () {
            var backPopup   = $(this);
            var contenu     = $(this).next();
            var popup       = $('<div></div>').css('display', $(this).css('display'));

            //On ajoute cette popup après le calque noir
            backPopup.add(contenu).wrapAll(popup);

            contenu.addClass('shadow');
            contenu.css({
                position:   'fixed',
                top:    '50%',
                left:   '50%',
                marginLeft: '-' + (contenu.outerWidth()/2) + 'px',
                marginTop:  '-' + (contenu.outerHeight()/2) + 'px'
            });

            var heightContenu = contenu.outerHeight();

            backPopup.show();

            contenu.resize(function () {
                if (contenu.height() !== 0 && contenu.width() !== 0) {
                    heightContenu = contenu.outerHeight();
                    if ($(window).height() < heightContenu) {
                        contenu.css({
                            'position':     'absolute',
                            top:    '0',
                            left:   '50%',
                            marginLeft: '-' + (contenu.outerWidth()/2) + 'px',
                            marginTop:  '0px'
                        });
                    }
                    else {
                        contenu.css({
                            'position':     'fixed',
                            top:    '50%',
                            left:   '50%',
                            marginLeft: '-' + (contenu.outerWidth()/2) + 'px',
                            marginTop:  '0px'
                        });
                    }
                }
            });

            //On détecte le resize de la popup qui va permettre de redimmenssionner l'image précédente
            if ($(window).height() < heightContenu) {
                contenu.css({
                    'position':     'absolute',
                    top:    '0',
                    left:   '50%',
                    marginLeft: '-' + (contenu.outerWidth()/2) + 'px',
                    marginTop:  '0px'
                });
            }
            $(window).bind('resize scroll', function () {
                if ($(window).height() < heightContenu) {
                    if ((heightContenu - $(window).height()) <= $(window).scrollTop()-30) {
                        contenu.css({
                            'position':     'fixed',
                            top:    '0',
                            left:   '50%',
                            marginLeft: '-' + (contenu.outerWidth()/2) + 'px',
                            marginTop:  '-' + (heightContenu - $(window).height()) + 'px'
                        });
                    }
                    else {
                        contenu.css({
                            'position':     'absolute',
                            top:    '0',
                            left:   '50%',
                            marginLeft: '-' + (contenu.outerWidth()/2) + 'px',
                            marginTop:  '0px'
                        });
                    }
                }
                else {
                    contenu.css({
                        'position':     'fixed',
                        top:    '50%',
                        left:   '50%',
                        marginLeft: '-' + (contenu.outerWidth()/2) + 'px',
                        marginTop:  '-' + (heightContenu/2) + 'px'
                    });
                }
            });
        });


        //Gestion des formulaires
        $('form').livequery(function () {
            var $this = $(this);
            var encours = false;
            var loadView = false;

            $this.idform();

            //On detecte l'envoi du formulaire
            $this.bind('idform_' + $this.attr('id') + '_submitted', function () {

                //On va chercher dans les fichiers de langue le texte à afficher pour faire patienter
                var msgLoad = eval('Translate.form.' + $this.attr('id') + '.load');
                //Si rien est en cours on peut continuer
                if (!encours) {
                    encours = true;
                    //Si rien n'est affiché on continue
                    if (!loadView) {
                        //On charge la popup d'attente'
                        var loadDiv = $('<div></div>').attr('id', 'idvive_loaded_form_' + $this.attr('id')).css({
                            zIndex:         6,
                            position:       'absolute',
                            width:          $this.width()
                        }).append($('<div></div>').attr('class','backLoadForms').css({
                            width:          $this.width(),
                            height:         $this.height()
                        }).after($('<div></div>').attr('class','loadForms').css({
                            zIndex:         7
                        }).append('<img src="' + baseurl + '/template/default/images/submit-load.gif" /> ' + msgLoad))).hide();

                        //Si toujours rien est affiché on continue
                        if (!loadView) {
                            loadView = true;
                            //On charge la popup
                            $this.prepend(loadDiv);
                            //On affiche
                            $('#idvive_loaded_form_' + $this.attr('id')).fadeIn();
                            var hLoad = $('.loadForms').height();
                            $('.loadForms').css({
                                top:            -((($this.height())/2)+hLoad)
                            });

                            //On detect si le formulaire est redimmensionné au quel cas on resize l'affichage
                            $this.resize(function () {
                                var aResize = $('#idvive_loaded_form_' + $this.attr('id'));

                                $('.backLoadForms', aResize).css({
                                    width:          $this.width(),
                                    height:         $this.height()
                                });

                                hLoad = $('.loadForms').height();
                                $('.loadForms').css({
                                    top:            -(($this.height()/2)+hLoad)
                                });
                            });
                        }
                        else {
                            delete loadDiv;
                        }
                    }
                }
            });

            //Lorsque le formulaire est en erreur on cache les popups d'attente
            $this.bind('idform_' + $this.attr('id') + '_validationError idform_' + $this.attr('id') + '_savedFailed idform_' + $this.attr('id') + '_savedSuccess', function () {
                if (encours) {
                    encours = false;
                    if (loadView) {
                        loadView = false;
                        $('#idvive_loaded_form_' + $this.attr('id')).each(function () {
                            $(this).fadeOut('normal', function () {
                                if (loadView) {
                                    $(this).fadeIn();
                                }
                                else {
                                    $(this).remove();
                                }
                            });
                        });
                    }
                }
            });
        });

        $('#authentification_login').each(function () {
            var $this = $(this);

            $(this).bind('idform_authentification_login_savedSuccess', function (type, response) {
                if (response.type === 'diffuseur') {
                    window.location = baseurl + '/profil';
                }
                else if (response.type === 'administrator') {
                    window.location = baseurl + '/admin';
                }
            });

            $(this).bind('idform_authentification_login_savedFailed', function (type, response) {
                if (response.errorType === 'authentification_fail') {
                    var message_errors = $('<ul></ul>');
                    message_errors.append($('<li></li>').append(Translate.form.authentification_login.loginFail));

                    var el = $('.login');

                    var cont = $('<div></div>').attr('class', 'errors').append(message_errors);
                    el.after(cont.hide());
                    cont.slideDown();
                    $this.submit(function () {
                        cont.slideUp('normal', function () {
                            $(this).remove();
                        });
                    });
                    cont.css({
                        left:   $('.login-label').position().left,
                        top:    $('.login-label').position().top+30,
                        width:  $('.login').width()
                    });
                }
                else {
                    var error_unkonwn = $('<div></div>').attr('class', 'error').css({position: 'absolute', width: '380px', height: '100px', textAlign: 'center', padding: '20px'}).append(Translate.form.authentification_login.unknownError).hide();
                    $this.before(error_unkonwn);
                    error_unkonwn.fadeIn();
                }
            });
        });

        $('.blockinfo').livequery(function () {

            var top = $('<div></div>').attr('class', 'blockinfo_top');
            var bottom = $('<div><div>').attr('class', 'blockinfo_bottom');

            $(this).before(top);
            $(this).after(bottom);

        });

        var script_fb = $('<script></script>').attr({
            'id'    : 'facebook-jssdk',
            'async' : 'true',
            'src'   : '//connect.facebook.net/fr_FR/all.js'
        });

        $('head').append(script_fb);

        window.fbAsyncInit = function() {
            FB.init({
                appId      : '315295561830741', // App ID
                channelUrl : '//adonn.fr/channel.html', // Channel File
                status     : true, // check login status
                cookie     : true, // enable cookies to allow the server to access the session
                xfbml      : true  // parse XFBML
            });
        };



        function createIban() {

            $('#iban').val($('#iban1').val() + $('#iban2').val() + $('#iban3').val() + $('#iban4').val() + $('#iban5').val() + $('#iban6').val() + $('#iban7').val());

        }

        $('#iban').each(function () {
            var val = $(this).val();

            var iban1 = $('<input />').attr({'id': 'iban1', 'maxlength': 4, 'type': 'text'}).addClass('iban').val(val.substr(0, 4)).bind('keyup change', function (e) {
                var char_code       = e.charCode ? e.charCode:0;
                var key_code        = char_code > 0 ? 0:e.keyCode ? e.keyCode:0;
                var code            = char_code === 0 ? key_code:char_code;

                createIban();
                if ($(this).val().length === 4 && code !== 9 && code !== 16 && code !== 37 && code !== 38 && code !== 39 && code !== 40) {
                    $('#iban2').focus();
                }
            });
            $(this).before(iban1);

            var iban2 = $('<input />').attr({'id': 'iban2', 'maxlength': 4, 'type': 'text'}).addClass('iban').val(val.substr(4, 4)).bind('keyup change', function (e) {
                var char_code       = e.charCode ? e.charCode:0;
                var key_code        = char_code > 0 ? 0:e.keyCode ? e.keyCode:0;
                var code            = char_code === 0 ? key_code:char_code;

                createIban();
                if ($(this).val().length === 4 && code !== 9 && code !== 16 && code !== 37 && code !== 38 && code !== 39 && code !== 40) {
                    $('#iban3').focus();
                }
            });
            iban1.after(iban2);

            var iban3 = $('<input />').attr({'id': 'iban3', 'maxlength': 4, 'type': 'text'}).addClass('iban').val(val.substr(8, 4)).bind('keyup change', function (e) {
                var char_code       = e.charCode ? e.charCode:0;
                var key_code        = char_code > 0 ? 0:e.keyCode ? e.keyCode:0;
                var code            = char_code === 0 ? key_code:char_code;

                createIban();
                if ($(this).val().length === 4 && code !== 9 && code !== 16 && code !== 37 && code !== 38 && code !== 39 && code !== 40) {
                    $('#iban4').focus();
                }
            });
            iban2.after(iban3);

            var iban4 = $('<input />').attr({'id': 'iban4', 'maxlength': 4, 'type': 'text'}).addClass('iban').val(val.substr(12, 4)).bind('keyup change', function (e) {
                var char_code       = e.charCode ? e.charCode:0;
                var key_code        = char_code > 0 ? 0:e.keyCode ? e.keyCode:0;
                var code            = char_code === 0 ? key_code:char_code;

                createIban();
                if ($(this).val().length === 4 && code !== 9 && code !== 16 && code !== 37 && code !== 38 && code !== 39 && code !== 40) {
                    $('#iban5').focus();
                }
            });
            iban3.after(iban4);

            var iban5 = $('<input />').attr({'id': 'iban5', 'maxlength': 4, 'type': 'text'}).addClass('iban').val(val.substr(16, 4)).bind('keyup change', function (e) {
                var char_code       = e.charCode ? e.charCode:0;
                var key_code        = char_code > 0 ? 0:e.keyCode ? e.keyCode:0;
                var code            = char_code === 0 ? key_code:char_code;

                createIban();
                if ($(this).val().length === 4 && code !== 9 && code !== 16 && code !== 37 && code !== 38 && code !== 39 && code !== 40) {
                    $('#iban6').focus();
                }
            });
            iban4.after(iban5);

            var iban6 = $('<input />').attr({'id': 'iban6', 'maxlength': 4, 'type': 'text'}).addClass('iban').val(val.substr(20, 4)).bind('keyup change', function (e) {
                var char_code       = e.charCode ? e.charCode:0;
                var key_code        = char_code > 0 ? 0:e.keyCode ? e.keyCode:0;
                var code            = char_code === 0 ? key_code:char_code;

                createIban();
                if ($(this).val().length === 4 && code !== 9 && code !== 16 && code !== 37 && code !== 38 && code !== 39 && code !== 40) {
                    $('#iban7').focus();
                }
            });
            iban5.after(iban6);

            var iban7 = $('<input />').attr({'id': 'iban7', 'maxlength': 3, 'type': 'text'}).addClass('iban').val(val.substr(24, 3)).bind('keyup change', function (e) {
                var char_code       = e.charCode ? e.charCode:0;
                var key_code        = char_code > 0 ? 0:e.keyCode ? e.keyCode:0;
                var code            = char_code === 0 ? key_code:char_code;

                createIban();
                if ($(this).val().length === 3 && code !== 9 && code !== 16 && code !== 37 && code !== 38 && code !== 39 && code !== 40) {
                    $('#bic').focus();
                }
            });
            iban6.after(iban7);

            $(this).hide();
        });

    });
})(jQuery);

