/*
  Over-engineered cookie getter and setter.
*/

var Cookie = (function(){

  var defaultOptions = {
    domain: window.location.hostname,
    path: '/'
  };

  return function(name, value, options){
    
    for (var p in defaultOptions) {
      if (defaultOptions.hasOwnProperty(p)) {
        this[p] = defaultOptions[p];
      }
    }
    
    if (typeof options === 'object') {
      for (p in options) {
        if (options.hasOwnProperty(p)) {
          this[p] = options[p];
        }
      }
    }
    
    this.name = name;
    this.value = value;
  };
  
})();

Cookie.prototype = {
  
  toCookieString: function(){
    var date = new Date(), expires;
    if (typeof this.expires === 'number') {
      date.setTime(date.getTime() + this.expires*24*60*60*1000);
      expires = '; expires=' + date.toGMTString();
    } else if (this.expires === true) {
      date.setTime(date.getTime() - 1000);
      expires = '; expires=' + date.toGMTString();
    } else {
      expires = '';
    }
    return this.name + '=' + this.value + expires + '; path=' + this.path;
  },
  
  toString: function(){
    return '<Cookie:' + this.name + ': ' + this.value + '>';
  }
  
};


var Cookies = [];

Cookies.findIndex = function(name){
  var index = -1;
  for (var i = 0; i < this.length; i++) {
    if (this[i].name === name) { index = i; break; }
  }
  return index;
};

Cookies.find = function(name){
  var i = this.findIndex(name);
  return i < 0 ? null : this[i];
};

Cookies.get = function(name){
  var c = this.find(name);
  return c && c.value;
};

Cookies.set = function(name, value, options){
  var c = (name instanceof Cookie) ? name : new Cookie(name, value, options);
  var existingIndex = this.findIndex(c.name);
  if (existingIndex >= 0) { this.splice(existingIndex, 1); }
  document.cookie = c.toCookieString();
  return this.push(c);
};

Cookies.remove = function(name){
  var i = this.findIndex(name);
  if (i > -1) {
    var c = this.splice(i, 1)[0];
    c.expires = true;
    document.cookie = c.toCookieString();
  }
};

Cookies.parse = function(cookieString) {
  var cookies = [],
      strings = cookieString.split(';'),
      i, j, segments, name, value;
      
  for (i = 0; i < strings.length; i++) {
    segments = strings[i].split('=');
    name = segments.shift().replace(/^ +| +$/g, '');
    value = segments.join('=');
    cookies.push(new Cookie(name, value));
  }
  
  return cookies;
};

Cookies.initialize = function(cookieString){
  if (typeof cookieString !== 'string') { cookieString = document.cookie; }
  var i, c;
  while (this.length) { this.pop(); }
  c = Cookies.parse(document.cookie);
  for (i = 0; i < c.length; i++) { this.push(c[i]); }
};

Cookies.initialize();




var Blahger = {};


//
// Extensions to Prototype's Element methods
//
Blahger.prototypeExtensions = {
  //Returns the content from all of this node and its descendants' text nodes
  getText: function(el){
    return $A(el.childNodes).inject('', function(s,n){
      return n.nodeType === 3 ? s+n.data : s+$(n).getText();
    });
  }
};

Element.addMethods(Blahger.prototypeExtensions);


Object.extend(Object, {
  inherit: function(o){
    function F(){};
    F.prototype = o;
    return new F();
  }
});

Object.extend(Function.prototype, {
  cache: function(){
    var orig = this,
        res;
    var replacement = function(){
      if (typeof res === 'undefined') {
        res = orig.apply(this, arguments);
      }
      return res;
    };
    replacement.original = orig;
    return replacement;
  }
});



//
//  Various functions
//
Object.extend(Blahger, {

  //All functions in this array will be run onDOMLoad
  //in the context of this object (Blahger)
  readyEvents: [],

  onReady: function(){
    var p;
    for (p in this.readyEvents) {
      if (this.readyEvents.hasOwnProperty(p)) {
        this.readyEvents[p].call(this);
      }
    }
  },

  pwitter: function(posts){
    var div = new Element('p', {id:'pwitter-posts'});
    posts.slice(0,5).each(function(post){
      post.photos.each(function(photo){
        var a = new Element('a', {href:post.url, title:post.title});
        a.insert({bottom:new Element('img', {src:photo.micro, alt:post.title})});
        div.insert({bottom:a});
      });
    });
    $('sidebar').insert({bottom:div});
  },

  toggleStyle: function(){
    var body = $$('body').first();

    this.toggleStyle = function(){
      ['boring', 'humbaba'].each(function(n){
        body.toggleClassName(n);
      });
      if (body.hasClassName('humbaba')) {
        Cookies.set('humbaba', true);
      } else {
        Cookies.remove('humbaba');
      }
    };
    this.toggleStyle();
  }
});

Blahger.readyEvents.push(function(){
  $$('a.textile-quick-reference').each(function(link){
    link.observe('click', function(e){
      e.stop();
      window.open(link.readAttribute('href'), 'textile_quick_reference', 'status=0,width=550,height=500');
    });
  });
});

Blahger.readyEvents.push(function(){
  if (Cookies.get('humbaba')) {
    Blahger.toggleStyle();
  }
});


document.observe('dom:loaded', function(){
  Blahger.onReady();
});


var KonamiKomando = function(fn){

  var keys = $w('UP UP DOWN DOWN LEFT RIGHT LEFT RIGHT').map(function(k){
        return Event['KEY_'+k];
      }).concat([98,97]),
      nextIndex = 0;

  document.observe('dom:loaded', function(){
    document.observe('keypress', function(e){
      var keyCode = e.keyCode || e.charCode;
      if (keyCode == keys[nextIndex]) {
        if (nextIndex == keys.length-1) {
          fn();
          nextIndex = 0;
        } else {
          nextIndex += 1;
        }
      } else {
        nextIndex = 0;
      }
    });
  });
  
};

KonamiKomando(function(){
  Blahger.toggleStyle();
});
