Ext.Ajax.extraParams = {authenticity_token: 'RkOaRjqP0SCgZfSzJivP7zE0ANpAJ2BbdoB/lxorMUg='}; 
Ext.ns('Netzke');
Ext.ns('Netzke.core');
Netzke.RelativeUrlRoot = '';
Netzke.RelativeExtUrl = '/extjs';
Netzke.core.directMaxRetries = 2;
if (!String.prototype.camelize) String.prototype.camelize = function(lowFirstLetter)
{
  var str=this; 
  var str_path=str.split('/');
  for(var i=0;i<str_path.length;i++)
  {
    var str_arr=str_path[i].split('_');
    var initX=((lowFirstLetter&&i+1==str_path.length)?(1):(0));
    for(var x=initX;x<str_arr.length;x++)
      str_arr[x]=str_arr[x].charAt(0).toUpperCase()+str_arr[x].substring(1);
    str_path[i]=str_arr.join('');
  }
  str=str_path.join('::');
  return str;
};
if (!String.prototype.capitalize) String.prototype.capitalize = function()
{
  var str=this.toLowerCase();
  str=str.substring(0,1).toUpperCase()+str.substring(1);
  return str;
};
if (!String.prototype.humanize) String.prototype.humanize = function(lowFirstLetter)
{
  var str=this.toLowerCase();
  str=str.replace(new RegExp('_id','g'),'');
  str=str.replace(new RegExp('_','g'),' ');
  if(!lowFirstLetter)str=str.capitalize();
  return str;
};
if (!String.prototype.underscore) String.prototype.underscore = function() {
  return this.replace(/::/g, '/')
             .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
             .replace(/([a-z\d])([A-Z])/g, '$1_$2')
             .replace(/-/g, '_')
             .toLowerCase();
};
Ext.ns('Ext.netzke'); 
Ext.ns('Netzke.page'); 
Ext.ns('Netzke.classes'); 
Ext.ns('Netzke.classes.Core'); 
Netzke.deprecationWarning = function(msg){
  if (typeof console == 'undefined') {
  } else {
    console.info("Netzke: " + msg);
  }
};
Netzke.warning = Netzke.deprecationWarning;
Netzke.exception = function(msg) {
  throw("Netzke: " + msg);
};
if( Netzke.nLoadingFixRequests == undefined ){
  Netzke.nLoadingFixRequests=0;
  Ext.Ajax.on('beforerequest',    function(conn,opt) { Netzke.nLoadingFixRequests+=1; });
  Ext.Ajax.on('requestcomplete',  function(conn,opt) { Netzke.nLoadingFixRequests-=1; });
  Ext.Ajax.on('requestexception', function(conn,opt) { Netzke.nLoadingFixRequests-=1; });
  Netzke.ajaxIsLoading = function() { return Netzke.nLoadingFixRequests > 0; };
}
Netzke.runningRequests = 0;
Netzke.isLoading=function () {
  return Netzke.runningRequests != 0;
}
Netzke.chainApply = function(){
  var res = {};
  Ext.each(arguments, function(o){
    Ext.apply(res, o);
  });
  return res;
};
Netzke.aliasMethodChain = function(klass, method, feature) {
  klass[method + "Without" + feature.capitalize()] = klass[method];
  klass[method] = klass[method + "With" + feature.capitalize()];
};
Netzke.cache = [];
Netzke.componentNotInSessionHandler = function() {
  throw "Netzke: component not in Rails session. Define Netzke.componentNotInSessionHandler to handle this.";
};
Netzke.classes.Core.Mixin = {};
Netzke.componentMixin = Ext.applyIf(Netzke.classes.Core.Mixin, {
  isNetzke: true, 
  detectComponents: function(o){
    if (Ext.isObject(o)) {
      if (o.items) this.detectComponents(o.items);
    } else if (Ext.isArray(o)) {
      var a = o;
      Ext.each(a, function(c, i){
        if (c.netzkeComponent) {
          var cmpName = c.netzkeComponent,
              cmpCfg = this.netzkeComponents[cmpName.camelize(true)];
          if (!cmpCfg) throw "Netzke: unknown component reference " + cmpName;
          a[i] = Ext.apply(cmpCfg, c);
          delete a[i].netzkeComponent; 
        } else if (c.items) this.detectComponents(c.items);
      }, this);
    }
  },
  evalCss : function(code){
    var head = Ext.fly(document.getElementsByTagName('head')[0]);
    Ext.core.DomHelper.append(head, {
      tag: 'style',
      type: 'text/css',
      html: code
    });
  },
  evalJs : function(code){
    eval(code);
  },
  localId : function(parent){
    return this.id.replace(parent.id + "__", "");
  },
  bulkExecute : function(instructions){
    if (Ext.isArray(instructions)) {
      Ext.each(instructions, function(instruction){ this.bulkExecute(instruction)}, this);
    } else {
      for (var instr in instructions) {
        if (Ext.isFunction(this[instr])) {
          this[instr].apply(this, [instructions[instr]]);
        } else {
          var childComponent = this.getChildNetzkeComponent(instr);
          if (childComponent) {
            childComponent.bulkExecute(instructions[instr]);
          } else {
            throw "Netzke: Unknown method or child component '" + instr +"' in component '" + this.id + "'"
          }
        }
      }
    }
  },
  endpointUrl: function(endpoint){
    return Netzke.RelativeUrlRoot + "/netzke/dispatcher?address=" + this.id + "__" + endpoint;
  },
  callServer : function(intp, params, callback, scope){
    Netzke.runningRequests++;
    if (!params) params = {};
      Ext.Ajax.request({
      params: params,
      url: this.endpointUrl(intp),
      callback: function(options, success, response){
        if (success && response.responseText) {
          this.bulkExecute(Ext.decode(response.responseText));
          if (typeof callback == 'function') {
            if (!scope) scope = this;
            callback.apply(scope, [this.latestResult]);
          }
        }
        Netzke.runningRequests--;
      },
      scope : this
    });
  },
  setResult: function(result) {
    this.latestResult = result;
  },
  componentNotInSession: function() {
    Netzke.componentNotInSessionHandler();
  }
});
Ext.override(Ext.Container, {
  instantiateChild: function(config){
    Netzke.deprecationWarning("instantiateChild is deprecated");
    var instance = Ext.createByAlias( config.alias, config );
    this.insertNetzkeComponent(instance);
    return instance;
  },
  insertNetzkeComponent: function(cmp) {
    this.removeChild(); 
    this.add(cmp);
    if (this.isVisible()) {
      this.doLayout();
    } else {
      this.on('show', function(cmp){cmp.doLayout();}, {single: true});
    }
  },
  getOwnerComponent: function(){
    Netzke.deprecationWarning("getOwnerComponent is deprecated");
    if (this.initialConfig.isNetzke) {
      return this;
    } else {
      if (this.ownerCt){
        return this.ownerCt.getOwnerComponent();
      } else {
        return null;
      }
    }
  },
  getNetzkeComponent: function(){
    Netzke.deprecationWarning("getNetzkeComponent is deprecated");
    return this.items ? this.items.first() : null; 
  },
  removeChild: function(){
    Netzke.deprecationWarning("removeChild is deprecated");
    var currentChild = this.getNetzkeComponent();
    if (currentChild) {this.remove(currentChild);}
  }
});
if (Ext.Compat) Ext.Compat.showErrors = true;
Ext.TabPanel.prototype.idDelimiter = "___";
Ext.QuickTips.init();
Ext.state.Provider.prototype.set = Ext.emptyFn;
(function(){
  var requiredVersionMajor = 4,
      requiredVersionMinor = 0,
      extVersion = Ext.getVersion('extjs'),
      currentVersionMajor = extVersion.getMajor(),
      currentVersionMinor = extVersion.getMinor(),
      requiredString = "" + requiredVersionMajor + "." + requiredVersionMinor + ".x",
      currentString = "" + currentVersionMajor + "." + currentVersionMinor + ".x";
  if (requiredVersionMajor != currentVersionMajor || requiredVersionMinor != currentVersionMinor) {
    Netzke.warning("Ext " + requiredString + " required. You have " + currentString + ".");
  }
})();
Ext.define('Netzke.FeedbackGhost', {
  showFeedback: function(msg){
    if (!msg) Netzke.exception("Netzke.FeedbackGhost#showFeedback: wrong number of arguments (0 for 1)");
    if (Ext.isObject(msg)) {
      this.msg(msg.level.camelize(), msg.msg);
    } else if (Ext.isArray(msg)) {
      Ext.each(msg, function(m) { this.showFeedback(m); }, this);
    } else {
      this.msg(null, msg); 
    }
  },
  msg: function(title, format){
      if(!this.msgCt){
          this.msgCt = Ext.core.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
      }
      var s = Ext.String.format.apply(String, Array.prototype.slice.call(arguments, 1));
      var m = Ext.core.DomHelper.append(this.msgCt, this.createBox(title, s), true);
      m.hide();
      m.slideIn('t').ghost("t", { delay: 1000, remove: true});
  },
  createBox: function(t, s){
    if (t) {
      return '<div class="msg"><h3>' + t + '</h3><p>' + s + '</p></div>';
    } else {
      return '<div class="msg"><p>' + s + '</p></div>';
    }
  }
});
Netzke.componentMixin.feedbackGhost = Ext.create("Netzke.FeedbackGhost");
Ext.define('Netzke.classes.NetzkeRemotingProvider', {
  extend: 'Ext.direct.RemotingProvider',
  getCallData: function(t){
    return {
      act: t.action, 
      method: t.method,
      data: t.data,
      type: 'rpc',
      tid: t.id
    }
  },
  addAction: function(action, methods) {
    var cls = this.namespace[action] || (this.namespace[action] = {});
    for(var i = 0, len = methods.length; i < len; i++){
      method = Ext.create('Ext.direct.RemotingMethod', methods[i]);
      cls[method.name] = this.createHandler(action, method);
    }
  },
  getTransaction: function(opt) {
    if (opt.$className == "Ext.direct.Transaction") {
      return opt;
    } else {
      return this.callParent([opt]);
    }
  }
});
Netzke.directProvider = new Netzke.classes.NetzkeRemotingProvider({
  type: "remoting",       
  url: Netzke.RelativeUrlRoot + "/netzke/direct/", 
  namespace: "Netzke.providers", 
  actions: {},
  maxRetries: Netzke.core.directMaxRetries,
  enableBuffer: true, 
  timeout: 30000 
});
Ext.Direct.addProvider(Netzke.directProvider);
Ext.apply(Netzke.classes.Core.Mixin, {
  componentLoadMask: true,
  initComponentWithNetzke: function(){
    this.normalizeActions();
    this.detectActions(this);
    this.detectComponents(this.items);
    this.normalizeTools();
    this.processEndpoints();
    this.processPlugins();
    this.callbackHash = {};
    this.componentsBeingLoaded = {};
    if (this.mode === "config"){
      if (!this.title) {
        this.title = '[' + this.id + ']';
      } else {
        this.title = this.title + ' [' + this.id + ']';
      }
    } else {
      if (!this.title) {
        this.title = this.id.humanize();
      }
    }
    this.initComponentWithoutNetzke();
  },
  processEndpoints: function(){
    var endpoints = this.endpoints || [];
    endpoints.push('deliver_component'); 
    var directActions = [];
    var that = this;
    Ext.each(endpoints, function(intp){
      directActions.push({"name":intp.camelize(true), "len":1});
      this[intp.camelize(true)] = function(arg, callback, scope) {
        Netzke.runningRequests++;
        scope = scope || that;
        Netzke.providers[this.id][intp.camelize(true)].call(scope, arg, function(result, remotingEvent) {
          if(remotingEvent.message) {
            console.error("RPC event indicates an error: ", remotingEvent);
            throw new Error(remotingEvent.message);
          }
          that.bulkExecute(result); 
          if(typeof callback == "function") {
            callback.call(scope, that.latestResult); 
          }
          Netzke.runningRequests--;
        });
      }
    }, this);
    Netzke.directProvider.addAction(this.id, directActions);
  },
  normalizeTools: function() {
    if (this.tools) {
      var normTools = [];
      Ext.each(this.tools, function(tool){
        this.addEvents(tool.id+'click');
        var handler = Ext.Function.bind(this.toolActionHandler, this, [tool]);
        normTools.push({type : tool, handler : handler, scope : this});
      }, this);
      this.tools = normTools;
    }
  },
  normalizeActions : function(){
    var normActions = {};
    for (var name in this.actions) {
      this.addEvents(name+'click');
      var actionConfig = Ext.apply({}, this.actions[name]); 
      actionConfig.customHandler = actionConfig.handler;
      actionConfig.handler = Ext.Function.bind(this.actionHandler, this); 
      actionConfig.name = name;
      normActions[name] = new Ext.Action(actionConfig);
    }
    delete(this.actions);
    this.actions = normActions;
  },
  detectActions: function(o){
    if (Ext.isObject(o)) {
      if ((typeof o.handler === 'string') && Ext.isFunction(this[o.handler.camelize(true)])) {
        o.handler = this[o.handler.camelize(true)].createDelegate(this);
      }
      Ext.each(["bbar", "tbar", "fbar", "menu", "items", "contextMenu", "buttons", "dockedItems"], function(key){
        if (o[key]) {
          var items = [].concat(o[key]); 
          delete(o[key]);
          o[key] = items;
          this.detectActions(o[key]);
        }
      }, this);
    } else if (Ext.isArray(o)) {
      var a = o;
      Ext.each(a, function(el, i){
        if (Ext.isObject(el)) {
          if (el.action) {
            if (!this.actions[el.action.camelize(true)]) throw "Netzke: action '"+el.action+"' not defined";
            a[i] = this.actions[el.action.camelize(true)];
            delete(el);
          } else {
            this.detectActions(el);
          }
        }
      }, this);
    }
  },
  loadNetzkeComponent: function(params){
    if (params.id) {
      params.name = params.id;
      Netzke.deprecationWarning("Using 'id' in loadComponent is deprecated. Use 'name' instead.");
    }
    params.name = params.name.underscore();
    var serverParams = params.params || {};
    serverParams.name = params.name;
    serverParams.cache = Netzke.cache.join();
    var storedConfig = this.componentsBeingLoaded[params.name] = params;
    var containerCmp = params.container && Ext.isString(params.container) ? Ext.getCmp(params.container) : params.container;
    storedConfig.container = containerCmp;
    var containerEl = (containerCmp || this).getEl();
    if (this.componentLoadMask && containerEl){
      storedConfig.loadMaskCmp = new Ext.LoadMask(containerEl, this.componentLoadMask);
      storedConfig.loadMaskCmp.show();
    }
    this.deliverComponent(serverParams);
  },
  loadComponent: function(params) {
    Netzke.deprecationWarning("loadComponent is deprecated in favor of loadNetzkeComponent");
    params.container = params.container || this.getId(); 
    this.loadNetzkeComponent(params);
  },
  componentDelivered: function(config){
    var storedConfig = this.componentsBeingLoaded[config.name] || {};
    delete this.componentsBeingLoaded[config.name];
    if (storedConfig.loadMaskCmp) {
      storedConfig.loadMaskCmp.hide();
      storedConfig.loadMaskCmp.destroy();
    }
    var componentInstance = Ext.createByAlias(config.alias, config);
    if (storedConfig.container) {
      var containerCmp = storedConfig.container;
      if (!storedConfig.append) containerCmp.removeAll();
      containerCmp.add(componentInstance);
      if (containerCmp.isVisible()) {
        containerCmp.doLayout();
      } else {
        containerCmp.on('show', function(cmp){ cmp.doLayout(); }, {single: true});
      }
    }
    if (storedConfig.callback) {
      storedConfig.callback.call(storedConfig.scope || this, componentInstance);
    }
    this.fireEvent('componentload', componentInstance);
  },
  componentDeliveryFailed: function(params) {
    var storedConfig = this.componentsBeingLoaded[params.componentName] || {};
    delete this.componentsBeingLoaded[params.componentName];
    if (storedConfig.loadMaskCmp) {
      storedConfig.loadMaskCmp.hide();
      storedConfig.loadMaskCmp.destroy();
    }
    this.netzkeFeedback({msg: params.msg, level: "Error"});
  },
  instantiateAndRenderComponent: function(config, containerId){
    var componentInstance;
    if (containerId) {
      var container = Ext.getCmp(containerId);
      componentInstance = container.instantiateChild(config);
    } else {
      componentInstance = this.instantiateChild(config);
    }
    return componentInstance;
  },
  getParentNetzkeComponent: function(){
    var idSplit = this.id.split("__");
    idSplit.pop();
    var parentId = idSplit.join("__");
    return parentId === "" ? null : Ext.getCmp(parentId);
  },
  getParent: function() {
    Netzke.deprecationWarning("getParent is deprecated in favor of getParentNetzkeComponent");
    return this.getParentNetzkeComponent();
  },
  reload: function(){
    var parent = this.getParentNetzkeComponent();
    if (parent) {
      parent.loadNetzkeComponent({id:this.localId(parent), container:this.ownerCt.id});
    } else {
      window.location.reload();
    }
  },
  reconfigure: function(config){
    this.ownerCt.instantiateChild(config)
  },
  instantiateChildNetzkeComponent: function(name) {
    name = name.camelize(true);
    return Ext.createByAlias(this.netzkeComponents[name].alias, this.netzkeComponents[name])
  },
  getChildNetzkeComponent: function(id){
    if (id === "") {return this};
    id = id.underscore();
    var split = id.split("__");
    if (split[0] === 'parent') {
      split.shift();
      var childInParentScope = split.join("__");
      return this.getParentNetzkeComponent().getChildNetzkeComponent(childInParentScope);
    } else {
      return Ext.getCmp(this.id+"__"+id);
    }
  },
  getChildComponent: function(id) {
    Netzke.deprecationWarning("getChildComponent is deprecated in favor of getChildNetzkeComponent");
    return this.getChildNetzkeComponent(id);
  },
  netzkeFeedback: function(msg){
    if (this.initialConfig && this.initialConfig.quiet) {
      return false;
    }
    if (this.feedbackGhost) {
      this.feedbackGhost.showFeedback(msg);
    } else {
      if (typeof msg == 'string'){
        alert(msg);
      } else {
        var compoundResponse = "";
        Ext.each(msg, function(m){
          compoundResponse += m.msg + "\n"
        });
        if (compoundResponse != "") {
          alert(compoundResponse);
        }
      }
    }
  },
  feedback: function(msg) {
    Netzke.deprecationWarning("feedback is deprecated in favor of netzkeFeedback");
    this.netzkeFeedback(msg);
  },
  actionHandler: function(comp){
    var actionName = comp.name;
    if (this.fireEvent(actionName+'click', comp)) {
      var action = this.actions[actionName];
      var customHandler = action.initialConfig.customHandler;
      var methodName = (customHandler && customHandler.camelize(true)) || "on" + actionName.camelize();
      if (!this[methodName]) {throw "Netzke: action handler '" + methodName + "' is undefined"}
      this[methodName](comp);
    }
  },
  toolActionHandler: function(tool){
    if (this.fireEvent(tool.id+'click')) {
      var methodName = "on"+tool.camelize();
      if (!this[methodName]) {throw "Netzke: handler for tool '"+tool+"' is undefined"}
      this[methodName]();
    }
  },
  processPlugins: function() {
    if (this.netzkePlugins) {
      if (!this.plugins) this.plugins = [];
      Ext.each(this.netzkePlugins, function(p){
        this.plugins.push(this.instantiateChildNetzkeComponent(p));
      }, this);
    }
  },
  onComponentLoad:Ext.emptyFn 
});
Ext.ns("Netzke.pre");
Ext.ns("Netzke.pre.Basepack");
Ext.ns("Ext.ux.grid");
Ext.apply(Ext.History, new Ext.util.Observable());
Ext.define('Ext.netzke.ComboBox', {
  extend        : 'Ext.form.field.ComboBox',
  alias         : 'widget.netzkeremotecombo',
  valueField    : 'field1',
  displayField  : 'field2',
  triggerAction : 'all',
  initComponent : function(){
    var modelName = this.parentId + "_" + this.name;
    Ext.define(modelName, {
        extend: 'Ext.data.Model',
        fields: ['field1', 'field2']
    });
    var store = new Ext.data.Store({
      model: modelName,
      proxy: {
        type: 'direct',
        directFn: Netzke.providers[this.parentId].getComboboxOptions,
        reader: {
          type: 'array',
          root: 'data'
        }
      }
    });
    store.on('beforeload', function(self, params) {
      params.params.column = this.name;
    },this);
    if (this.store) store.loadData({data: this.store});
    this.store = store;
    this.callParent();
  },
  collapse: function(){
    if( !this.store.loading ) this.callParent();
  }
});
Ext.util.Format.mask = function(v){
  return "********";
};
Ext.define('Ext.ux.form.TriCheckbox', {
  extend: 'Ext.form.field.ComboBox',
  alias: 'widget.tricheckbox',
  store: [[true, "Yes"], [false, "No"]],
  forceSelection: true
});
Ext.override( Ext.form.field.Checkbox, {
  getSubmitValue: function() {
    return this.callOverridden() || false; 
  }
});
Ext.override(Ext.data.proxy.Server, {
  constructor: function() {
    this.addEvents('load');
    this.callOverridden([arguments]);
  },
  processResponse: function(success, operation, request, response, callback, scope){
    this.callOverridden(arguments);
    this.fireEvent('load', this, response, operation);
  }
});

