jQuery( function ( $ ) {
    $(document).ready(function() {
        // default multiple select
        $(".emc-setup select:not([name='facturation-pays_iso'], [name='facturation-contact_etat'], [name='user-default_shipping_country'])")
        .multipleSelect({
            width: '100%',
            selectAllText: translations.selectAll,
            allSelected: translations.allSelected,
            single: true
        });
        // state selection
        $(".emc-setup select[name='facturation-contact_etat']").multipleSelect({
            width: '100%',
            selectAllText: translations.selectAll,
            allSelected: translations.allSelected,
            single: true,
            filter: true
        });
        // country selection
        $(".emc-setup select[name='facturation-pays_iso']").multipleSelect({
            width: '100%',
            selectAllText: translations.selectAll,
            allSelected: translations.allSelected,
            single: true,
            filter: true,
            onClick : function(option) {
                populateStates(option.value, '');
                updateSiretVat();
            }
        });
        // shipping country selection
        $(".emc-setup select[name='user-default_shipping_country']").multipleSelect({
            width: '100%',
            selectAllText: translations.selectAll,
            allSelected: translations.allSelected,
            single: true,
            onClick : function(option) {
                $('#pays_iso').multipleSelect("setSelects", [option.value]);
                populateStates(option.value, $('#contact_etat select').multipleSelect("getSelects")[0]);
                updateSiretVat();
            }
        });

        updateSiretVat();

        // user-volumetrie select is disabled by default
        $('#volumetrie select').multipleSelect("disable");
        /* Ask for the number items the user is sending if he said yes to question about he's online presence */
        $('[name="user-site-online"]').change(function() {
            if($(this).multipleSelect("getSelects")[0] == "1") {
                $('#volumetrie select').multipleSelect("enable");
                $('#volumetrie').show();
            } else {
                $('#volumetrie select').multipleSelect("disable");
                $('#volumetrie').hide();
            }
        });

        if ($('#emc-submit-account').length > 0) {
            fields = {
                "user-default_shipping_country" : {
                    required: true,
                    type: "select"
                },
                "facturation-contact_civ" : {
                    required: true,
                    type: "radio"
                },
                "facturation-contact_nom" : {
                    required: true,
                    type: "text"
                },
                "facturation-contact_prenom" : {
                    required: true,
                    type: "text"
                },
                "user-site-online" : {
                    required: true,
                    type: "select"
                },
                "user-volumetrie" : {
                    required: "user-site-online",
                    type: "select"
                },
                "user-partner_code" : {
                    required: false,
                    type: "text"
                },
                "facturation-url" : {
                    required: false,
                    type: "text"
                },
                "facturation-contact_email" : {
                    required: true,
                    type: "text",
                    format: "email"
                },
                "facturation-contact_email2" : {
                    equalTo: "facturation-contact_email",
                    required: true,
                    type: "text"
                },
                "user-login" : {
                    required: true,
                    type: "text",
                    format: "alphanumeric"
                },
                "user-password" : {
                    minlength: 6,
                    required: true,
                    type: "password"
                },
                "user-confirm_password" : {
                    equalTo: "user-password",
                    required: true,
                    type: "password"
                },
                "facturation-contact_ste" : {
                    required: true,
                    type: "text"
                },
                "facturation-adresse1" : {
                    required: true,
                    type: "text"
                },
                "facturation-adresse2" : {
                    required: false,
                    type: "text"
                },
                "facturation-adresse3" : {
                    required: false,
                    type: "text"
                },
                "facturation-pays_iso" : {
                    required: true,
                    type: "select"
                },
                "facturation-contact_etat" : {
                    required: "facturation-pays_iso",
                    type: "select"
                },
                "facturation-codepostal" : {
                    required: true,
                    type: "text"
                },
                "facturation-ville" : {
                    required: true,
                    type: "text"
                },
                "facturation-contact_tel" : {
                    required: true,
                    type: "text",
                    format: "phone"
                },
                "facturation-defaut_enl" : {
                    required: false,
                    type: "checkbox"
                },
                "facturation-contact_locale" : {
                    required: true,
                    type: "select"
                },
                "facturation-contact_stesiret" : {
                    required: true,
                    type: "text",
                    format: "siret"
                },
                "facturation-contact_tvaintra" : {
                    required: false,
                    type: "text"
                },
                "cgv" : {
                    required: true,
                    type: "checkbox"
                },
                "newsletterEmc" : {
                    required: false,
                    type: "checkbox"
                },
            };
        }

        if ($('#emc-generate-keys').length > 0) {
            fields = {
                "user-site-online" : {
                    required: true,
                    type: "select"
                },
                "user-volumetrie" : {
                    required: "user-site-online",
                    type: "select"
                },
                "user-login" : {
                    required: true,
                    type: "text",
                },
                "user-password" : {
                    required: true,
                    type: "password"
                },
                "cgv" : {
                    required: true,
                    type: "checkbox"
                },
            };
        }

        if (typeof(fields) != "undefined") {
            $.each(fields, function(name, field) {
                $(document).on('change', '[name="'+name+'"]', function () {
                    var checkEl = null;
                    if ($('#emc-generate-keys').length > 0) {
                        checkEl = validateForm($('#EMC-api-keys'), name);
                    } else {
                        checkEl = validateForm($('#EMC-account-creation'), name);
                    }
                    if (checkEl !== true) {
                        $.each(checkEl, function (name, error) {
                            addError(name, error);
                        });
                    } else {
                        removeErrors(name);
                    }
                });
            });
        }

        checkAccountForm = false;

        $('#emc-submit-account').click(function(e) {
            // let the click proceed
            if (checkAccountForm === true) {
                checkAccountForm = false; // reset flag
                return;
            }

            e.preventDefault();
            var checkForm = validateForm($('#EMC-account-creation'));
            if (checkForm !== true) {
                $.each(checkForm, function (name, error) {
                    addError(name, error);
                });
                // scroll up to first error
                $('html, body').animate({
                    scrollTop: $(".triangle-border:first").offset().top
                });
                return false;
            }
            $('#loading-animation').show();
            $('#loading-animation').css('width', $('#emc-submit-account').css('width'));
            $(this).hide();
            $.ajax({
                url:ajax_url,
                data: { action: 'create_account', security: ajax_nonce, data: $('#EMC-account-creation').serializeArray()},
                dataType: 'json',
                method: 'POST',
                success: function(res) {
                    if (res !== false) {
                        if (res === 1) {
                            // submit form and proceed to next page
                            checkAccountForm = true;
                            $('#emc-submit-account').trigger('click');
                            // disable buttons while redirect is happening
                            $('#emc-submit-account').prop('disabled', true);
                            $('.emc-setup-actions a').click(function(e) {
                                e.preventDefault();
                            });
                        } else {
                            $.each(res, function(i, item) {
                                var name;
                                switch (i) {
                                    case "known_email":
                                    case "facturation.email":
                                        name = "facturation-contact_email";
                                        break;

                                    case "facturation.civilite":
                                        name = "facturation-contact_civ";
                                        break;

                                    case "facturation.nom":
                                        name = "facturation-contact_nom";
                                        break;

                                    case "facturation.prenom":
                                        name = "facturation-contact_prenom";
                                        break;

                                    case "facturation.adresse":
                                        name = "facturation-adresse1";
                                        break;

                                    case "facturation.tel":
                                        name = "facturation-contact_tel";
                                        break;

                                    case "facturation.codepostal":
                                        name = "facturation-codepostal";
                                        break;

                                    default:
                                        name = i;
                                        break;
                                }
                                addError(name, item);
                            });
                            // scroll up to first error
                            $('html, body').animate({
                                scrollTop: $(".triangle-border:first").offset().top
                            });
                            $('#loading-animation').hide();
                            $('#emc-submit-account').show();
                        }
                    }
                    return false;
                }
            });

        });

        checkKeysForm = false;

        $('#emc-generate-keys').click(function(e) {
            // let the click proceed
            if (checkKeysForm === true) {
                checkKeysForm = false; // reset flag
                return;
            }

            e.preventDefault();
            var checkForm = validateForm($('#EMC-api-keys'));
            if (checkForm !== true) {
                $.each(checkForm, function (name, error) {
                    addError(name, error);
                });
                // scroll up to first error
                $('html, body').animate({
                    scrollTop: $(".triangle-border:first").offset().top
                });
                return false;
            }
            $('#loading-animation').show();
            $('#loading-animation').css('width', $('#emc-generate-keys').css('width'));
            $(this).hide();
            $.ajax({
                url:ajax_url,
                data: { action: 'generate_keys', security: ajax_nonce, data: $('#EMC-api-keys').serializeArray()},
                dataType: 'json',
                method: 'POST',
                success: function(res) {
                    if (res !== false) {
                        if (res === 1) {
                            // submit form and proceed to next page
                            checkKeysForm = true;
                            $('#emc-generate-keys').trigger('click');
                            // disable buttons while redirect is happening
                            $('#emc-generate-keys').prop('disabled', true);
                            $('.emc-setup-actions a').click(function(e) {
                                e.preventDefault();
                            });
                        } else {
                            $.each(res, function(i, item) {
                                addError(i, item);
                            });
                            // scroll up to first error
                            $('html, body').animate({
                                scrollTop: $(".triangle-border:first").offset().top
                            });
                            $('#loading-animation').hide();
                            $('#emc-generate-keys').show();
                        }
                    }
                    return false;
                }
            });

        });
    });

    function populateStates(id_country, id_state) {
        $.ajax({
            url: ajax_url,
            method: 'POST',
            data: {
                action: 'return_states',
                security: ajax_nonce,
                id_country: id_country
            },
            dataType:'html',
            success: function (html) {
                if (html == "false") {
                    $("#contact_etat").hide();
                    $("#contact_etat select").html('');
                    $("#contact_etat select").multipleSelect('refresh');
                } else {
                    $("#contact_etat").show();
                    $("#contact_etat select").html(html);
                    $("#contact_etat select").multipleSelect('refresh');

                    // set submitted value if set
                    if (id_state) {
                        $('#contact_etat select').multipleSelect("setSelects", [id_state]);
                    }
                }
            }
        });
    }

    function updateSiretVat() {
        pays = $('#pays_iso').multipleSelect("getSelects")[0];
        franceFirmChecked = (pays == "FR");
        spainFirmChecked = (pays == "ES");
        worldFirmChecked = (ue.indexOf(pays) == -1);

        // change the placeholders and display of the siret inputs
        if (franceFirmChecked) {
            // France
            $('label[for="facturation-contact_stesiret"]').html(translations.siretLabelFr);
            $('#tva').show();
            $('#tva input').removeAttr("disabled");
        } else if (spainFirmChecked) {
            // Spain
            $('label[for="facturation-contact_stesiret"]').html(translations.siretLabelEs);
            $('#tva').show();
            $('#tva input').removeAttr("disabled");
        } else if (!worldFirmChecked) {
            // Europe
            $('label[for="facturation-contact_stesiret"]').html(translations.siretLabelWorld);
            $('#tva').show();
            $('#tva input').removeAttr("disabled");
        } else {
            // World
            $('label[for="facturation-contact_stesiret"]').html(translations.siretLabelWorld);
            $('#tva').hide();
            $('#tva input').attr("disabled", "disabled");
        }
    }

    /* function to validate form, if an element name is passed is passed then only this element is validated */
    function validateForm(formEl, elName) {
        var errors = {};
        $.each(fields, function(name, field) {
            if (typeof(elName) != "undefined" && name != elName) {
                return true;
            }

            var el = formEl.find('[name="'+name+'"]');

            el.removeClass('error');

            // get value
            var value = null;
            switch(field.type) {
                case "text":
                case "radio":
                case "password":
                    value = el.val();
                    break;

                case "select":
                    value = el.multipleSelect("getSelects")[0];
                    break;

                case "checkbox":
                    value = el.is(':checked');
                    break;

                default:
                    value = "";
                    break;
            }

            // check if required
            if (field.required === false) {
                return true;
            } else if (field.required === true) {
                if ((field.type == "text" && value === "") || (field.type == "checkbox" && value === false)) {
                    errors[name] = translations.required;
                    return true;
                }
            } else {
                switch(field.required) {
                    case "user-site-online":
                        var parentInput = formEl.find('[name="user-site-online"]');
                        if (parentInput.multipleSelect("getSelects")[0] == 1) {
                            if (value === "") {
                                errors[name] = translations.required;
                                return true;
                            }
                        }
                        break;

                    default:
                        break;
                }
            }

            // check minlength
            if (typeof (field.minlength) != "undefined") {
                if (value.length < field.minlength) {
                    errors[name] = translations.minlength;
                    return true;
                }
            }

            // check duplicate fields
            if (typeof (field.equalTo) != "undefined") {
                var parentEl = formEl.find('[name="'+field.equalTo+'"]');
                if (parentEl.val() != value) {
                    if (name == "facturation-contact_email2") {
                        errors[name] = translations.mismatchEmail;
                    }
                    if (name == "user-confirm_password") {
                        errors[name] = translations.mismatchPassword;
                    }
                    return true;
                }
            }

            // check format
            if (typeof (field.format) != "undefined") {
                switch(field.format) {
                    case "alphanumeric":
                        if (/^[a-zA-Z0-9]+$/.test(value) === false) {
                            errors[name] = translations.formatAlpha;
                            return true;
                        }
                        break;

                    case "phone":
                        if (/^([+\- \(\)]*[\d])+$/.test(value) === false) {
                            errors[name] = translations.formatPhone;
                            return true;
                        }
                        break;

                    case "email":
                        if (/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/.test(value) === false) {
                            errors[name] = translations.formatEmail;
                            return true;
                        }
                        break;

                    case "siret":
                        if ((franceFirmChecked && value.length != 14) || (!franceFirmChecked && value.length < 1))  {
                            if (franceFirmChecked) {
                                errors[name] = translations.lengthSiret;
                            } else {
                                errors[name] = translations.lengthOther;
                            }
                            return true;
                        }
                        break;

                    default:
                        break;
                }
            }

        });

        if (!$.isEmptyObject(errors)) {
            return errors;
        } else {
            return true;
        }
    }

    function addError(name, error) {
        var el = $('[name="'+name+'"]');
        if (el.length > 0) {
            el.addClass('error');
            var elErrorText = $('.'+name.replace('.', '-')+'-error');
            elErrorText.addClass("triangle-border").addClass("left");
            elErrorText.html(error);
            var position = null;
            if (el.attr("type") == "checkbox") {
                var label = $('label[for="'+name+'"]');
                position = label.offset();
                // 10 is the margin left negative value of .triangle-border.left:before class
                elErrorText.css("left", (position.left+label.width()+10));
                elErrorText.css("top", position.top+label.height()/2-elErrorText.outerHeight()/2);
            } else {
                position = el.offset();
                elErrorText.css("left", (position.left+el.width()+10));
                elErrorText.css("top", position.top+el.height()/2-elErrorText.outerHeight()/2);
            }
            elErrorText.fadeIn();
        }
    }

    function removeErrors(name) {
        var elErrorText = $('.'+name.replace('.', '-')+'-error');
        elErrorText.fadeOut(400, function() {
            elErrorText.removeClass("triangle-border").removeClass("left");
            elErrorText.html();
        });
    }
});
