(function(jQ, window){

    'use strict';

    jQ.RxGrabMainMenu = function(self) {
        this.$self = self;
        this._init();
    };

    jQ.RxGrabMainMenu.defaults = {
        isOpen: false,
        //slideSpeed: 500,
        hideClass: 'rxgrab-main-menu-hide',
        container: null
    };

    jQ.RxGrabMainMenu.prototype = {
        _init: function(self) {
            this.options = jQ.RxGrabMainMenu.defaults;
            var that = this;
            this.options.container = jQ(this.$self.data('content-id'));
            this.$self.unbind('click').bind('click', function(){ that.onClick() });
        },
        onClick: function() {
            if(this.options.isOpen) this.close(); else this.open();
        },
        open: function() {
            this.options.isOpen = true;
            this.$self.addClass(this.options.hideClass);
            //this.options.container.slideDown(this.options.slideSpeed);
            this.options.container.toggle('fade', 200);
        },
        close: function() {
            this.options.isOpen = false;
            this.$self.removeClass(this.options.hideClass);
            //this.options.container.slideUp(this.options.slideSpeed);
            this.options.container.toggle('fade', 200);
        }
    };

    jQ.fn.RxGrabMainMenu = function() {

        var instance = jQ.data(this, 'RxGrabMainMenu');

        if(!instance) {
            instance = jQ.data(this, 'RxGrabMainMenu', new jQ.RxGrabMainMenu(this));
        }

        return instance;
    };

    /* ------------------------------------------------------------------------------------------------------------------------------------------------------- */

    jQ.RxGrabMainTabs = function(self) {
        this.$self = self;
        this._init();
    };

    jQ.RxGrabMainTabs.defaults = {
        selectedTab: null,
        selectedTabContent: null,
        defaultSelectedTabId: null,
        defaultTabsCount: 0,
        tabs: [],
        hasDropDown: false
    };

    jQ.RxGrabMainTabs.prototype = {
        _init: function() {
            this.options = jQ.extend( true, {}, jQ.RxGrabMainTabs.defaults);
            this.countDefaultTabs();
            this.responsive();
            this.bindTab();
            this.preSelectTab();
            this.winResize();
            this.doResponsive();
        },
        countDefaultTabs: function() {
            this.options.defaultTabsCount = this.$self.find('.rxgrab-main-tabs-tabs').length;
        },
        preSelectTab: function() {
            if(this.options.defaultSelectedTabId !== null) {
                this.selectTab(jQ(this.options.defaultSelectedTabId));
            } else if(this.options.selectedTab === null) {
                this.$self.find('div:first-child a').click();
            }
        },
        bindTab: function() {
            var that = this;
            this.$self.find('a:not(.rxgrab-main-tabs-dropdown-toggle)').unbind('click').bind('click', function(){ that.selectTab(jQ(this)) });
        },
        selectTab: function(el) {
            this.hideSelectedTab();
            this.options.selectedTab = el;
            this.options.selectedTabContent = jQ(el.data('id'));
            this.showSelectedTab();
        },
        hideSelectedTab: function() {
            if(this.options.selectedTab !== null && this.options.selectedTab !== 'undefined') this.options.selectedTab.parent().removeClass('active');
            if(this.options.selectedTabContent !== null && this.options.selectedTabContent !== 'undefined') this.options.selectedTabContent.removeClass('active');
        },
        showSelectedTab: function() {
            if(this.options.selectedTab !== null && this.options.selectedTab !== 'undefined') this.options.selectedTab.parent().addClass('active');
            if(this.options.selectedTabContent !== null && this.options.selectedTabContent !== 'undefined') this.options.selectedTabContent.addClass('active');
        },
        newTab: function(el) {
            if(jQ('#'+el.data('id')).length>0) {
                jQ('#'+el.data('id')).click();
                this.doResponsive();
                return false;
            } else {
                var tabDiv = document.createElement('div');
                tabDiv.className = 'rxgrab-main-tabs-tabs active';
                tabDiv.innerHTML = '<a href="javascript:void(0)" id="' + el.data('id') + '" data-id="#' + el.data('id') + '-content">' + el.data('label') + '</a>';
                this.$self.children(':eq(0)').after(tabDiv);
                var tabDivContent = document.createElement('div');
                tabDivContent.className = 'active loading';
                tabDivContent.id = el.data('id') + '-content';
                jQ(this.$self.data('content-id')).append(tabDivContent);
                this.bindTab();

                var newTabInfo =  {
                    isDropDown: false,
                    width: jQ('#'+el.data('id')).parent().outerWidth(),
                    element: jQ('#'+el.data('id')).parent()
                };

                this.options.tabs.splice(this.options.defaultTabsCount, 0, newTabInfo);

                jQ('#'+el.data('id')).click();
                this.doResponsive();
                return true;
            }
        },
        refreshTab: function(RxGrabMainTabId) {
            if(jQ(RxGrabMainTabId).length>0) {
                jQ(RxGrabMainTabId+'-content').html('').addClass('loading');
                return true;
            } else {
                return false;
            }
        },
        winResize: function() {
            var that = this;
            jQ(window).resize(function() {
                that.doResponsive();
            });
        },
        responsive: function() {
            var that = this;
            that.$self.find('.rxgrab-main-tabs-tabs').each(function(){
                that.options.tabs.push({
                    isDropDown: false,
                    width: jQ(this).outerWidth(),
                    element: jQ(this)
                });
            });
        },
        doResponsive: function() {
            var referenceWidth = this.$self.width() - 100,
                calculatedWidth = 0;
            if(this.options.hasDropDown = true) {
                this.$self.find('.rxgrab-main-tabs-dropdown').remove();
                this.options.hasDropDown = false;
            }
            for(var i=0; i<this.options.tabs.length; i++) {
                if(calculatedWidth + this.options.tabs[i].width > referenceWidth) {
                    this.options.hasDropDown = true;
                    if(!this.options.tabs[i].isDropDown) {
                        this.options.tabs[i].isDropDown = true;
                        this.options.tabs[i].element.remove();
                    }
                } else {
                    if(this.options.tabs[i].isDropDown) {
                        this.options.tabs[i].isDropDown = false;
                        this.$self.append(this.options.tabs[i].element);
                    }
                }
                calculatedWidth += this.options.tabs[i].width;
            }
            if(this.options.hasDropDown) {
                var dropDownDiv = document.createElement('div');
                    dropDownDiv.className = 'rxgrab-main-tabs-dropdown';
                    dropDownDiv.innerHTML = '<div class="rxgrab-main-tabs-dropdown-toggle-container"><a href="javascript:void(0)" class="rxgrab-main-tabs-dropdown-toggle"><i class="fi-arrow-down"></i></a></div><div class="rxgrab-main-tabs-dropdown-content"></div>';
                var dropDownDivContent = this.$self.append(dropDownDiv).find('.rxgrab-main-tabs-dropdown-content');
                for(var i=0; i<this.options.tabs.length; i++) {
                    if(this.options.tabs[i].isDropDown) {
                        dropDownDivContent.append(this.options.tabs[i].element);
                    }
                }
                this.$self.find('.rxgrab-main-tabs-dropdown-toggle').unbind('click').bind('click', function(){
                    if(jQ(this).find('i').hasClass('fi-arrow-down')) {
                        jQ(this).find('i').removeClass('fi-arrow-down').addClass('fi-arrow-up');
                        dropDownDivContent.show();
                    } else {
                        jQ(this).find('i').removeClass('fi-arrow-up').addClass('fi-arrow-down');
                        dropDownDivContent.hide();
                    }
                });
            }
            this.bindTab();
        }
    };

    jQ.fn.RxGrabMainTabs = function(options) {

        var instance = jQ.data(this, 'RxGrabMainTabs');

        if(!instance) {
            instance = jQ.data(this, 'RxGrabMainTabs', new jQ.RxGrabMainTabs(this));
        }

        return instance;
    };

})(jQuery, window);

