if ((typeof console) == "undefined" || (typeof console.log) == "undefined")
{
  console = {
    log: function (v) {} // do nothing if undefined
  }
}

Ext.BLANK_IMAGE_URL = "ext/resources/images/default/s.gif";
Ext.namespace("Admin");

Admin.main = function()
{
  return (
  {
    view: null,
    gateway: "io.php",
    userdata: {
      logged_in: false,
      user_id: 0
    },
    page_size: 25,
    loaded_modules: [],
    load_masks: [],

    init: function()
    {
      // check for loading mask
      Ext.destroy(Ext.get("loading"));
      Ext.destroy(Ext.get("loading-mask"));

      Ext.QuickTips.init();

      Ext.form.Field.prototype.msgTarget = 'under';
      Ext.MessageBox.winWidth = 300;
      Ext.Msg.winWidth = 300;

      // set default ajax URL
      Ext.Ajax.url = this.gateway;
      Ext.Ajax.on('requestcomplete', function(c, r, o)
      {
        if (r.responseText)
        {
          // check if the response is in json format
          if (r.responseText.substr(0, 1) === '{' && r.responseText.substr(-1) === '}')
          {
            var json = Ext.decode(r.responseText);
            // if it is one of my backend exceptions
            if (!json.success && json.errors.reason)
            {
              // disable load masks
              console.log('request failed 1');
              console.log(this.load_masks);

              // show the message
              Ext.Msg.alert('Error', json.errors.reason);
            }
            else if (!json.success)
            {
              // disable load masks
              console.log('request failed 2');
              console.log(this.load_masks);

              Ext.Msg.alert('Error', 'There was an error on the server.');
            }
          }
        }
      }, this);

      this.view = new Ext.Viewport({
        layout:'fit',
        items:[{
          layout: "border",
          border: false,
          items: [
            {
              region: "north",
              id: "view-head",
              height: 50,
              html: "<a href=\"index.php\">Admin</a>",
              border: false
            },
            {
              region: "center",
              xtype: 'grouptabpanel',
              id: 'view-body',
              tabWidth: 130,
              activeGroup: 0,
              items: [
                {
                  id: 'main-menu-login',
                  items: [
                    {
                      id: 'login-panel',
                      title: 'Log In',
                      loadModule: 'login',
                      listeners: {
                        'activate': this.main_menu_click,
                        scope: this
                      }
                    },
                    {
                      id: 'passreset-panel',
                      title: 'Reset Password',
                      iconCls: 'none',
                      loadModule: 'passreset',
                      listeners: {
                        'activate': this.main_menu_click,
                        scope: this
                      }
                    }
                  ]
                }
              ]
            }
          ]
        }
      ]}); // view
      
      // check for login
      Ext.Ajax.request({
        url: this.gateway,
        params: {page_mode: "check-login"},
        failure: this.submit_failure,
        success: function (r, o)
        {
          resp = Ext.decode(r.responseText);
          if (resp.logged_in)
          {
            this.userdata.logged_in = true;
            this.userdata.user_id = resp.data.user_id;
            this.userdata.email = resp.data.email;

            if (this.loaded_modules.indexOf("login") == -1)
            {
              Ext.ux.OnDemandLoadByAjax.load(["js/login.js"], function()
              {
                (function() {
                  Admin.login.init.call(Admin.login);
                  Admin.login.do_login.call(Admin.login);
                }).defer(100);
              }, this);
            }
            else
              Admin.login.do_login.call(Admin.login);
          }
        },
        scope: this
      });

      this.session_keepalive.defer(15 * 60 * 1000, this);

      if ((typeof autoload_tab) != "undefined")
      {
        Ext.getCmp('main-menu-login').setActiveTab(autoload_tab);
      }
    }, // init

    main_menu_click: function(t)
    {
      if ((typeof t.loadModule) != "undefined")
      {
        this.load_module.call(this, t.loadModule);
      }
    },

    load_module: function(mod_name, skip_main)
    {
      if (this.loaded_modules.indexOf(mod_name) == -1)
      {
        var mask = this.loadmask(Ext.getBody(), {msg:"Loading..."});
        mask.show();
        Ext.ux.OnDemandLoadByAjax.load(["js/" + mod_name + ".js"], function()
        {
          mask.hide();
          Admin[mod_name].init.call(Admin[mod_name]);

          (function() {
            if (this.loaded_modules.indexOf(mod_name) == -1)
              alert('Loading module ' + mod_name + ' failed.');
            else if (skip_main !== true)
              Admin[mod_name].main.call(Admin[mod_name]);
          }).defer(100, this);
        }, this);
      }
      else if (skip_main !== true)
        Admin[mod_name].main.call(Admin[mod_name]);
    },
    
    unload_module: function(mod_name)
    {
      if (this.loaded_modules.indexOf(mod_name) != -1)
      {
        if ((typeof Admin[mod_name].unload) == 'function')
          Admin[mod_name].unload.call(Admin[mod_name]);
        this.loaded_modules.remove(mod_name);
      }
    },
    
    // remove all children from a component
    remove_children: function(comp)
    {
      if ((typeof comp.removeAll) == "function")
        comp.removeAll();
      else if ((typeof comp.items) != "undefined")
      {
        var items = comp.items.getRange();
        for (var i = 0; i < items.length; i++)
        {
          comp.remove(items[i].id);
        }
      }
    },

    // check if an object has a certain ancestor
    is_parent: function(parent_id, child_id)
    {
      var el = Ext.getCmp(child_id);
      if ((typeof el) == 'undefined')
        return false;
      while ((typeof el.ownerCt) != 'undefined')
      {
        el = el.ownerCt;
        if (el.id == parent_id)
          return true;
      }
      return false;
    },
    
    // return an appropriate width
    good_width: function(n)
    {
      var w = Admin.main.view.getWidth();
      if (w - 20 > n)
        return n;
      return w - 20;
    },
    
    // return an appropriate height
    good_height: function(n)
    {
      var h = Admin.main.view.getHeight();
      if (h - 20 > n)
        return n;
      return h - 20;
    },

    // add a menu item
    add_menu_item: function(opts)
    {
      var menu = Ext.getCmp('view-body');
      menu.add(opts);
      menu.doLayout();
    },
    
    // remove a menu item
    remove_menu_item: function(id)
    {
      console.log(Ext.getCmp(id));

      if (Ext.getCmp(id) != undefined)
      {
        var menu = Ext.getCmp('view-body');
        menu.remove(Ext.getCmp(id));
        menu.doLayout();
        console.log('remove');
      }
    },
    
    validate_num_range: function(val, field) {
      if (field.startRangeField) {
        var start = Ext.getCmp(field.startRangeField);
        start.maxValue = val;
        start.validate();
      }
      else if (field.endRangeField) {
        var end = Ext.getCmp(field.endRangeField);
        end.minValue = val;
        end.validate();
      }
      return true;
    },

    // submit_failure is the common callback function when a form submission fails
    submit_failure: function(frm, act)
    {
      if (act.failureType == "server")
      {
        // server error - errors property should contain fields
        obj = Ext.util.JSON.decode(act.response.responseText);
        if (typeof(obj.errors.reason) != "undefined")
        {
          Ext.Msg.show({
            title: "Warning",
            msg: "Submit failed! " + obj.errors.reason,
            buttons: Ext.Msg.OK,
            icon: Ext.Msg.WARNING
          });
        }
        else
        {
          Ext.Msg.show({
            title: "Warning",
            msg: "Submit failed! Please review the form for errors.",
            buttons: Ext.Msg.OK,
            icon: Ext.Msg.WARNING
          });
        }
      }
      else if (act.failureType == "client")
      {
        Ext.Msg.show({
          title: "Warning",
          msg: "Submit failed!  Please review the form for errors.",
          buttons: Ext.Msg.OK,
          icon: Ext.Msg.WARNING
        });
      }
      else if (act.failureType == "connect" || act.failureType == "load")
      {
        Ext.Msg.show({
          title: "Warning",
          msg: "There was an error on the server.  Failure type: " + act.failureType,
          buttons: Ext.Msg.OK,
          icon: Ext.Msg.WARNING
        });
      }
      else
      {
        obj = Ext.util.JSON.decode(act.response.responseText);
        msgtxt = "Submit error!";
        if (typeof(obj.errors.reason) != "undefined")
          msgtxt += " " + obj.errors.reason;
        Ext.Msg.show({
          title: "Warning",
          msg: msgtxt,
          buttons: Ext.Msg.OK,
          icon: Ext.Msg.WARNING
        });
      }
    },

    session_keepalive: function()
    {
      Ext.Ajax.request({
        url: this.gateway,
        params: {page_mode: ""},
        disableCaching: true,
        callback: Ext.emptyFn
      });
      this.session_keepalive.defer(15 * 60 * 1000, this);
    },

    check_ajax_response: function(s, r)
    {
      if (!s)
      {
        Ext.Msg.alert('Error', 'There was an error updating the server.');
        return false;
      }
      var resp = Ext.decode(r.responseText);
      if ((typeof resp.errors.reason) != 'undefined')
      {
        Ext.Msg.alert('Error', resp.errors.reason);
        return false;
      }
      if (!resp.success)
      {
        Ext.Msg.alert('Error', 'There was an error updating the server.');
        return false;
      }

      return resp;
    },

    get_child_nodes: function(n)
    {
      var retval = [];

      for (var i = 0; i < n.childNodes.length; i++)
      {
        retval.push(n.childNodes[i].attributes);
      }
      
      return retval;
    },
    
    loadmask: function(el, config)
    {
      var mask = new Ext.LoadMask(el, config);
      //this.load_masks.push(mask);
      return mask;
    }

  })
}();
