var modules = {
  modulesLoaded:false,
  load:function(){
    this.actions = new this.loadActions();
    this.modulesLoaded = true;
  },
  
  //{{{ test:function(a,b)
  test:function(a,b){
    if(a == b){
      return true;
    }
    else{
      return false;
    }
  }, //}}}
  
  //{{{ 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{
          //modules.showAlert('Sending Data')
        }
      },
      onSuccess:function(req){
        if(typeof(options.onSuccess) == 'function'){
          options.onSuccess(req);
        }
        else{
          //modules.hideAlert();
        }
        Event.fire(window, 'ajax:general-success');
      },
      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();
            }
            //modules.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.onCreate){
      allParams.onCreate = function(){
        options.onCreate();
      }
    }
    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.trace();
    //console.dir(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;
  }, //}}}
  
  //{{{ ieVersion:function(elem)
  ieVersion: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));
      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);
  }, //}}}
  
  //{{{ addLoadingClass:function(elem, classN)
  addLoadingClass:function(elem, classN){
    elem.style.display = 'block';
    elem.style.height = '200px';
    Element.addClassName(elem, classN);
  }, //}}}
  
  //{{{ removeLoadingClass:function(elem, classN)
  removeLoadingClass:function(elem, classN){
    elem.style.height = 'auto';
    Element.removeClassName(elem, classN);
  } //}}}

}

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){} */
if('Prototype' in window){
  document.observe('dom:loaded', function(){
    modules.load();
    
    //if(window.console)console.dir(modules);
    
  });
}

modules.loadActions.prototype.asyncModule = function(){
  
  var asyncModule  = this.asyncModule;
  
  asyncModule.load = function(){
    asyncModule.objs = SiteVars.modules.ajaxLoader;
    for(obj in asyncModule.objs){
      //console.log(typeof(asyncModule.objs[obj]));
      if('url' in asyncModule.objs[obj]){
        modules.sendAsync(asyncModule.objs[obj]);
      }
    }
  }
  if('ajaxLoader' in SiteVars.modules){
    asyncModule.load();
  }
}


modules.loadActions.prototype.weatherExt = function(){
  var wExt = this.weatherExt;
  wExt.mLink = $$(".dwidget-weather .more .weather-statewide")[0];
  wExt.localTime = $$(".dwidget-weather .more #local-time")[0];
  
  wExt.amPhrase = (SiteVars.modules.Weather.phrases.am!='') ? SiteVars.modules.Weather.phrases.am : 'am' ;
  wExt.pmPhrase = (SiteVars.modules.Weather.phrases.pm!='') ? SiteVars.modules.Weather.phrases.pm : 'pm' ;
  
  wExt.load = function(){
    
    Event.observe(wExt.mLink, 'click', function(e){
        
        var activeIsland = $$(".dwidget-weather .dwidget-weather-container.selected")[0]
        
        switch(activeIsland.id){
          case 'dropdown_kauai':
            wExt.mLink.href = SiteVars.path_to_top + "/kauai/about/kauai-weather";
            break;
          case 'dropdown_oahu':
            wExt.mLink.href = SiteVars.path_to_top + "/oahu/about/weather";
            break;
          case 'dropdown_molokai':
            wExt.mLink.href = SiteVars.path_to_top + "/molokai/about/weather";
            break;
          case 'dropdown_lanai':
            wExt.mLink.href = SiteVars.path_to_top + "/lanai/about/weather";
            break;
          case 'dropdown_maui':
            wExt.mLink.href = SiteVars.path_to_top + "/maui/about/maui-weather";
            break;
          case 'dropdown_big-island':
            wExt.mLink.href = SiteVars.path_to_top + "/big-island/about/weather";
            break;
        }
    });
    
  }
  
  wExt.loadTime = function(){
    
    wExt.date = new Date();
    
    //time zone offsets expressed im milliseconds
    var localOffset = new Number(wExt.date.getTimezoneOffset() * 60 * 1000); 
    var hstOffset = 600 * 60 * 1000; //never uses daylight savings 
    
    //set time to GMT based on client machine's time zone offset
    wExt.date.setTime(wExt.date.getTime() + localOffset);
    
    //extra steps to test as JST time zone
    //var jpTest = new Number(-540 * 60 * 1000); 
    //set time from GMT to JST based on jpTest offset
    //wExt.date.setTime(wExt.date.getTime() - jpTest);
    //set time from JST to GMT based on jpTest offset
    //wExt.date.setTime(wExt.date.getTime() + jpTest);

    //then set time from GMT to HAST based on hstOffset
    wExt.date.setTime(wExt.date.getTime() - hstOffset);
    
    //write the time to the screen
    var h = (wExt.date.getHours() > 12) ? wExt.date.getHours()-12 : wExt.date.getHours();
    var m = (wExt.date.getMinutes() < 10) ? "0"+wExt.date.getMinutes() : wExt.date.getMinutes();
    var amPm = (wExt.date.getHours() >= 12) ? wExt.pmPhrase : wExt.amPhrase;
    wExt.localTime.innerHTML = h + ":" + m + amPm;
    
    //time in milliseconds until the next update
    var fullMinute = 59000;
    var secondsOffset = wExt.date.getSeconds() * 1000;
    var diff = fullMinute - secondsOffset;

    window.setTimeout(modules.actions.weatherExt.loadTime,diff);
  }
  
  if(wExt.mLink){
    wExt.load();
  }
  else if(wExt.localTime){
    wExt.loadTime();
  }
}

