var modules = {
  load:function(){
    this.actions = new this.loadActions();
  },
  
  //{{{ setCMSSiteVar:(options)
  setCMSSiteVar:function(options) {
    
    var name    = options.name;
    var value   = options.value;
    var url     = (options.url)? options.url : CoreSiteVars.this_url;
    //var refresh = (options.refreshOnComplete)? options.refreshOnComplete : false;
    
    var params  = 'CMSSiteVars='+name+':'+value;
    
    this.sendAsync({
      url:url,
      params:params,
      onLoad:function(){},
      onSuccess:function(){
        if(typeof(options.refreshOnComplete)=='function'){
          options.refreshOnComplete();
        }
        else if(typeof(options.refreshOnComplete)=='string'){
          location.href = unescape(options.refreshOnComplete);
        }
        else if(options.refreshOnComplete==true){
          if(location.search.indexOf(name)!=-1){ //Can't have a url param with the same name as the CMSSiteVar, values will be different
            var length = name.length;
            var searchArray = location.search.split('&');
            for(x = 0; x < searchArray.length; x++){
              if(searchArray[x].indexOf(name)!=-1){ searchArray.splice(x,1); }
            }
            location.search = searchArray.join('&');
          }
          else{
            location.reload();
          }
        }
      }
    })
  }, //}}}
  
  //{{{ readCookie:function(name)
  readCookie:function(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
  }, //}}}
  
  //{{{ sendAsync:function(options)
  sendAsync:function(options){

    //options.onLoad, onSuccess, onFail need to be sent as onLoad:function(){ ... do something ...}

    var adminUrl   = (options.url)? options.url : '/admin';
    var params     = (options.params)? options.params : '';
    var evScripts  = (options.evalScripts==false)? false : true;
    var sendMethod = (options.sendMethod)? options.sendMethod : 'post';
    var async      = (options.async)? options.async : true;
    var updateElem = (options.updateElem)? $(options.updateElem) : false;
    var periodic   = (options.periodic==true)? true : false;
    var freq       = (options.frequency)? options.frequency : 15;
    var decay      = (options.decay)? options.decay : 1;

    var allParams  = {
      asynchronous:async,
      method:sendMethod,
      evalScripts:evScripts,
      parameters:params,
      onLoading:function(){
        if(typeof(options.onLoad) == 'function'){
          options.onLoad();
        }
        else{
          this.showAlert('Sending Data')
        }
      },
      onSuccess:function(req){
        if(typeof(options.onSuccess) == 'function'){
          options.onSuccess(req);
        }
        else{
          this.hideAlert();
        }
      },
      onFailure:function(){
        if(typeof(options.onFail) == 'function'){
          options.onFail();
        }
        else{
          alert("The server has returned an error.");
          try{
            if(typeof(Lightbox)!='undefined'){
              Lightbox.base.hideBox();
            }
            this.hideAlert();
          }
          catch(err){
          }
        }
      },
      onException:function(req,err){
        if(typeof(options.onException) == 'function'){
          options.onException();
        }
        else{
          if(window.console){console.log(err);}
          //alert("ajax exception caught");
        }
      }
    }
    
    if(options.onComplete){
      allParams.onComplete = function(req){
        options.onComplete(req);
      }
    }
    if(options.onLoaded){
      allParams.onLoaded = function(req){
        options.onLoaded(req);
      }
    }
    /* for(props in options){
      console.log(props);
    } */
    
    if(periodic){
      allParams.frequency = freq;
      allParams.decay     = decay;
      return new Ajax.PeriodicalUpdater(updateElem,adminUrl,allParams);
    }
    else if(updateElem){
      new Ajax.Updater(updateElem,adminUrl,allParams)
    }
    else{
      new Ajax.Request(adminUrl,allParams)
    }
  }, //}}}

  //{{{ sanitizeResponse:function(req, options)
  sanitizeResponse:function(req, options){
    //console.log(req);
    var sanitizedResponse = (req.responseText)? req.responseText.stripTags().evalJSON(true) : req.stripTags().evalJSON(true) ;
    //console.log(sanitizedResponse);
    if(sanitizedResponse.status == 'failure'){
      if(typeof(options.ifFail) == 'function'){
        options.ifFail();
      }
      else{
        var failOptions = {
          type:'alert',
          content:{
            msg:'Error: '+sanResponse.reason
          }
        }
        sanResponse.message = new Lightbox.base('cmsContextMenuDiv', failOptions);
      }
    }
    else{
      if(typeof(options.ifSuccess) == 'function'){
        options.ifSuccess();
      }
      else{
        return sanitizedResponse
      }
    }
  }, //}}}
  
  //{{{ ieBackCompat:function(elem)
  ieBackCompat:function(elem){
    if((typeof(elem.currentStyle)!='undefined')&&(typeof(elem.currentStyle.hasLayout)=='boolean')&&(document.body)){ //was document.body
      
      var vIndex = window.navigator.appVersion.indexOf('MSIE');
      var ieAppVersion = parseFloat(window.navigator.appVersion.substring(vIndex+5));
      
      if(document.compatMode=='BackCompat' || ieAppVersion <= 6){
        return ieAppVersion;
      }
    }
    return false;
  }, //}}}
  
  //{{{ showAlert:function(msg)
  showAlert:function(msg){

    //alert('window.screenY = '+window.screenY + '\n' + 'window.pageYOffset = '+window.pageYOffset + '\n' + 'document.body.scrollTop = '+document.body.scrollTop);


    var menuDiv = $('cmsContextMenuDiv');
    if(menuDiv){
      //cmsUI.hideAlert();
    }
    else{
      var menu_obj = document.createElement('div');
      menu_obj.setAttribute('id','cmsContextMenuDiv');
      window.document.body.appendChild(menu_obj);
      menuDiv = $(menu_obj);
    }

    var div_obj,msg_obj,txt_obj;
    div_obj = document.createElement('div');
    div_obj.className = 'cmsDropShadow';
    div_obj.setAttribute('id','cmsDropShadow');
    msg_obj = document.createElement('div');
    msg_obj.className = "cmsContextMessage"
    msg_obj.setAttribute('id','cmsContextMessage');
    txt_obj = document.createElement('span');
    txt_obj.setAttribute('id','cmsTextMessage');

    var txtText_obj = document.createTextNode(msg);
    txt_obj.appendChild(txtText_obj);
    msg_obj.appendChild(txt_obj);
    div_obj.appendChild(msg_obj);
    //set message

    menuDiv.appendChild(div_obj)

    var divObj = $(div_obj);
    var txtObj = $('cmsTextMessage');

    menuDiv.style.visibility = 'visible';
    menuDiv.style.display = 'none';

    //set container styles, visibility
    menuDiv.style.position = 'absolute';

    //set position
    menuDiv.style.top = '30%'; //TODO - make this a proper centered position
    menuDiv.style.width = '50%';
    menuDiv.style.left = '25%';
    menuDiv.style.right = '25%';
    menuDiv.style.textAlign = 'center';
    menuDiv.style.zIndex   = '10000';
    menuDiv.style.display = 'block';
  }, //}}}
  
  //{{{ hideAlert:function()
  hideAlert:function(){
    var menuDiv = $('cmsContextMenuDiv');
    var textDiv = $('cmsDropShadow');
    menuDiv.removeChild(textDiv);
    Element.toggle(menuDiv);
  } //}}}

  
}

modules.loadActions = function(){
  /* allowing additional prototyped functions to be called */
  
  for(funct in this){
    if(typeof(this[funct]) == 'function'){
      try {
        this[funct]();
      } catch(e) {}
        
    }
    
  }
  
}

/* calling the main loader function on window load */
try {
  if(typeof(Prototype!='undefined')){
    Event.observe(window, 'load', function(){
      modules.load();
      
      if(window.console)console.dir(modules);
      
    }.bind(modules));
  }
}
catch(e){}

//{{{ make non-firebug browsers ignor all the firebug console calls...
if (! ("console" in window) || !("firebug" in console)) {
  var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
  window.console = {};
  for (var i = 0; i <names.length; ++i) window.console[names[i]] = function() {};
}
//}}}



