/*
-- CONSTANTS
---------------------------------------------------*/

// Stylesheet only in combination with JS...
// The DOM way has issues with Opera 9 and Safari, so we use document.write
// document.write('<link rel="stylesheet" media="screen" href="/?css=home/css_withjsonly" />');

// Extend String with getHash()
String.extend({
 getHash : function() {
  var hash = this.split('#');
  return (hash[1]) ? hash[1] : false;
 }
});

// Extend Array with shuffle()
Array.extend({
 shuffle : function() {
  for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
 }
});

/*
-- THROBBER CLASS
---------------------------------------------------*/

function Throbber(target) {
 this.target  = $(target);
 this.status  = 0;
 this.img     = new Element('img');
 this.img.src = arguments[1] || '/images/structure/throbber.gif';
 
 this.on = function() {
  if (this.status == 0) {
   $(this.target).appendChild(this.img);
   this.status = 1; 
  }
 }
 
 this.off = function() {
  if (this.status == 1) { 
   try { this.img.remove(); } catch(x) { /* already removed */ }
   this.status = 0;
  }
 }
 
 this.toggle = function() {
  if (this.status)
   this.off();
  else
   this.on();
 }
}



/*
-- YEARLY ARCHIVES
---------------------------------------------------*/

var YA = {
 target : 'result',
 
 load : function(url) {
  // turn on throbber
  YA.throbber.on();
  
  // construct url
  url = url.replace('africa-news', 'includes/news-archives');
  
  // proceed with ajax call
  new Ajax(url, {
   method:'get',
   update:YA.target,
   onComplete:function(r){
    YA.throbber.off();
    if (r.length) {
     $('result').effect('height',{duration:600,onComplete:function(){new Fx.Scroll(window,{duration:250}).toElement('ya');}}).start(0,YA.target.getStyle('height').toInt());
    }
   }
  } ).request();
 },
 
 get : function(e) {
  var ev = new Event(e);
  
  // cancel if key was pressed
  if (ev.shift || ev.control || ev.alt) return;
  
  // Wrap up
  $('result').effect('height',{
   duration:400,
   onComplete:function(){YA.load(ev.target.href);}
  }).start(0);
  
  // cancel default event
  ev.preventDefault();
 },

 init : function() {
  window.addEvent('load',function() {
   // do nothing if there aren't yearly archives
   if (!$('ya')) return;
   $(YA.target).setStyle('overflow','hidden');

   // init throbber
   var thr = new Element('span');
   thr.id  = 'ya-throbber';
   thr.injectAfter('result');
   YA.throbber = new Throbber(thr);
   
   var div = new Element('div');
   div.id  = 'ya-target';
   div.injectInside(YA.target);
   YA.target = div;

   // add event to each link
   $$('#ya a').each(
    function(el) {
     el.addEvent('click',YA.get);
    }
   ); // end each

  }); // end addevent
 } // end init
}
YA.init();


