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.AjaxHelper.js

/**
 * ajax helper module
 *  @param {object} window  global object
 *  @param {function} $ jQuery library
 *  @param {object} EventMgr EventMgr library
 */
App.AjaxHelper = function(window, $, EventMgr) {
  'use strict';
  var init = function() {
    EventMgr.bind('ajaxRequest', ajaxRequest);
    EventMgr.bind('ajaxRequestAbort', ajaxRequestAbort);
  },
      CACHE = {},

      ajaxRequestAbort = function(e, data) {
        var id = data.id;
        if (CACHE[id] && CACHE[id].xhr.abort) {
          CACHE[id].erMsg = 'Request canceled By User';
          CACHE[id].xhr.abort();
        }
      },

      addRequestHook = function(cb) {
        if (typeof cb === 'function') {
          requestHooks.push(cb);
        } 
      },

      addResponseHook = function(cb) {
        if (typeof cb === 'function') {
          responseHooks.push(cb);
        }
      },

      requestHooks = [],

      responseHooks = [],

      applyRequestHooks = function(data) {
        for (var i = 0, l = requestHooks.length; i < l; i++) {
          requestHooks[i].apply(this, [data]);
        }
      },

      applyResponseHooks = function(data) {
        for (var i = 0, l = responseHooks.length; i < l; i++) {
          responseHooks[i].apply(this, [data]);
        }
      },

      ajaxRequest = function(e, dataSource) {
       applyRequestHooks(dataSource);
        var cUrl = dataSource.url || pageInfo.url,
            param = dataSource.param || {},
            formData = dataSource.formData || {},
            inVar = dataSource.invar || {},
            trFunc = dataSource.trfunc || 'ajaxResponse',
            failFunc = dataSource.failfunc || false,
            type = dataSource.type || 'get',
            outType = dataSource.outtype || 'html',
            queueName = dataSource.queue || 'queue',
            noesc = !!dataSource.noesc,
            reqType = dataSource.reqType || 'jquery',
            progressCb = dataSource.progressCb || function() {},
            rp = dataSource.rp || [],
            id = dataSource.id;
        inVar.__dataSource = dataSource;
        if (queueName === 'noqueue') {
          queueName = new Date().getTime();
        }
        param.sfrom = 'ajax';
        param.operafake = new Date().getTime();
        var paramString = getQueryString(param, noesc);

        if (reqType === 'jquery') {
          EventMgr.trigger('getAjaxRequest', {});
          var ajaxParams = {
             url: cUrl,
             type: type,
             dataType: 'html',
             data: paramString,
             headers: { 'ISP-Client': 'Web-interface' },
             //data : param,
             async: true,
             success: success,
             xhrFields: { withCredentials: true },
             error: error
          };
          if (type === 'jsonp') {
            ajaxParams.jsonp = 'callback';
            ajaxParams.dataType = 'jsonp';
            ajaxParams.crossDomain = true;
          }
          $.ajaxq(queueName, ajaxParams);
        } else {
          //progress upload
          var xhr = new XMLHttpRequest();
          xhr.upload.addEventListener('progress', progressCb, false);
          xhr.open('POST', cUrl);
          //set header for long request
          xhr.setRequestHeader('ISP-Client', 'Web-interface');
          xhr.onreadystatechange = function() {
            if (this.readyState === 4) {
              if (this.status === 200) {
                delete CACHE[id];
                success(this.responseText);
              } else {
                error(this, this.statusText, this.statusText);
              }
            }
          };
          formData.append('sfrom', 'ajax');
          CACHE[id] = { xhr: xhr };
          xhr.send(formData);
        }
        /* jshint latedef: false*/
        function success(data) {
          if (type !== 'jsonp') {
            data = data.replace(/\\'/g, "'");
            data = data.replace(/^<![\w\s\"-\/]*>/g, '');
            if (!data) {
              //wtf?
              console.log('empty response');
              EventMgr.trigger('ajaxError', {});
              return;
            }
          }

          if (outType === 'json' && type !== 'jsonp') {
            //remove non-printable characters
            data = data.replace(/[\x00-\x08\x0B-\x0C\x0E-\x1F]/g, '');
            try {
              data = jQuery.parseJSON(data);
            } catch (e) {
              //error
              console.log('jsonParseError', dataSource, failFunc);
              dataSource.erType = 'json';
              if (failFunc) {
                EventMgr.trigger(failFunc, dataSource);
              }
              //EventMgr.trigger('ajaxError', {});
              return;
            }
          }
          if (outType !== 'html') {
            data.sourceParamString = paramString;
            //add props in returned object
            $.extend(data, inVar);
            data.selfUrl = pageInfo.url + '?' + data.urlparam;
            //remove some param from response
            if (rp.length) {
              data = removeParams(data, rp);
            }
          }

          if (trFunc !== 'DoNothing') {
            EventMgr.trigger(trFunc, data);
          }
          EventMgr.trigger('giveAjaxRequest', {});
        }
        /* jshint latedef: false*/
        function error(jqXHR, textStatus, errorThrown) {
          //check for long request
          if ((errorThrown === 'Service Unavailable' || jqXHR.status === 503) && !dataSource.ignore503) {
            //go to new url while request not end
            var longUrl = jqXHR.responseText;
            dataSource.url = pageInfo.host + '/' + longUrl;
            dataSource.reqType = 'jquery';
            EventMgr.trigger('ajaxRequest', dataSource);
          } else if (trFunc === 'ajaxResponse' &&
              inVar.exType === 'dashboard') {
            inVar.error = true;
            inVar.shithappend = true;
            EventMgr.trigger('ajaxResponse', inVar);
          } else if (failFunc) {
            var regex = /<div class="fatal-error-desc">(.*?)<\/div>/ig,
                errText = String(jqXHR.responseText).match(regex);
            if (errText && errText[0]) {
              dataSource.erMsg = errText[0];
            }
            if (CACHE[dataSource.id] &&
                App.u.isString(CACHE[dataSource.id].erMsg)) {
              dataSource.erMsg = CACHE[dataSource.id].erMsg;
            }
            EventMgr.trigger(failFunc, dataSource);
            delete CACHE[dataSource.id];
          }
          console.log(textStatus);
        }
      },

      removeParams = function(data, rp) {
        var l = rp.length;
        while(l--) {
          data[rp[l]] = null;
        }
        return data;
      },
      //join with &
      getQueryString = function(queryObj, noesc) {
        var j = 0,
            paramString = '',
            curValue,
            keyVar;
        for (keyVar in queryObj) {
          if (keyVar !== '') {
            if (j !== 0) {
              paramString += '&';
            }
            curValue = queryObj[keyVar];
            //encode params
            if (noesc) {
              paramString += keyVar + '=' + curValue;
            } else {
              paramString += keyVar + '=' + encodeURIComponent(curValue);
            }
            j++;
          }
        }
        return paramString;
      };
  return {
    init: init,
    addRequestHook: addRequestHook,
    addResponseHook: addResponseHook
  };
}(window, $, EventMgr);