var jQ = jQuery.noConflict(),
    global = {
        settings: {
            url : null,
            notif_url: null,
            countNotif_url: null,
            notifList_url: null,
            doSeenNotif_url: null,
            ajaxRequest: [],
            vars: {
                flashMessagesContentId: '#flash-messages-content'
            },
            io: null,
        },
        init: function() {
            this.initFoundation();
            this.initSideMenu();
            //this.initSideMenuHeight();
            this.initNotif();
            this.bindFormSubmitted();
            this.initFlashMessages();
            this.backToTop();
            //this.draggableReveal();
        },
        initFoundation: function() {
            jQ(document).foundation();
        },
        initFlashMessages: function() {
            if(jQ('.flash-messages').length) {
                //jQ('#flash-messages').fadeIn(850);
                setTimeout(function(){
                    if(jQ('.flash-messages-close-button').length > 0) jQ('.flash-messages-close-button').click();
                }, 10000);
            }
        },
        initSideMenu: function() {
            jQ('.main-side-menu-toggle').unbind('click').bind('click', function(){
                if(jQ('#main-side-menu-container').css('margin-left') === '-222px') {
                    jQ('#main-side-menu-container').animate({
                        marginLeft: '0'
                    }, {
                        start: function() {
                            jQ('#content-container').animate({
                                width: '-=222px'
                            });
                        },
                        complete: function() { // Just to make sure the width will be changed to its needed value
                            jQ('#content-container').css('width', '');
                            global.setCookie('msm-hidden', 'no', 365);
                        }
                    });
                } else {
                    jQ('#main-side-menu-container').animate({
                        marginLeft: '-222px'
                    }, {
                        start: function() {
                            jQ('#content-container').animate({
                                width: '+=222px'
                            });
                        },
                        done: function() {
                            jQ('#content-container').css('width', '100%');
                            global.setCookie('msm-hidden', 'yes', 365);
                        }
                    });
                }
            });
        },
       /* initSideMenuHeight: function() {
            if(jQ('#content-container').height() > jQ('#main-side-menu').height()) {
                jQ('#main-side-menu').css('min-height', jQ('#content-container').height() + 'px');
            }
            new ResizeSensor(jQ('#content-container'), function(){
                if(jQ('#content-container').height() > jQ('#main-side-menu').height()) {
                    jQ('#main-side-menu').css('min-height', jQ('#content-container').height() + 'px');
                } else {
                    jQ('#main-side-menu').css('min-height', '');
                }
            });
        },*/
        initNotif: function() {
            if(this.settings.notif_url != null) {
                this.countNotif();
                jQ('#global-notif-toggle').unbind('click').bind('click', function() {
                    var notifContent = jQ('#global-notif-content');
                    if(notifContent.css('display') == 'block') {
                        notifContent.fadeOut(300);
                    } else {
                        notifContent.fadeIn(300);
                        global.getNotif();
                    }
                    return false;
                });
                jQ(document).unbind('click.fadeOutNotif').bind('click.fadeOutNotif', function(){
                    jQ('#global-notif-content').fadeOut(300);
                });
                jQ('#global-notif-content').unbind('click').bind('click', function(){
                    return false;
                });
                jQ('#global-notif-see-all').unbind('click').bind('click', function(){
                    document.location = global.settings.notif_url;
                });
            }
        },
        countNotif: function() {

            global.ajaxCancel('countUserNotif');
            var settings = {
                url: global.settings.countNotif_url,
                type: 'GET',
                error: function(xhr, responseText) {
                    if(responseText !== 'abort' && responseText !== 'error') {
                        alert(responseText);
                    }
                },
                success: function(json) {
                    if(json.success) {
                        jQ('#global-notif-ctr').html(json.ctr);
                    } else {
                        location.reload();
                    }
                }
            };
            global.ajax(settings, 'countUserNotif');
        },
        getNotif: function() {

            global.ajaxCancel('getUserNotif');
            var notifListCtnr = jQ('#global-notif-list-container'),
                settings = {
                    url: global.settings.notifList_url,
                    type: 'GET',
                    error: function(xhr, responseText) {
                        if(responseText !== 'abort' && responseText !== 'error') {
                            alert(responseText);
                        }
                    },
                    beforeSend: function() {
                        notifListCtnr.html('').addClass('global-notif-loading');
                    },
                    success: function(json) {
                        if(json.success) {
                            notifListCtnr.removeClass('global-notif-loading').html(json.html);
                            global.doSeenNotif();
                        } else {
                            location.reload();
                        }
                    }
                };
            global.ajax(settings, 'getUserNotif');
        },
        doSeenNotif: function() {

            global.ajaxCancel('doSeenUserNotif');
            var settings = {
                url: global.settings.doSeenNotif_url,
                type: 'GET',
                error: function(xhr, responseText) {
                    if(responseText !== 'abort' && responseText !== 'error') {
                        alert(responseText);
                    }
                },
                success: function(json) {
                    if(json.success) {
                        global.countNotif();
                    } else {
                        location.reload();
                    }
                }
            };
            global.ajax(settings, 'doSeenUserNotif');
        },
        bindFormSubmitted: function() {
            if(jQ('form').length > 0) {
                jQ('form').unbind('submit.submitted').bind('submit.submitted', this.formSubmitted);
                this.maskInput();
                this.askContinue();
                this.justContinue();
            }
        },

        maskInput: function() {
            if(jQ('.date').length > 0) jQ('.date').mask('99/99/9999').datepicker({
                changeMonth: true,
                changeYear: true
            });
            
            if(jQ('.amount').length > 0) jQ('.amount').maskMoney();
            if(jQ('.quantity').length > 0) jQ('.quantity').maskMoney({precision: 0});
            if(jQ('.year').length > 0) jQ('.year').mask('99');
            if(jQ('.month').length > 0) jQ('.month').mask('9999');
            if(jQ('.fax').length > 0) jQ('.fax').mask('+1 (999) 999-9999');
            if(jQ('.numeric').length > 0) {
                jQ('.numeric').focus(function(e){
                    jQ(this).attr('placeholder', '0');
                }).blur(function(e){
                    jQ(this).attr('placeholder', '');
                });
                jQ(".numeric").keypress(function (e) {
                    if (e.which !== 8 && e.which !== 0 && (e.which < 48 || e.which > 57)) {
                        return false;
                    }
                });
            }
        },
        askContinue: function() {
            if(jQ('.ask-continue').length > 0) {
                jQ('.ask-continue').unbind('click.askContinue').unbind('click.justContinue').bind('click.askContinue', function(e) {
                    var conf = confirm(jQ(this).data('message'));
                    console.log(conf);
                    if(!conf) {
                        //Fixed for modal
                        e.stopImmediatePropagation();
                        return false;
                    } else {
                        if(jQ('.form-action').length > 0) jQ('.form-action').val(jQ(this).val());
                    }
                });
            }
        },
        justContinue: function() {
            if(jQ('.just-continue').length > 0) {
                jQ('.just-continue').unbind('click.justContinue').unbind('click.askContinue').bind('click.justContinue', function() {
                    if(jQ('.form-action').length > 0) jQ('.form-action').val(jQ(this).val());
                });
            }
        },
        formSubmitted: function() {
            if(jQ('.button-container').length > 0) {
                jQ('.button-container').children().each(function() {
                    if(jQ(this).is('a')) {
                        jQ(this).data('href', jQ(this).attr('href')).removeAttr('href').addClass('disabled');
                    } else {
                        jQ(this).prop('disabled', true).addClass('disabled');
                    }
                });
            }
        },
        formSubmittedReverse: function() {
            if(jQ('.button-container').length > 0) {
                jQ('.button-container').children().each(function() {
                    if(jQ(this).is('a')) {
                        jQ(this).attr('href', jQ(this).data('href')).removeClass('disabled');
                    } else {
                        jQ(this).prop('disabled', false).removeClass('disabled');
                    }
                });
            }
        },
        backToTop: function() {
            if(jQ('.back-to-top-container').length > 0) {
                jQ(window).scroll(function(){
                    if(jQ(window).scrollTop() > 150) {
                        jQ('.back-to-top-container').fadeIn('slow');
                    } else {
                        jQ('.back-to-top-container').fadeOut('slow');
                    }
                });
                jQ('.back-to-top-container a').bind('click', function(){
                    jQ('html, body').stop().animate({scrollTop: 0}, 500);
                });
            }
        },
        ajax: function( settings, requestName ) {

            var required = {
                type    : 'POST',
                dataType: 'json',
                error: function(xhr, responseText, errorThrown) {
                }
            };

            settings = jQ.fn.extend( required, settings );

            this.settings.ajaxRequest[requestName] = jQ.ajax( settings );
        },
        ajaxCancel: function(ajaxCallName) {

            for(var prop in this.settings.ajaxRequest) {
                if(ajaxCallName.indexOf(prop) > -1 && global.settings.ajaxRequest[prop] !== undefined) {
                    global.settings.ajaxRequest[prop].abort();
                }
            }
        },
        dataTableResponsiveCallBack: function(api, rowIdx, callBack) {

            var data = api.cells( rowIdx, ':hidden' ).eq(0).map( function ( cell ) {
                var header = jQ( api.column( cell.column ).header() );
                var idx = api.cell( cell ).index();

                if ( header.hasClass( 'control' ) || header.hasClass( 'never' ) ) {
                    return '';
                }

                // Use a non-public DT API method to render the data for display
                // This needs to be updated when DT adds a suitable method for
                // this type of data retrieval
                var dtPrivate = api.settings()[0];
                var cellData = dtPrivate.oApi._fnGetCellData(
                    dtPrivate, idx.row, idx.column, 'display'
                );
                var title = header.text();
                if ( title ) {
                    title = title + ':';
                }

                return '<li data-dtr-index="'+idx.column+'">'+
                    '<span class="dtr-title">'+
                    title+
                    '</span> '+
                    '<span class="dtr-data">'+
                    cellData+
                    '</span>'+
                    '</li>';
            } ).toArray().join('');

            return data ?
            { append: jQ('<ul data-dtr-index="'+rowIdx+'"/>').append( data ), callBack: callBack } :
                false;
        },
        autocomplete: {
            processes: [],
            bind: function(url, el, hidEl, callBacks) {

                // To set additional parameters call jQ(element).devbridgeAutocomplete('setOptions', {params: {sampleParam: 'sampleParamValue'}});

                jQ(el).devbridgeAutocomplete({
                    serviceUrl: url,
                    dataType: 'json',
                    noCache: true,
                    showNoSuggestionNotice: true,
                    minChars: 0,
                    width: 'flex',
                    onSearchStart: function() {
                        jQ(this).removeClass('autocomplete-loading').addClass('autocomplete-loading');
                        if(typeof callBacks === 'object' && typeof callBacks.onSearchStart === 'function') {
                            callBacks.onSearchStart();
                        }
                        global.autocomplete.processes.push(el);
                        global.autocomplete.checkProcesses();
                    },
                    onSearchComplete: function() {
                        jQ(this).removeClass('autocomplete-loading');
                        if(jQ(this).val() === '') {
                            if(hidEl !== null) {
                                jQ(hidEl).val('');
                            }
                            if(!jQ(this).data('on-focus')) {
                                jQ(el).devbridgeAutocomplete('hide');
                            }
                        }
                        if(typeof callBacks === 'object' && typeof callBacks.onSearchComplete === 'function') {
                            callBacks.onSearchComplete();
                        }
                        global.autocomplete.removeProcess(el);
                    },
                    onSearchError: function() {
                        if(jQ(this).val() === '' && hidEl !== null) {
                            jQ(hidEl).val('');
                        }
                        if(typeof callBacks === 'object' && typeof callBacks.onSearchError === 'function') {
                            callBacks.onSearchError();
                        }
                        global.autocomplete.removeProcess(el);
                    },
                    onSelect: function(s) {
                        if(hidEl !== null) {
                            jQ(hidEl).val(s.id);
                        }
                        if(typeof callBacks === 'object' && typeof callBacks.onSelect === 'function') {
                            callBacks.onSelect(s);
                        }
                        global.autocomplete.removeProcess(el);
                    }
                });

                jQ(el).unbind('keyup.checkEmpty').bind('keyup.checkEmpty', function(){
                    if(jQ(this).val() === '') {
                        jQ(this).removeClass('autocomplete-loading');
                        if(hidEl !== null) {
                            jQ(hidEl).val('');
                        }
                        jQ(el).devbridgeAutocomplete('hide');
                        global.autocomplete.removeProcess(el);
                        if(typeof callBacks === 'object' && typeof callBacks.checkEmpty === 'function') {
                            callBacks.checkEmpty();
                        }
                    }
                }).unbind('focus.checkFocus').bind('focus.checkFocus', function(){
                    jQ(this).data('onFocus', true);
                }).unbind('keydown.checkFocus').bind('keydown.checkFocus', function(){
                    jQ(this).data('onFocus', false);
                });
            },
            removeProcess: function(el) {

                for(var i=0; i < global.autocomplete.processes.length; i++) {
                    if(global.autocomplete.processes[i] === el) {
                        global.autocomplete.processes.splice(i, 1);
                    }
                }

                global.autocomplete.checkProcesses();
            },
            checkProcesses: function() {

                if(global.autocomplete.processes.length > 0) {
                    global.formSubmitted();
                } else {
                    global.formSubmittedReverse();
                }
            }
        },
        parseNum: function(n) {
            n = n.toString();
            var num = parseFloat(n.replace(/,/,''));
            return num==null || num==undefined || !isFinite(num) || isNaN(num) ? 0 : num;
        },
        numWithCommas: function(x) {
            return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        },
        numWithCommasAndDecimal: function(x){
            let num = global.parseNum(x);
            let numWithDecimal = num.toFixed(2);
            return global.numWithCommas(numWithDecimal)
        },
        parseFlashMessages: function(containerId, type, messages) {
            var divMessages = '';
            jQ.each(messages, function(index, value){
                divMessages += '<div>' + value + '</div>';
            });
            var fiIcon = type === 'success' ? 'fi-check fa fa-check' : 'fi-x-circle fa fa-times',
                _html = '<div class="' + type + ' callout flash-messages flash-messages-dynamic">' +
                    '<i class="' + fiIcon + '"></i>' +
                    divMessages +
                    '<button class="close-button flash-messages-close-button" aria-label="Dismiss alert" type="button">' +
                    '<span aria-hidden="true">&times;</span>' +
                    '</button>' +
                    '</div>';
            jQ(containerId).html(_html);
            jQ('.flash-messages-close-button').unbind('click').bind('click', function(){
                jQ('.flash-messages-dynamic').fadeOut(300);
            });
            setTimeout(function(){
                if(jQ('.flash-messages-close-button').length > 0) jQ('.flash-messages-close-button').click();
            }, 10000);
        },
        setCookie: function(cname, cvalue, exdays) {
            const d = new Date();
            d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
            const expires = "expires=" + d.toUTCString();
            document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
        },
        createModal: function (modalId, modalContentId, size = 'medium') {
            var modal = jQ("<div>").attr({
                'class': 'reveal reveal-draggable ' + size,
                'id': modalId,
                'data-reveal': '',
            });
            var modalContent = jQ("<div>").attr({
                'id': modalContentId,
                'class': 'has-loading modal-content',
            });
            let closeBtn = jQ("<button>").attr({
                    'class': 'close-button',
                    'data-close': '',
                    'aria-label' : 'Close modal',
                    'type': 'button',
                }).html(jQ("<span>").attr({
                    'aria-hidden': 'true',
                }).html('&times;'));
            modalContent.appendTo(modal);
            closeBtn.appendTo(modal);
            modal.appendTo('body');
            global.initFoundation();
            global.draggableReveal();
        },
        draggableReveal: function(){
            setTimeout(function () {
                let draggable = jQ('.reveal-draggable'); //element
                draggable.on('mousedown', function(e){
                    if(e.target !== this){
                        return;
                    }
                    let dr = jQ(this).addClass("drag");
                    let height = dr.outerHeight();
                    let width = dr.outerWidth();
                    let ypos = dr.offset().top + height - e.pageY,
                        xpos = dr.offset().left + width - e.pageX;
                    jQ(document.body).on('mousemove', function(e){
                        let itop = e.pageY + ypos - height;
                        let ileft = e.pageX + xpos - width;
                        if(dr.hasClass("drag")){
                            dr.offset({top: itop,left: ileft});
                        }
                    }).on('mouseup', function(e){
                        dr.removeClass("drag");
                    });
                });
            }, 1000);
        },
        zapParseAmount: function(x){
            let val = x === '' ? '0' : x,
                val2 = val.replace(/,/g, '');
            return parseFloat(val2);
        },
        zapNumWithCommasAndDecimal: function(x){
            let numWithDecimal = x.toFixed(2);
            return global.numWithCommas(numWithDecimal)
        },
        flashMessage: function(type, messages, autoClose = true, closeDelay = 10000) {
            var divMessages = '';
            jQ.each(messages, function(index, value){
                divMessages += '<div>' + value + '</div>';
            });
            var fiIcon = type === 'success' ? 'fi-check fa fa-check' : 'fi-x-circle fa fa-times',
                _html = '<div class="' + type + ' callout flash-messages flash-messages-dynamic" style="display: none;">' +
                    '<i class="' + fiIcon + '"></i>' +
                    divMessages +
                    '<button class="close-button flash-messages-close-button" aria-label="Dismiss alert" type="button">' +
                    '<span aria-hidden="true">&times;</span>' +
                    '</button>' +
                    '</div>';
            jQ('#flash-messages2').html(_html);
            jQ('.flash-messages-dynamic').slideDown();
            jQ('.flash-messages-close-button').unbind('click').bind('click', function(){
                jQ('.flash-messages-dynamic').fadeOut(300);
            });
            if(autoClose) {
                setTimeout(function () {
                    if (jQ('.flash-messages-close-button').length > 0) jQ('.flash-messages-close-button').click();
                }, closeDelay);
            }
        },
    };