$loaded = {};
$loaded.push = function() {};

Environment = {
  meta: {},  //contains page meta attributes
  params: {//global hash of current params
    version: Math.round(Math.random() * 50000)
  },
  config: {//frontend configuration. see frontend.yml
    path: "/javascripts",
    index: "/javascripts/build.json",
    autoload: true,
    cache: true,
    pack: true,
    verbosity: 3,
    subdomain: false,
    hosts: 1,
    name: "artificial"
  },
  things: {} //contains some important widget instances for easy debug
};

(function () {
  
  //essential functions 
  var $empty = function(){};

  var JSON = {
    parse: function (text) {
      return eval('(' + text + ')');
    }
  };

  var extend = function(one, another) {
    for (var i in another) one[i] = another[i];
    return one;
  }

  //extract meta-params from head
  for (var i = 0, nodes = document.getElementsByTagName('head')[0].getElementsByTagName('meta'), node; node = nodes[i++];) {
    switch(node.getAttribute('rel')) {
      case "param":
        Environment.params[node.name] = node.content;
        break;

      case "config":
        extend(Environment.config, JSON.parse(node.content));
        break;

      default:
        Environment.meta[node.name || node['http-equiv']] = node.content;
    } 
  }
  
  //Add console fallbacks
  if (!window.console) window.console = {};
  for (var methods = ['info', 'warn', 'profile', 'group', 'profileEnd', 'groupCollapsed', 'groupEnd', 'error'], i = 0, method; method = methods[i]; i++) {
    if (!console[method] || !console[method].apply) console[method] = $empty;
  }



  console.info('Loading ' + Environment.config.name.toUpperCase() + ' light environment...');

})();

DM = {};
DM.staticFileURL = function(path) {
  var prefix = '';
  if (Environment.config.subdomain) {
     var hash = 0;
    for (var chars = path.split("?")[0], i = 0, ch; ch = chars[i++];) hash += ch.charCodeAt(0)
    prefix = Environment.config.subdomain.replace('%i', hash % Environment.config.hosts + 1) + '.';
  }
  
  return location.protocol + '//' + prefix + location.host.replace(/^.*?(\w*\.\w*)$/, '$1') + path;
}
DM.format = function(path) {
	return DM.staticFileURL(path) + "?" + Environment.params.version;
}


var Attachment = function(name) {
  this.name = name;
  this.load(name);
};

Attachment.prototype = {
  load: function(name) {
    if (Environment.config.attach) this.inject(this.getNode())
  },
  
  getAttributes: function() {
    var ua = navigator.userAgent;
    var attrs = {tag: 'link', rel: 'Stylesheet', href: "/stylesheets/" + this.name + ".uri.css"}
    //IE8 + Non-IE
    if (!window.ActiveXObject || /MSIE 8./i.test(ua)) {
      attrs.href = "/stylesheets/" + this.name + ".css";
    } else {
      //IE7 on vista doesnt support MHT embedding.
      //MHT throws out security warning when is used with SSL
      if (!/NT 6.0/i.test(ua) && location.protocol != 'https:' && (Environment.config.mht != false)) {
        attrs = {
          tag: 'script',
          defer: 'defer',
          type: 'text/javascript',
          src: "/javascripts/compiled/" + this.name + ".mht.js"
        };
      }
    }
    return attrs;
  },
  
  getNode: function(name) {
    var attrs = this.getAttributes();
    var tag = attrs.tag
    delete attrs.tag

    if (attrs.src) attrs.src = DM.format(attrs.src);
    if (attrs.href) attrs.href = DM.format(attrs.href);

    var node = document.createElement(tag);
    for (var i in attrs) node[i] = attrs[i];

     return node;
  },
  
  inject: function(node) {
    document.getElementsByTagName('head')[0].appendChild(node);
  }
}

var DOMReady = function(func){
  var already = false;

  ready = function () {
    if (!already) {
      func();
      already = true;
    }
  };
  try {//opera, firefox
    document.addEventListener("DOMContentLoaded", ready, false);
  } 
  catch (e) { //ie
    timer = setInterval(function(){
      if (/loaded|complete/.test(document.readyState)) {
        clearInterval(timer);
        ready();
      }
    }, 20);
  }


  window.onload = function(){
    ready();
  };
};


new DOMReady(function() {
	new Attachment("mainpage")
	new Attachment("common")
});