modules.loadActions.prototype.trackedLinks = function(){
  var tracked = this.trackedLinks;
  tracked.extlinks = $$(".ext-tracked-link");
  tracked.single = $$(".single-tracked-link");
  
  if(tracked.extlinks[0]){
    tracked.extlinks.each(function(link){
        Event.observe(link, 'click', function(e){
            tracked.extCall(link);
        });
    });
  }
  
  if(tracked.single[0]){
    tracked.single.each(function(link){
        Event.observe(link, 'click', function(e){
            tracked.singleCall(link);
        });
    });
  }
  
  tracked.extCall = function(link){
    var s=s_gi(s_account);
    s.linkTrackVars='eVar13,events';
    s.linkTrackEvents='event4';
    s.eVar13=link.text;
    s.events='event4';
    s.tl(this,'e',link.href);
  }
  
  tracked.singleCall = function(link){
    var s=s_gi(s_account);
    s.linkTrackVars='eVar13,events';
    s.linkTrackEvents='event4';
    s.eVar13=link.text;
    s.events='event4';
    s.tl(this,'e',link.href);
  }
}


//{{{ make non-firebug browsers ignor all the firebug console calls...
if (!("console" in window)) {
  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() {};
}
//}}}


/* Temp fix for cmscore stuff */
if(typeof(cmsMenusUI)!='undefined'){
cmsMenusUI.menuItemActions = function(options){

  var adminUrl = (options.url)? options.url : '/admin';
  var confirmmsg = (options.confirmmsg) ? options.confirmmsg : null ;
  var statusmsg = (options.statusmsg) ? options.statusmsg : null ;
  var params = (options.params) ? options.params : null ;
  var evScripts = (options.evScripts==false) ? false : true;
  
  if(confirmmsg && "base" in CMSLightbox){
    new CMSLightbox.base('cmsContextMenuDiv', {
        createDraggable:true,
        type:'form',
        content:{
          heading:'<h1>Are you Sure?</h1>',
          msg:confirmmsg
        },
        action:{
          url:adminUrl+ '?' + params,
          msg:statusmsg,
          onLoad:options.onLoad,
          onSuccess:options.onSuccess
        }
    });
  }
  else if(confirmmsg){
    //console.dir(options);
    if(confirm(confirmmsg)){
      cmsUI.sendAsync({
          url:adminUrl,
          params:options.params,
          evalScripts:evScripts,
          onLoad:options.onLoad,
          onSuccess:options.onSuccess
      });
    }
  }
  else{
    //Update!!!
    cmsUI.sendAsync({
        url:adminUrl,
        params:options.params,
        evalScripts:evScripts,
        onLoad:options.onLoad,
        onSuccess:options.onSuccess
    });
  }
}
}

if(typeof(cmsUI)!='undefined'){
cmsUI.hideAlert = function(){
  var menuDiv = $('cmsContextMenuDiv');
  var textDiv = $('cmsDropShadow');
  if (menuDiv){
    if (textDiv){
      menuDiv.removeChild(textDiv);
    }
    Element.toggle(menuDiv);
  }
  if("base" in CMSLightbox){CMSLightbox.hideAll()}//console.dir(Lightbox) }
  showingMessage = false;
}
}



//{{{ Omniture Site Catalyst Scripts specificly created for this website:
var omniSearchRefresh = function(resultsFound,searchBucket){
  if (resultsFound) {
    s=s_gi(SiteVars.omniture_id);  
    s.linkTrackVars="prop4,eVar2,events"; 
    s.linkTrackEvents="event1";
    s.events="event1";
    s.tl(this,'o','Refreshed Search Results');
  } else {
    /*  hacky hacky: only set it as a failed search
       if its the second ajax refresh search (partner)
       and the first ajax refresh search (topic) set did NOT find any results
       OR we are the first ajax refresh search (topic) */
    if ((s.events.indexOf('event1')== -1 && searchBucket =='partner') || searchBucket =='topic') {
      s=s_gi(SiteVars.omniture_id);  
      s.linkTrackVars="prop4,eVar2,events"; 
      s.linkTrackEvents="event5";
      s.events="event5";
      s.tl(this,'o','Refreshed Search Results');
    };
  }

}
//}}}



//{{{ overrides for form controls (from cmscore.js)
function getMultiValueOverride(element)
{
  return getMultiValueOverrideWithForm(element.form, element.name);
}

function getMultiValueOverrideWithForm(f,name)
{
  
  //console.log(f);
  //console.log(name);
  
  var result = "";
  for (var i=0; i<f.elements.length; i++) {
    if (f.elements[i].name == name && f.elements[i].checked) {
      result += f.elements[i].value + "|";
    }
  }
  
  return result;
  
  
} //}}}



function outputStatus(e) {
	if (e.success == false) { 
		$$('#imageobj a span')[0].style.display="block";
	}	
}




