Your IP : 18.219.40.177


Current Path : /usr/local/mgr5/skins/orion/src/
Upload File :
Current File : //usr/local/mgr5/skins/orion/src/App.ActionHandler.js

/**
 *  Модуль.
 *  ваш К.О.
 *  @param {object} window  global object
 *  @param {function} $ jQuery library
 *  @param {object} EventMgr EventMgr library
 *  @param {object} App Application
 */
App.ActionHandler = function(window, $, EventMgr, App) {
  'use strict';
  var init = function() {
    EventMgr.onwithdata($content(), actionBtnSel, 'click', 'menuAction',
        actionController);
    EventMgr.on($content(), formBtnFunc, 'click', actionFormController);
    EventMgr.on($content(), cancelDefActionNonActSel, 'click', cancelDefAct);
    EventMgr.on($content(), reloadTabBtnSel, 'click', reloadTabController);
    EventMgr.on('#main-wrapper', formSubmitSel, 'click', submitForm);
    EventMgr.on($content(), ticketRate, 'click', ticketRateHandler);
    EventMgr.bind('rateResponse', rateResponseHandler);
//    EventMgr.onwithdata('#main-wrapper', formSubmitSel, 'click', 'formSubmit',
//        submitForm);
    EventMgr.bind('failedAjaxResponseForDashboard',
        failedDashboardBlockRequestHandler);
    EventMgr.bind('failMenuAjaxResponse', failMenuRequest);
    EventMgr.bind('failCommonAjaxResponse', failListRequest);
    EventMgr.bind('failFormAjaxResponse', failFormRequest);
    EventMgr.bind('tabLoading', tabLoadingHandler);
    EventMgr.bind('tabLoadingHide', tabLoadingHideHandler);
    EventMgr.on($content(), dismissMsgSelector, 'click', dismissMessage);
  },

      $content = function() {
        return $('#main-wrapper');
      },

      // wrapper for right menu links
      actionBtnSel = '.m-item a, .b-menu-item',

      //wrapper for reload tab btn
      reloadTabBtnSel = '.reload',
      // wrapper for toolbar's group btn

      //prevent default not active actions
      cancelDefActionNonActSel = '.notActive span',

      formSubmitSel = '.i-button_type_ok',

      formBtnFunc = '.i-button_type_func',

      dismissMsgSelector = '.i-message__dismiss-link',

      ticketRate = '.i-ticket__rate',

      cancelDefAct = function(e) {
        e.preventDefault();
      },

      tabLoadingId = {},

      tabLoadingHandler = function(e, data) {
        var tabId = data.tabId;
        clearTimeout(tabLoadingId[tabId]);
        tabLoadingId[tabId] = setTimeout(function() {
          $('#cont-' + tabId).addClass('loading');
        }, 350);
      },

      tabLoadingHideHandler = function(e, data) {
        var tabId = data.tabId;
        setTimeout(function() {
          clearTimeout(tabLoadingId[tabId]);
          $('#cont-' + tabId).removeClass('loading');
        }, 0);
        //for be sure what it fucking loading hide
        setTimeout(function() {
          $('#cont-' + tabId).removeClass('loading');
        }, 100);
        //for be defintly sure what it fucking loading hide
        setTimeout(function() {
          $('#cont-' + tabId).removeClass('loading');
        }, 200);
        //for be absolutly sure  what it fucking loading hide
        setTimeout(function() {
          $('#cont-' + tabId).removeClass('loading');
        }, 350);
      },
      //handler for failed request from menu
      failMenuRequest = function(e, data) {
        $('.m-item.loading').removeClass('loading');
        if (data.erType === 'json') {
          EventMgr.trigger('pullMsg', { msg: 'JSON Parse Error. Func: "' + data.param.func + '"' });
        } else if (data.erMsg) {
          EventMgr.trigger('pullMsg', { msg: data.erMsg });
        } else {
          EventMgr.trigger('pullMsg', { msg: 'Request failed. Try again. Func: "' + data.param.func + '"' });
        }
      },
      //handler for failed request from list
      failListRequest = function(e, data) {
        var tabId = (data.invar) ? (data.invar.tabId) ? data.invar.tabId :
            (data.invar.parent) ? data.invar.parent :
                (data.invar.targetTabId) : undefined;
        EventMgr.trigger('tabLoadingHide', { tabId: tabId });
        if (data.erType === 'json') {
          EventMgr.trigger('pullMsg', { msg: 'JSON Parse Error. Func: "' + data.param.func + '"' });
        } else if (data.erMsg) {
          EventMgr.trigger('pullMsg', { msg: data.erMsg });
        } else {
          EventMgr.trigger('pullMsg', { msg: 'Request failed. Try again. Func: "' + data.param.func + '"' });
        }
      },

      disabledButton = function(btn) {
        btn.addClass('b-button_st_disabled');
        btn.html(btn.attr('data-disabled'));
      },

      resetButtonForDefault = function(arg) {
        //return btn state
        var btn, tabId;
        if (typeof arg === 'string') {
          tabId = arg;
          btn = $('#form-wrapper-' + tabId + ' .b-button_st_disabled'); 
        } else {
          btn = arg;
        }
        if (btn.length) {
          btn.html(btn[0].getAttribute('data-enabled'));
          btn.removeClass('b-button_st_disabled');
        }
      },
      //handler fot failed request from form
      failFormRequest = function(e, data) {
        var tabId = data.invar.tabId;

        if (data.erType === 'json') {
          EventMgr.trigger('pullMsg', { msg: 'JSON Parse Error. Func: "' + data.param.func + '"' });
        } else if (data.erMsg) {
          EventMgr.trigger('pullMsg', { msg: data.erMsg });
        } else {
          EventMgr.trigger('pullMsg', { msg: 'Request failed. Try again. Func: "' + data.param.func + '"' });
        }
        //reset button
        resetButtonForDefault(tabId);
        //for run after upload callback
        setTimeout(function() {
          //return progressbar state
          var loader = $('#' + tabId + '-progressbar .b-progressbar__loader');
          $('#' + tabId + '-progressbar')
              .removeClass('b-progressbar_type_withbtn');
          //remove animated
          loader.addClass('b-progressbar__loader_type_animate');
          //add static color
          loader.removeClass('b-progressbar__loader_type_static');
          loader.css('width', '');
          loader.html('');
          //remove cancel btn
          $('#' + tabId + '-progressbar .b-progressbar__btn-wr').remove();
        }, 1);

        EventMgr.trigger('tabLoadingHide', { tabId: tabId });
      },

      failedDashboardBlockRequestHandler = function(e, data) {
        var blockId = data.invar.blockId,
            tblock = App.Dom.byId('t' + blockId);
        if (tblock) {
          tblock.className = tblock.className.replace(/loading/g, '');
        }
        if (data.erType === 'json') {
          EventMgr.trigger('pullMsg', { msg: 'JSON Parse Error. Func: "' + data.param.func + '"' });
        } else if (data.erMsg) {
          EventMgr.trigger('pullMsg', { msg: data.erMsg });
        } else {
          EventMgr.trigger('pullMsg', { msg: 'Request failed. Try again. Func: "' + data.param.func + '"' });
        }
      },

      //reload page handler
      reloadTabController = function(e, data) {
        var tabId = '',
            addedParam = {};
        if (e) {
          tabId = this.getAttribute('data-tabid');
          addedParam = {
            clickstat: 'title'
          };
          e.preventDefault();
        } else {
          tabId = data.tabId;
        }
        EventMgr.trigger('reloadTab', {
          addedParam: addedParam,
          tabId: tabId,
          help: true,
          selid: true,
          filter: true });
      },

      ticketRateHandler = function(e) {
        var func = this.getAttribute('data-func'),
            type = this.getAttribute('data-type'),
            name = this.getAttribute('data-name'),
            $parent = this.parentNode,
            elid = $parent.getAttribute('data-id'),
            plid = $parent.getAttribute('data-elid'),
            param = {
              func: func,
              elid: elid,
              plid: plid
            };
        if (type === 'setrate') {
          EventMgr.trigger('ajaxRequest', {
            param: param,
            invar: {
              $parent: $parent,
              rateType: name,
              self: this
            },
            outtype: 'json',
            trfunc: 'rateResponse',
            failfunc: 'failCommonAjaxResponse'
          });
        } else if (type === 'rate') {
          EventMgr.trigger('ajaxRequest', {
            param: param,
            invar: {
              parent: $(this).closest('.tab-content_st_active').attr('data-tabid')
            },
            type: 'get',
            outtype: 'json',
            trfunc: 'ajaxResponse',
            failfunc: 'failCommonAjaxResponse',
            queue: 'noqueue' });
        }
      },

      rateResponseHandler = function(e, data) {
        if (!data.error) {
          $(data.$parent).addClass('b-ticket__rate_rated_' + data.rateType);
          $(data.self).removeClass('i-ticket__rate');
        } else if (data.erMsg) {
          EventMgr.trigger('pullMsg', { msg: data.erMsg });
        }
      },

      actionFormController = function(e) {
        var $self = $(this),
            func = $self.attr('data-func'),
            id = $self.attr('data-id'),
            tabId = $self.attr('data-tabid'),
            param = {
              func: func
            };
        //check for button id
        if (id && id !== 'undefined') {
          id = id.split('=', 2);
          if (id[1]) {
            param[id[0]] = id[1];
          }
        }
        EventMgr.trigger('ajaxRequest', {
          param: param,
          invar: {
            parent: tabId
          },
          type: 'get',
          outtype: 'json',
          trfunc: 'ajaxResponse',
          failfunc: 'failMenuAjaxResponse',
          queue: 'menu' });
        EventMgr.trigger('tabLoading', { tabId: tabId });

      },

      checkSameTabsOpened = function(func, tabs) {
        var resp = {
          exist: false,
          tabId: null,
          status: 0
        };
        var curFunc, regExpWitDot;
        if (func && tabs && typeof tabs === 'object') {
          /* jslint forin:true */
          for (var key in tabs) {
            if (tabs[key]) {
              curFunc = tabs[key].func;
              if (!curFunc && tabs[key].paramObjAll) {
                curFunc = tabs[key].paramObjAll.func;
              }
              //check if empty func like basket.empty
              //regExpWitDot = new RegExp('^' + func + '\\.');
              //.empty
              regExpWitDot = func + '.empty';
              //if ((String(curFunc).match(regExpWitDot) || curFunc === func) &&
              if ((regExpWitDot === curFunc || curFunc === func) &&
                  tabs[key].hType === 'parent') {
                resp.exist = true;
                resp.tabId = key;
                resp.status = tabs[key].status;
                //be sure that found active same tab
                if (resp.status === 1) {
                  break;
                }
              }
            }
          }
        }
        return resp;
      },

      //handler for menu action
      actionController = function(e, data) {
        var self = $(this),
            href = this.getAttribute('data-url'),
            parent = this.getAttribute('data-parent'),
            re = new RegExp('/?func=+'),
            cgi = this.getAttribute('data-cgi'),
            sameModule = false,
            queue = 'menu',
            isFromMenu = self.hasClass('i-menu-link'),
            fromFatalError = self.parent()
                .hasClass('b-fatal-error__refresh-link'),
            newtab = false,
            url, param;
        if (e.ctrlKey || e.metaKey || self.hasClass('newtab')) {
          newtab = true;
          queue = 'noqueue';
        }
        if (self.hasClass('wohan')) {
          return true;
        }
        //if from fatal error close alertBox
        if (fromFatalError) {
          $('#modal_alert_ok').trigger('click');
        }

        if (href) {
          if (href.match(re)) {
            url = cgi ? pageInfo.host + cgi : pageInfo.url;
            href = href.replace('?', '');
            param = App.Common.parseParams(href);
            param.clickstat = 'yes';
            //check for same module open from menu
            if (!newtab) {
              var actFunc = $('.tab-content_st_active').attr('data-func');
              if (param.func === actFunc) {
                sameModule = true;
              }
            }
            //check for exist tabs with this function
            var checkTabs = checkSameTabsOpened(param.func, data.__tabs);
            if (checkTabs.exist && !checkTabs.status && isFromMenu) {
              $('#switch-' + checkTabs.tabId).trigger('lclick');
              EventMgr.trigger('reloadTab', { tabId: checkTabs.tabId, resetFilterOn: true });
            } else {
              EventMgr.trigger('ajaxRequest', {
                url: url,
                param: param,
                invar: {
                  parent: parent, newtab: newtab, sameModule: sameModule, __src: 'menuAction', __src_func: param.func },
                type: 'get',
                outtype: 'json',
                trfunc: 'ajaxResponse',
                failfunc: 'failMenuAjaxResponse',
                queue: queue });
              //add loading class to menu
              self.parents('.m-item').addClass('loading');
            }
          } else {
            //what else?
            console.log(url);
          }
        }
        if (e) { e.preventDefault(); }
      },

      //handler for submit form
      submitForm = function(e, data) {
        e.preventDefault();
        var self = $(this),
            flags = self.getFlags(),
            tabId = self.attr('data-tabid'),
            form = $('#frm-' + tabId),
            vars = form.getVars(),
            action = form.attr('action'),
            param = form.serializeObject(),
            parent = self.attr('data-parent'),
            type = self.attr('data-type'),
            hasFiles = form.hasClass('withfiles'),
            act = self.attr('data-act'),
            id = self.attr('data-id'),
            isShowcaseForm = form.hasClass('b-form_showcase_yes'),
            name = self.attr('data-name'),
            progressTypeElem = App.Dom.byId(tabId + '-progresstype'),
            progressType, confirmMsg, RequiredMsg, progressid,
            param1, text, passwdField,
            pwstrength, options;
        //prevent dbclick
        if (self.hasClass('b-button_st_disabled')) {
          return false;
        }
        disabledButton(self);
        if (progressTypeElem !== null) {
          progressType = progressTypeElem.value;
        }
        //check for valid
        if (act !== 'back') {
          //check file length
          var fileSizeRes = App.u.checkFileSize(tabId);
          if (fileSizeRes.msg) {
            EventMgr.trigger('errMsgValid', {
              self: fileSizeRes.field,
              err: fileSizeRes.msg,
              number: 0
            });
            resetButtonForDefault(self);
            return false;
          }
          //check passwd confirm fields
          confirmMsg = checkConfirm(tabId);
          if (confirmMsg.msg !== '') {
            EventMgr.trigger('showAlert', confirmMsg);
            resetButtonForDefault(self);
            return false;
          }
          //check required fields
          RequiredMsg = checkRequired(tabId);
          if (RequiredMsg.msg !== '') {
            EventMgr.trigger('errMsgValid', {
              self: RequiredMsg.himself,
              err: RequiredMsg.msg,
              number: 0
            });
            //watching while input not be empty for remove error
            $(RequiredMsg.himself).bind('keyup', function() {
              if (this.value !== '') {
                $(this).unbind('keyup');
                EventMgr.trigger('okMsgValid', {
                  self: this,
                  number: 0,
                  notOk: true
                });
              }
            });
            resetButtonForDefault(self);
            return false;
          }
          //maybe it not needed
         // if ($('#frm-' + tabId +
         //     ' .row-error:not(".l-form__row_hidden_yes") input.test').length !== 0) {
         //   return false;
         // }
          //check password strength
          passwdField = $('#frm-' + tabId + ' input[data-check-field]');
          if (passwdField.length !== 0) {
            pwstrength = getPwdStrength(passwdField);
            var badPwd = false;
            passwdField.each(function() {
              var pname = this.getAttribute('name');
              if (pwstrength !== 0 &&
                  param[pname] !== '' &&
                  $(this).width() !== 0) {
                if (pwstrength > App.Forms.checkPassStrength(param[pname])) {
                  EventMgr.trigger('showAlert', { msg: pageInfo.pwErrorMsg });
                  badPwd = true;
                  return false;
                }
              }
            });
            if (badPwd) {
              resetButtonForDefault(self);
              return false;
            }
          }
        }

        if (act === 'back') {
          param.sback = 'ok';
          //not needed progress when press back btn
          progressType = 'false';
        }
        //check for button id
        if (id && id !== 'undefined') {
          id = id.split('=', 2);
          if (id[1]) {
            param[id[0]] = id[1];
          }
        }

        //add name of button
        if (name) {
          /* jslint camelcase: false */
          param.clicked_button = name;
          /* jslint camelcase: true */
        }
        //add progressid
        progressid = progressType;
        param.progressid = progressid;
        param1 = { elid: progressid, func: 'progress.get', sfrom: 'ajax' };
        //check for target
        if (act === 'blank') {
          var $form, winId = progressid + new Date().getTime(),
              $formWrapper = $('#form-wrapper-' + tabId);
          $formWrapper.wrap(function() {
            return '<form action="' + action + '" id="form-' + winId +
                '" method="POST" enctype="multipart/form-data" target="' +
                winId + '"/>';
          });
          $form = $('#form-' + winId);
          $form.append('<input type="hidden" class="i-input-tmp-elem" value="ok" name="sok"/>');
          $form.append('<input type="hidden" class="i-input-tmp-elem" value="' + name +
              '" name="clicked_button"/>');
          if (id && id[1]) {
            $form.append('<input type="hidden" class="i-input-tmp-elem"' +
            ' value="' + id[1] + '" name="' + id[0] + '"/>');
          }
          //remove sfrom=ajax
          $form.find('input[name="sfrom"]').remove();
          window.open('', winId);
          $form.submit();
          if (!flags.keepform) {
            App.Tabs.closeTab(e, tabId);
            if (parent) {
              EventMgr.trigger('reloadTab', { tabId: parent });
            }
          } else {
            $formWrapper.unwrap();
            $('.i-input-tmp-elem').remove();
          }
          //try reload parent after close form
          resetButtonForDefault(self);
          return false;
        }
        var $mixedContols = $('#frm-' + tabId + ' .i-control-mixed');
        if ($mixedContols.length !== 0) {
          param = App.u.removeParam($mixedContols, param);
        }
        //get progressType before request
        progressType = String(progressType).split('_')[0];
        //options for form & form with files submit
        options = {
          url: pageInfo.host + action,
          param: param,
          invar: {
            tabId: tabId,
            parent: parent,
            type: type,
            progresstype: progressType,
            progressid: progressid,
            iType: 'replace',
            dataSaved: true,
            targetTabId: tabId,
            __vars: vars
          },
          type: 'post',
          outtype: 'json',
          trfunc: 'ajaxFormResponse',
          queue: 'noqueue',
          failfunc: 'failFormAjaxResponse' };
        //check for files
        //THIS IS FORM WITH FILE
        /* jshint camelcase: false */
        if (hasFiles) {
          param.sok = 'ok';
          EventMgr.trigger('setBrandSettings', {
            options: options,
            tabId: tabId,
            pid: progressid,
            name: name,
            param: param,
            addParams: {
              sok: 'ok',
              sfrom: 'ajax',
              clicked_button: name,
              pid: progressid
            },
            parent: parent });
        } else if (type === 'report') {
        //THIS IS REPORT
          param.sok = 'ok';
          options = {
            url: pageInfo.host + action,
            param: param,
            invar: { parent: parent, tabId: tabId, __src: 'report' },
            outtype: 'json',
            trfunc: 'ajaxResponse',
            queue: 'noqueue',
            failfunc: 'failCommonAjaxResponse'
          };
          EventMgr.trigger('ajaxRequest', options);
        } else {
          //THIS IS FORM
          param.sok = 'ok';
          EventMgr.trigger('ajaxRequest', options);
        }
        if (progressType !== 'false') {
          setTimeout(function() {
            EventMgr.trigger('ajaxRequest', {
              param: param1,
              invar: {
                tabId: tabId,
                param: param1,
                type: type,
                progresstype: progressType },
              outtype: 'json',
              trfunc: 'progressBarResponse',
              queue: 'noqueue' });
          }, 1000);
        }
        EventMgr.trigger('tabLoading', { tabId: tabId });
      },

      getPwdStrength = function(passwdField) {
        var pws = passwdField.attr('data-check-args'), firstSing;
        if (!pws) { return pageInfo.pwstrength; }
        firstSing = pws.substring(0, 1);
        if (firstSing === '-' || firstSing === '+') {
          return parseFloat(pws) + parseFloat(pageInfo.pwstrength);
        } else {
          return parseFloat(pws);
        }
      },

      //check required field on form
      checkRequired = function(tabId) {
        var field = $('#form-wrapper-' + tabId +
                ' input[required="required"],' +
                ' #form-wrapper-' + tabId +
                ' .b-textarea[required="required"]'),
            msg = '',
            self = null;
        if (field.length > 0) {
          field.each(function() {
            //check for empty and not hidden
            var value = String(this.value).replace(/\s/g, '');
            if (this.className.match('i-control-mixed')) {
              return true;
            }
            if (value === '' && this.offsetWidth !== 0) {
              msg = getRequiredMsg();
              self = this;
              return false;
            }
            if (this.getAttribute('data-type') === 'multiple' &&
                value === '') {
              var id = this.getAttribute('data-id'),
                  elem = App.Dom.byId(id + '-ms-view');
              if (elem && elem.offsetWidth !== 0) {
                msg = getRequiredMsg();
                self = elem.parentNode;
                return false;
              }
            }
          });
        }
        return {
          param: tabId,
          msg: msg,
          himself: self
        };
      },

      //get message for required error
      getRequiredMsg = function() {
        return pageInfo.messages.empty;
      },
      //check password confirm field
      checkConfirm = function(tabId) {
        var field = $('#form-wrapper-' + tabId + ' input[data-confirm="yes"]'),
            msg = '',
            self = null;
        if (field.length > 0) {
          field.each(function() {
            var confirmField = this.getAttribute('data-check-field'),
                value1 = this.value,
                confirmFieldElem = App.Dom.byId(confirmField + '-' + tabId),
                confirmFieldElemFake = App.Dom.byId(confirmField + '-' +
                    tabId + '-fake'),
                value2;
            if (confirmFieldElem !== null) {
              value2 = confirmFieldElem.value;
            }
            if (value1 !== value2 && (confirmFieldElem.offsetWidth !== 0 ||
                confirmFieldElemFake.offsetWidth !== 0)) {
              msg = pageInfo.confirm;
              self = this;
            }
            return;
          });
        }
        return {
          msg: msg,
          himself: self,
          callback: function() { this.focus(); }
        };
      },

      //banner dismiss link handler
      dismissMessage = function(e, data) {
        if (e) { e.preventDefault(); }
        var self = $(this),
            param;
        self.parents('.i-message').hide();
        param = this.getAttribute('data-href');
        EventMgr.trigger('updTableHeight');
        param = App.Common.parseParams(param);
        EventMgr.trigger('ajaxRequest', {
          url: pageInfo.url,
          param: param,
          trfunc: 'DoNothing',
          queue: 'noqueue' });
      };
  return {
    init: init
  };
}(window, $, EventMgr, App);