var Nildog = {  
  cache: {},
  
  config: {
    uuid: 1,
    debug: 1,
    salt: $.now()
  },
  
  /*
    Function: bootstrap
    Runs before anything else.
    Add code here that you want to be executed for all pages.
  */
  bootstrap: function() {
    Nildog.log('Start er up!');
    
    $.extend(Nildog.cache, {
      test: function(el) {
        var caller = arguments.callee.caller.toString();          
        if (this[caller] == undefined)
          this[caller] = [];
        el = $(el);
        if (!el.data('uuid'))
          el.data('uuid', Nildog.config.uuid++);            
        id = el.data('uuid');
        if ($.inArray(id, this[caller]) == -1) {
          this[caller].push(id);
          return false;
        }
        return true;          
      },
      clear: function() {
       Nildog.cache = $.extend({}, { test: this.test, clear: this.clear }); 
      }
    });
    
    // this.fr('.head h1 a', ['.head ul a', { hover: true }]);
    
    this.dispatcher();
  },
  
  /*
    Function: dispatcher
    Attempts to execute the callback for the current page.
  */
  dispatcher: function() {
    var body = $.test('.body');
    if (body) {
      init = Nildog.log($.camelize('init_' + body.attr('id')));
      $.attempt(Nildog[init], Nildog);
    }
    
    Nildog.log('Ready!');   
  }
};

$.extend(Nildog, {

  /*
    Function: fr
    Helper to replace fonts with cufon.
  
    Parameters:
      - arguments: one or more selectors to replace
  */
  fr: function() {
    for (var i = 0, l = arguments.length; i < l; i++) {
      var args = $.splat(arguments[i]);
            
      Cufon.replace.apply(Cufon, args);
    }      
  },
  
  /*
    Function: carousel
    Bartalos-style carousel gallery.
  
    Parameters:
      - selector: css selector to add gallery behavior to
      - ops: options
  */
  carousel: function(selector, opts) {
    opts = $.extend({
      duration: 'normal',
      easing: 'easeOutBack',
      hash: true,
      loop: true
    }, opts || {}); 

    $(selector).each(function() {
      var self = $(this);      
      var prev = $('<a>'), next = $('<a>'), nav = $('<ul class="arrows">');
      var curr = 0, articles = $('.article', self), len = articles.length - 1;
      
      if (!len)
        return;
      
      if (opts.hash) {
        var id = window.location.hash.substr(1);
        if (id.length) {
          var ids = $.map(articles, function(article) {
            return article.id;
          });
          var i = $.inArray(id, ids);
          if (i != -1)
            curr = i; 
        }
      }
      
      articles.hide().each(function(i) {
        var header = $(this).find('.header');
        $('<p>').text('(' + (i + 1) + '/' + (len + 1)+ ')').prependTo(header);
      });

      var article = articles.eq(0).clone()
        .removeAttr('id').prependTo(self).bind('animate', function(e, i, p) {
          var article = $(this), section = article.find('.section'), figure = article.find('.figure'), pos = figure.width();
          article.find('img').stop(true, true);
          if (!opts.loop) {
            prev.toggleClass('disabled', (i == 0));
            next.toggleClass('disabled', (i == len));
          }
          var newArticle = articles.eq(i);
          section.empty().html(newArticle.find('.section').html());
          // prepare images
          var image = figure.find('img');
          var newImage = newArticle.find('.figure img').clone().css('left', pos * p * -1).appendTo(figure);
          if (p) { // animate
            image.animate({ left: pos * p }, opts.duration, opts.easing, function() { $(this).remove(); });
            newImage.animate({ left: 0 }, opts.duration, opts.easing);
          }
          else // firstrun
            image.remove();
          if (opts.hash)
            window.location.hash = "#" + newArticle.attr('id');
        }).trigger('animate', curr).show();

      prev.click(function() {
        if (prev.hasClass('disabled'))
          return false;
        curr -= 1;
        if (curr < 0)
          curr = len;
        article.trigger('animate', [curr, 1]);
      }).wrap('<li class="prev">').parent().appendTo(nav);

      next.click(function() {
        if (next.hasClass('disabled'))
          return false;
        curr += 1;
        if (curr > len)
          curr = 0;
        article.trigger('animate', [curr, -1]);
      }).wrap('<li class="next">').parent().appendTo(nav);

      nav.appendTo(self);

      $(window).keypress(function(e) {
        if (e.keyCode == 37) // left
          prev.trigger('click');
        if (e.keyCode == 39) // right
          next.trigger('click');
      });
    });
  },
  
  /*
    Function: log
    Logs output with a timestamp if debugging is enabled.
  
    Parameters:
      - str: variable to log
  */
  log: function(str) {
    if (this.config.debug && window.console) {
      if (!this.timestamp)
        this.timestamp = $.now();
        
      console.log(($.now() - this.timestamp) + ': ' + str);
    }
    
    return str;
  }
});

$.extend(Nildog, {
  // do dom stuff

  initBlog: function() {
    // this.fr('.section h2');
  },

  initPage: function() {
    var form = $('.section form').hide();
    
    $('<a>').text('Contact David Goldin').click(function() {
      form.slideDown();
    }).wrap('<p>').parent().insertBefore(form);
    
    // this.fr('.section h2, button');
  },

  initPageOfPosts: function() {
    this.carousel('.main');
  }

});

// start er up!

$(document).ready(function() {
  Nildog.bootstrap();
});