/*
	Author: Jeremy Espinosa
	Filename: form.js
	Description: 
	Dependencies:
		- jquery-validation
	How to use:
*/

;
(function($) {
    'use strict'

    B2C.form = {
        init: function(option) {
            // set default
            let _default = {
                target: '#mg-form',
                showDetails: '.js-showDetail',
                hideDetails: '.js-hideDetail',
                serialForm: '.js-validateserialForm',
                prodForm: '.js-prodRegistration',
                validateSerial: '.js-validateserial',
                detailsToShow: '.hiddenDetails',
                uploadFile: '.js-upload',
                showDropItem: '.js-dropDownShowHide',
                dropDownItem: '.drop-down-item',
                writeReview: '.js-review',
                closeContent: '.js-close',
                options: {
                    errorClass: 'mg-form__error'
                }
            }

            // combine the default and option pass
            this._option = $.extend(true, _default, option)

            if (!$(this._option.target).length) return

            $(this._option.target).validate(this._option.options)

            // can create customize method or create own rules
            this.createMethod()
            this.eventListner()
                // this.getCountry()
        },

        createMethod: function() {

            //this is base on the current implementation to validate email
            $.validator.methods.email = function(value, element) {
                return this.optional(element) || /^\(([a-zA-Z0-9 _\-\.\+]+)\)\ ([a-zA-Z0-9\n_\!\#\$\%\&\'\*\-\/\=\?\^\`\{\|\}\~\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\\n.[0-9]{1,3}\.)|(([a-zA-Z0-9\w\n_\!\#\$\%\&\'\*\-\/\=\?\^\`\{\|\}\~]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3}\n)$|^([a-zA-Z0-9 \w\n_\!\#\$\%\&\'\*\-\/\=\?\^\`\{\|\}\~\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\\n.[0-9]{1,3}\.)|(([a-zA-Z0-9_\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})$/.test(value);
            }

            //textfield accepts alphanumeric, underscore and dash only
            $.validator.addMethod('nospecialChar', function(value, element) {
                return this.optional(element) || /^[0-9a-zA-Z\_\-]+$/.test(value);
            }, "No special character");

            //textfield accepts numbers only
            $.validator.addMethod('numbersOnly', function(value, element) {
                return this.optional(element) || /^[0-9\+]+$/.test(value);
            }, "Numbers only please")

            //Select element validator
            $.validator.addMethod('selectValidator', function(value, element, arg) {
                return arg !== $(element).find('option:selected').text() || arg !== value
            }, "Please select")

            //URL Validator
            $.validator.addMethod('urlValidator', function(value, element) {
                return this.optional(element) || /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/gm.test(value.toLowerCase());
            }, "Invalid URL")


        },
        eventListner: function() {
            let self = B2C.form
                //validate serial number in product registration
            $(this._option.validateSerial).on('click', self.serialValidate)

            //for radio button -- show and hide of company option
            $(this._option.showDetails).on('change', self.showCompanyDetails)
            $(this._option.hideDetails).on('change', self.showCompanyDetails)

            //for upload purpose
            $(this._option.uploadFile).on('change', self.uploadFile)

            //showHide items using dropdown
            $(this._option.showDropItem).on('change', self.showDropDownItems)

            //show write review 
            $(this._option.writeReview).on('click', self.writeProductReview)

            //close Content	
            $(this._option.closeContent).on('click', self.closeContent)
        },
        // getCountry: function() {
        //     let self = B2C.form
        //     $.getJSON('../public/data/countries.json', function(result) {
        //         self.renderCountries(result)
        //     })
        // },
        // renderCountries: function() {
        //     let template = Handlebars.compile($('#options').html()),
        //         html = template(data),
        //         countryList = $('.country-list')

        //     countryList.append(html)
        // },
        serialValidate: function() {
            let self = B2C.form._option,
                targetClass = self.serialForm,
                showForm = self.prodForm
            $(targetClass).addClass('d-none')
            $(showForm).removeClass('d-none')
        },
        showCompanyDetails: function() {
            let self = B2C.form._option,
                companyOption = self.detailsToShow,
                showOption = self.showDetails

            //Checker if the radio company is selected
            if ($(showOption).is(":checked")) {
                $(companyOption).removeClass('d-none')
            } else {
                $(companyOption).addClass('d-none')
            }
        },
        uploadFile: function() {
            let self = B2C.form._option
        },
        showDropDownItems: function() { //switcher forms to show
            let self = B2C.form._option,
                showDropItem = self.showDropItem,
                itemShow = self.dropDownItem,
                value = $(showDropItem).find("option:selected").attr('value')
            $(itemShow).removeClass("active")

            $('#' + value).addClass("active")
            if (value === "") {
                $(dropDownItem).hide()
            }

        },
        writeProductReview: function() {
            let self = B2C.form._option,
                detailsToShow = self.detailsToShow
            $(detailsToShow).removeClass('d-none')
        },
        closeContent: function() {
            let self = B2C.form._option,
                detailsToShow = self.detailsToShow
            $(detailsToShow).addClass('d-none')
        }
    }

    // initialize form here
    // if you have additional rules just add it as parameter
    B2C.form.init({
        options: {
            rules: {
                field: {
                    nospecialChar: true
                },
                numberfield: {
                    numbersOnly: true
                },
                country: {
                    required: true
                },
                brandList: {
                    required: true
                },
                modelname: {
                    required: true
                },
                website: {
                    urlValidator: true
                },
                language: {
                    required: true
                },
                parts: {
                    required: true
                }
            }
        }
    })
})(jQuery)