var jQ = jQuery.noConflict(),
    global = {
        url : null,
        ajaxRequest: [],
        RxGrabMainMenu: null,
        RxGrabMainTabs: null,
        lastScrollTop: 0,
        delayMouseWheel: false,
        winHeight: 0,
        bgNum: 0,
        bgName: null,
        scheduleRequestDataTable: null,
        init: function() {
            jQ(document).foundation();
            global.RxGrabMainMenu = jQ('#rxgrab-main-menu').RxGrabMainMenu();
            jQ('#rxgrab-main-menu-content-close').unbind('click').bind('click', function() { global.RxGrabMainMenu.close() });
            global.RxGrabMainTabs = jQ('#rxgrab-main-tabs').RxGrabMainTabs();
            jQ('.rxgrab-main-tabs-link').unbind('click').bind('click', global.openModule);
            CKEDITOR.config.removePlugins = 'about';
        },
        maskDate: function () {
            jQ('.date').mask('99/99/9999').datepicker();
        },
        maskAmount: function() {
            jQ('.amount').maskMoney();
        },
        maskQuantity: function() {
            jQ('.quantity').maskMoney({precision: 0});
        },
        ajax: function( settings, requestName ) {

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

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

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

            for(var prop in global.ajaxRequest) {
                if(ajaxCallName.indexOf(prop) > -1 && global.ajaxRequest[prop] !== undefined) global.ajaxRequest[prop].abort();
            }
        },
        open_modal: function(id) {
            jQ('#'+id).foundation('reveal', 'open');
        },
        open_modal_ajax: function(id, settings) {
            jQ('#'+id).foundation('reveal', 'open', settings);
        },
        close_modal: function(id) {
            jQ('#'+id).foundation('reveal', 'close');
        },
        openModule: function() {

            if(global.RxGrabMainTabs.newTab(jQ(this))) {

                var that = jQ(this);

                that.addClass('rxgrab-loading-module');

                var RxGrabMainTabId = '#'+jQ(this).data('id'),
                    data = {
                        RxGrabMainTabId: RxGrabMainTabId
                    },
                    settings = {
                        url     : jQ(this).data('url'),
                        data    : data,
                        success : function(json) {

                            if(json.success) {
                                global.RxGrabMainMenu.close();
                                jQ(RxGrabMainTabId+'-content').removeClass('loading').html(json.html);

                                if(json.javascripts !== undefined) {

                                    for(i=0; i<json.javascripts.length; i++) {
                                       jQ.getScript(global.url+'/bundles/rxgrab/'+json.javascripts[i]);
                                    }
                                }

                            } else
                                alert(json.message);

                            that.removeClass('rxgrab-loading-module');
                        }
                    };
                global.ajax(settings, 'normal');
            }
        },
        refreshModule: function() {
            global.doRefreshModule(jQ(this).data('rx-grab-main-tab-id'));
        },
        doRefreshModule: function(RxGrabMainTabId) {

            if(global.RxGrabMainTabs.refreshTab(RxGrabMainTabId)) {

                var data = {
                        RxGrabMainTabId: RxGrabMainTabId
                    },
                    settings = {
                        url     : jQ(RxGrabMainTabId+'-link').data('url'),
                        data    : data,
                        success : function(json) {

                            if(json.success) {

                                jQ(RxGrabMainTabId+'-content').removeClass('loading').html(json.html);

                                if(json.javascripts !== undefined) {

                                    for(i=0; i<json.javascripts.length; i++) {
                                        jQ.getScript(global.url+'/bundles/rxgrab/'+json.javascripts[i]);
                                    }
                                }

                            } else
                                alert(json.message);
                        }
                    };
                global.ajax(settings, 'normal');
            }
        },
        doAlertMessages: function(messages) {

            jQ('#global-alert-modal-message').html(messages.replace(/\n/g, "<br/>"));
            global.open_modal('global-alert-modal');
        },
        form: function() {

            global.doForm(jQ(this).data('rx-grab-main-tab-id'), jQ(this).data('container-id'), jQ(this).data('url'), jQ(this).data('action'), jQ(this).data('id'));
        },
        doForm: function(RxGrabMainTabId, containerId, url, action, id) {

            jQ(containerId).html('').addClass('loading');

            var data = {
                    RxGrabMainTabId: RxGrabMainTabId,
                    containerId: containerId,
                    url: url,
                    action: action,
                    id: id
                },
                settings = {
                    url     : url,
                    data    : data,
                    error   : function(xhr) {
                    },
                    success : function(json) {

                        if(json.success) {

                            jQ(containerId).removeClass('loading').html(json.html);

                            if(json.javascripts !== undefined) {

                                for(i=0; i<json.javascripts.length; i++) {
                                    jQ.getScript(global.url+'/bundles/rxgrab/'+json.javascripts[i]);
                                }
                            }

                        } else
                            alert(json.message);
                    }
                };
            global.ajax(settings, 'normal');
        },
        formSave: function() {

            var formId = jQ(this).data('form-id');

            jQ(formId).find('.ckeditor').each(function(){
                var ckeditorInstance = CKEDITOR.instances[jQ(this).attr('id')];
                jQ(this).val(ckeditorInstance.getData());
            });

            global.disableFormActions(formId);

            var settings = {
                    url     : jQ(this).data('url'),
                    data    : jQ(formId).serialize(),
                    error   : function(xhr) {
                        //console.log(xhr.responseText);
                        global.enableFormActions(formId);
                    },
                    success : function(json) {
                        global.doAlertMessages(json.message);
                        if(json.success) {
                            if(json.stay !== undefined && json.stay)
                                global.doForm(json.RxGrabMainTabId, json.containerId, json.url, json.action, json.id);
                            else
                                global.doRefreshModule(json.RxGrabMainTabId);
                        } else
                            global.enableFormActions(formId);
                    }
                };
            global.ajax(settings, 'normal');
        },
        fileFormSave: function() {

            var that = jQ(this),
                formId = that.data('form-id');

            jQ(formId).find('.ckeditor').each(function(){
                var ckeditorInstance = CKEDITOR.instances[jQ(this).attr('id')];
                jQ(this).val(ckeditorInstance.getData());
            });

            var progressBarId = that.data('progress-bar-id'),
                formData = new FormData(jQ(formId)[0]);

            jQ.ajax({
                url: that.data('url'),  //Server script to process data
                type: 'POST',
                xhr: function() {  // Custom XMLHttpRequest
                    var myXhr = jQ.ajaxSettings.xhr();
                    if(myXhr.upload){ // Check if upload property exists
                        myXhr.upload.addEventListener('progress', function(e) {
                            if(e.lengthComputable){
                                var percentComplete = (e.loaded / e.total) * 100;
                                jQ(progressBarId + ' span').width(percentComplete+'%');
                            }
                        }, false); // For handling the progress of the upload
                    }
                    return myXhr;
                },
                //Ajax events
                beforeSend: function() {

                    jQ(progressBarId).show();
                    jQ(progressBarId + ' span').width('0%');
                    global.disableFormActions(formId);
                },
                success: function(json) {
                    global.doAlertMessages(json.message);
                    if(json.success) {
                        if(json.stay !== undefined && json.stay)
                            global.doForm(json.RxGrabMainTabId, json.containerId, json.url, json.action, json.id);
                        else
                            global.doRefreshModule(json.RxGrabMainTabId);
                    } else {
                        jQ(progressBarId).hide();
                        global.enableFormActions(formId);
                    }

                },
                error: function(xhr, response_text) {
                    jQ(progressBarId).hide();
                    global.enableFormActions(formId);
                },
                // Form data
                data: formData,
                //Options to tell jQuery not to process data or worry about content-type.
                cache: false,
                contentType: false,
                processData: false
            });
        },
        formDelete: function() {

            if(confirm('Are you sure you want to delete this record?')) {

                var RxGrabMainTabId = jQ(this).data('rx-grab-main-tab-id');

                global.addContainerLoading(RxGrabMainTabId+'-content');

                var data = {id: jQ(this).data('id')},
                    settings = {
                    url     : jQ(this).data('url'),
                    data    : data,
                    error   : function() {
                        global.removeContainerLoading(RxGrabMainTabId+'-content');
                    },
                    success : function(json) {
                        alert(json.message);
                        if(json.success)
                            global.doRefreshModule(RxGrabMainTabId);
                        else
                            global.removeContainerLoading(RxGrabMainTabId+'-content');
                    }
                };
                global.ajax(settings, 'normal');
            }
        },
        formAction: function() {

            var action = jQ(this).data('action');

            if(confirm('Are you sure you want to ' + action + ' this record?')) {

                var RxGrabMainTabId = jQ(this).data('rx-grab-main-tab-id');

                global.addContainerLoading(RxGrabMainTabId+'-content');

                var data = {id: jQ(this).data('id'), action: action},
                    settings = {
                        url     : jQ(this).data('url'),
                        data    : data,
                        error   : function() {
                            global.removeContainerLoading(RxGrabMainTabId+'-content');
                        },
                        success : function(json) {
                            alert(json.message);
                            if(json.success)
                                global.doRefreshModule(RxGrabMainTabId);
                            else
                                global.removeContainerLoading(RxGrabMainTabId+'-content');
                        }
                    };
                global.ajax(settings, 'normal');
            }
        },
        openSubModule: function() {
            global.doOpenSubModule(jQ(this).data('container-id'), jQ(this).data('sub-module-url'), jQ(this).data('ref-id'), jQ(this).data('type'), jQ(this).data('ajax-call-name'));
        },
        doOpenSubModule: function(containerId, subModuleUrl, refId, type, ajaxCallName) {

            if(ajaxCallName !== undefined && ajaxCallName !== '' && global.ajaxRequest[ajaxCallName] !== undefined) global.ajaxCancel(ajaxCallName);

            jQ(containerId).html('').addClass('loading');

            var data = {
                    containerId: containerId,
                    refId: refId,
                    type: type,
                    subModuleUrl: subModuleUrl,
                    ajaxCallName: ajaxCallName !== undefined && ajaxCallName !== '' ? ajaxCallName : 'normal'
                },
                settings = {
                    url     : subModuleUrl,
                    data    : data,
                    error   : function(xhr, responseText) {
                        jQ(containerId).removeClass('loading');
                    },
                    success : function(json) {

                        jQ(containerId).removeClass('loading');

                        if(json.success) {

                            jQ(containerId).html(json.html);

                            if(json.javascripts !== undefined) {

                                for(i=0; i<json.javascripts.length; i++) {
                                    jQ.getScript(global.url+'/bundles/rxgrab/'+json.javascripts[i]);
                                }
                            }

                        } else
                            alert(json.message);
                    }
                };

            global.ajax(settings, ajaxCallName !== undefined && ajaxCallName !== '' ? ajaxCallName : 'normal');
        },
        subModuleForm: function() {
            global.doSubModuleForm(jQ(this).data('container-id'), jQ(this).data('form-url'), jQ(this).data('sub-module-url'), jQ(this).data('ref-id'), jQ(this).data('type'), jQ(this).data('action'), jQ(this).data('id'), jQ(this).data('ajax-call-name'));
        },
        doSubModuleForm: function(containerId, formUrl, subModuleUrl, refId, type, action, id, ajaxCallName) {

            if(ajaxCallName !== undefined && ajaxCallName !== '' && global.ajaxRequest[ajaxCallName] !== undefined) global.ajaxCancel(ajaxCallName);

            jQ(containerId).html('').addClass('loading');

            var data = {
                    containerId: containerId,
                    refId: refId,
                    type: type,
                    action: action,
                    id: id,
                    formUrl: formUrl,
                    subModuleUrl: subModuleUrl,
                    ajaxCallName: ajaxCallName !== undefined && ajaxCallName !== '' ? ajaxCallName : 'normal'
                },
                settings = {
                    url     : formUrl,
                    data    : data,
                    error   : function() {
                        jQ(containerId).removeClass('loading');
                    },
                    success : function(json) {

                        jQ(containerId).removeClass('loading');

                        if(json.success) {

                            jQ(containerId).html(json.html);

                            if(json.javascripts !== undefined) {

                                for(i=0; i<json.javascripts.length; i++) {
                                    jQ.getScript(global.url+'/bundles/rxgrab/'+json.javascripts[i]);
                                }
                            }

                        } else
                            alert(json.message);
                    }
                };

            global.ajax(settings, ajaxCallName !== undefined && ajaxCallName !== '' ? ajaxCallName : 'normal');
        },
        subModuleFormSave: function() {

            var ajaxCallName = jQ(this).data('ajax-call-name'),
                formId = jQ(this).data('form-id');

            jQ(formId).find('.ckeditor').each(function(){
                var ckeditorInstance = CKEDITOR.instances[jQ(this).attr('id')];
                jQ(this).val(ckeditorInstance.getData());
            });

            global.disableFormActions(formId);

            var settings = {
                url     : jQ(this).data('url'),
                data    : jQ(formId).serialize(),
                error   : function(xhr) {
                    global.enableFormActions(formId);
                },
                success : function(json) {
                    global.doAlertMessages(json.message);
                    if(json.success) {
                        if(json.stayInForm) {
                            global.doSubModuleForm(json.containerId, json.formUrl, json.subModuleUrl, json.refId, json.type, json.action, json.id, ajaxCallName);
                        } else {
                            global.doOpenSubModule(json.containerId, json.subModuleUrl, json.refId, json.type, ajaxCallName);
                        }
                    } else {
                        global.enableFormActions(formId);
                    }
                }
            };

            global.ajax(settings, ajaxCallName !== undefined && ajaxCallName !== '' ? ajaxCallName : 'normal');
        },
        subModuleFileFormSave: function() {

            var that = jQ(this),
                ajaxCallName = that.data('ajax-call-name'),
                formId = that.data('form-id');

            jQ(formId).find('.ckeditor').each(function(){
                var ckeditorInstance = CKEDITOR.instances[jQ(this).attr('id')];
                jQ(this).val(ckeditorInstance.getData());
            });

            var progressBarId = that.data('progress-bar-id'),
                formData = new FormData(jQ(formId)[0]);

            jQ.ajax({
                url: that.data('url'),  //Server script to process data
                type: 'POST',
                xhr: function() {  // Custom XMLHttpRequest
                    var myXhr = jQ.ajaxSettings.xhr();
                    if(myXhr.upload){ // Check if upload property exists
                        myXhr.upload.addEventListener('progress', function(e) {
                            if(e.lengthComputable){
                                var percentComplete = (e.loaded / e.total) * 100;
                                jQ(progressBarId + ' span').width(percentComplete+'%');
                            }
                        }, false); // For handling the progress of the upload
                    }
                    return myXhr;
                },
                //Ajax events
                beforeSend: function() {

                    jQ(progressBarId).show();
                    jQ(progressBarId + ' span').width('0%');
                    global.disableFormActions(formId);
                },
                success: function(json) {
                    global.doAlertMessages(json.message);
                    if(json.success) {
                        if(json.stayInForm) {
                            global.doSubModuleForm(json.containerId, json.formUrl, json.subModuleUrl, json.refId, json.type, json.action, json.id, ajaxCallName);
                        } else {
                            global.doOpenSubModule(json.containerId, json.subModuleUrl, json.refId, json.type, ajaxCallName);
                        }
                    } else {
                        jQ(progressBarId).hide();
                        global.enableFormActions(formId);
                    }
                },
                error: function(xhr, response_text) {
                    jQ(progressBarId).hide();
                    global.enableFormActions(formId);
                },
                // Form data
                data: formData,
                //Options to tell jQuery not to process data or worry about content-type.
                cache: false,
                contentType: false,
                processData: false
            });
        },
        subModuleFormDelete: function() {

            if(confirm('Are you sure you want to delete this record?')) {

                var ajaxCallName = jQ(this).data('ajax-call-name'),
                    containerId = jQ(this).data('container-id');

                global.addContainerLoading(containerId);

                var data = {
                        containerId: jQ(this).data('container-id'),
                        type: jQ(this).data('type'),
                        refId: jQ(this).data('ref-id'),
                        subModuleUrl: jQ(this).data('sub-module-url'),
                        id: jQ(this).data('id')
                    },
                    settings = {
                        url     : jQ(this).data('form-delete-url'),
                        data    : data,
                        error   : function() {
                            global.removeContainerLoading(containerId);
                        },
                        success : function(json) {
                            alert(json.message);
                            global.removeContainerLoading(json.containerId);
                            if(json.success)
                                global.doOpenSubModule(json.containerId, json.subModuleUrl, json.refId, json.type, ajaxCallName);
                        }
                    };

                global.ajax(settings, ajaxCallName !== undefined && ajaxCallName !== '' ? ajaxCallName : 'normal');
            }
        },
        submitLoading: function() {
            var div = document.createElement('div');
            div.className = 'container-loading';
            div.innerHTML = "<div>&nbsp;</div>";
            jQ(this).parent().append(div);
        },
        disableFormActions: function(formId) {
            jQ(formId).find(':button').prop('disabled', true);
        },
        enableFormActions: function(formId) {
            jQ(formId).find(':button').prop('disabled', false);
        },
        addContainerLoading: function(containerId) {
            var div = document.createElement('div');
                div.className = 'container-loading';
                div.innerHTML = "<div>&nbsp;</div>";
            jQ(containerId).append(div);
        },
        removeContainerLoading: function(containerId) {
            jQ(containerId).find('.container-loading').remove();
        },
        parseNum: function(n) {
            var num = parseFloat(n);
            return num==null || num==undefined || !isFinite(num) || isNaN(num) ? 0 : num;
        },
        dt_responsive_callBack: 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;
        },
        init_bg: function(bgName, bgNum) {
            global.bgName = bgName;
            global.bgNum = bgNum;
            jQ(document).bind('keydown.winKeyDown', global.win_keydown);
            jQ(window).bind('resize.winResize', global.win_resize).bind('mousewheel.winMousewheel DOMMouseScroll.winMousewheel', global.win_mousewheel);
            global.win_resize();
        },
        scroll_to: function(target) {
            target = jQ('#'+target);
            if(target.offset() !== undefined)
                jQ('html,body').animate({
                    scrollTop: target.offset().top - 45
                }, 600);
            return false;
        },
        win_mousewheel: function(e) {

            if(global.bgNum>1 && !global.delayMouseWheel) {

                global.delayMouseWheel = true;

                setTimeout(function(){
                    global.delayMouseWheel = false;
                }, 500);

                if(e.originalEvent.wheelDelta /120 > 0) {
                    global.do_win_keydown(38);
                }
                else{
                    global.do_win_keydown(40);
                }
            }
        },
        win_resize: function() {
            global.winHeight = jQ(window).height() - 45;
            jQ('.'+global.bgName).css('min-height', global.winHeight+'px').css('min-width', jQ(window).width()+'px');
        },
        win_keydown: function(e) {
            if(global.bgNum>1) {
                global.do_win_keydown(e.keyCode);
            }
        },
        do_win_keydown: function(keyCode) {

            var top = jQ(window).scrollTop(),
                additionalHeight = 0,
                lessHeight = 0;

            if(keyCode==40) {

                for(var i=1; i<=global.bgNum; i++) {

                    additionalHeight += (jQ('#'+global.bgName+i).innerHeight() - global.winHeight);

                    if(top<((global.winHeight*i) + additionalHeight)) {
                        global.scroll_to(global.bgName+(i+1));
                        break;
                    }
                }

            } else if (keyCode==38) {

                for(var i=global.bgNum; i>=1; i--) { additionalHeight += (jQ('#'+global.bgName+i).innerHeight() - global.winHeight); }

                for(var i=global.bgNum; i>=1; i--) {

                    lessHeight += (jQ('#'+global.bgName+i).innerHeight() - global.winHeight);

                    if(i==1) {
                        if(top<=(global.winHeight + (additionalHeight - lessHeight))) {
                            global.scroll_to(global.bgName+i);
                            break;
                        }
                    } else if(top>((global.winHeight*(i-2)) + (additionalHeight - lessHeight)) && top<((global.winHeight*(i-1)) + ((additionalHeight + 45) - lessHeight))) {
                        global.scroll_to(global.bgName+(i-1));
                        break;
                    }
                }
            }
        }
    };