/*global YAHOO,context_url,escape,window */

/*jslint white: true, onevar: true, browser: true, on: true, undef: true,
         eqeqeq: true, plusplus: true, bitwise: true, regexp: true,
         newcap: true, immed: true, indent: 2, nomen: false */

if (!window.AZCAT) {
  var AZCAT = {};
}

AZCAT.namespace = function () {
  var a = arguments, o = null, i, j, d;
  for (i = 0; i < a.length; i = i + 1) {
    d = a[i].split(".");
    o = AZCAT;

    // YAHOO is implied, so it is ignored if it is included
    for (j = (d[0] === "AZCAT") ? 1 : 0; j < d.length; j = j + 1) {
      o[d[j]] = o[d[j]] || {};
      o = o[d[j]];
    }
  }

  return o;
};

AZCAT.init = function () {
  this.namespace("siteman"); // Declare our namespaces
  this.namespace("utils");
  this.namespace("widgets");
};

AZCAT.register = function (name, mainClass, data) {
  var mods = AZCAT.env.modules, m, v, b, ls, i;
  if (!mods[name]) {
    mods[name] = { versions: [], builds: [] };
  }
  m = mods[name];
  v = data.version;
  b = data.build;
  ls = AZCAT.env.listeners;
  m.name = name;
  m.version = v;
  m.build = b;
  m.versions.push(v);
  m.builds.push(b);
  m.mainClass = mainClass;
  // fire the module load listeners
  for (i = 0; i < ls.length; i = i + 1) {
    ls[i](m);
  }
  // label the main class
  if (mainClass) {
    mainClass.VERSION = v;
    mainClass.BUILD = b;
  } else {
    YAHOO.log("mainClass is undefined for module " + name, "warn");
  }
};
AZCAT.env = AZCAT.env || {
  modules: [],
  listeners: [],
  getVersion: function (name) {
    return AZCAT.env.modules[name] || null;
  }
};

AZCAT.init();

AZCAT.register("azcat", AZCAT, {version: "2.0.0", build: "???"});

// This should go into a separate file for utilities at some point

AZCAT.utils.connFail = function (o) {
  alert(['Unfortunately, you have encountered an error connecting with our server. Please try again later.  If the problem persists, contact support @ emergence.com']);
};

AZCAT.utils.reportError = function (msg) {
  YAHOO.util.Connect.asyncRequest('POST', [context_url, '/reportError'].join(""), {}, 'msg=' + escape(msg));
};

AZCAT.utils.errorCatcher = function (e) {
  AZCAT.utils.reportError(JSON.stringify(e));
};

AZCAT.utils.errorEvent = function () {
  var real_array = [], msg = JSON.stringify(arguments), x;
  // JSON.stringify returns '()' on arguments directly in FF3
  if (msg === '{}') {
    for (x = arguments.length - 1; x >= 0; x -= 1) {
      real_array.unshift(arguments[x]);
    }
    msg = JSON.stringify(real_array);
  }
  AZCAT.utils.reportError(msg);
  return false;
};

window.onerror = AZCAT.utils.errorEvent; // Subscribtion to this event using YUI does not produce the correct arguments.

YAHOO.env.supports_inline_block = (YAHOO.env.ua.ie !== 6 &&
                                   YAHOO.env.ua.ie !== 7);

YAHOO.util.Event.throwErrors = true;
