var recently_viewed = function(spec) {
  
  spec = spec || {};
  
  var recently_viewed = [],
      container = spec.container || $('#recently-viewed'),
      history_size = 5,
      current_page = {url: document.location.toString(), title: document.title.replace(/ *(.+) \| BakerHughes\.com.*/g, '$1')};
  
  var storeHistory = function() {
    if(recently_viewed.length >= history_size) {
      recently_viewed.pop();
    }
    recently_viewed.unshift(current_page);
    
    $.cookies.set('recently_viewed', JSON.stringify(recently_viewed));
  };
  
  var getHistory = function() {
    var cookie = JSON.stringify($.cookies.get('recently_viewed') || []);
    
    cookie = JSON.parse(cookie);
    
    return cookie;
  };
  
  var hasHistory = function() {
    return recently_viewed.length > 0 ? true : false;
  };
  
  var inHistory = function() {
    var found = false;
    
    $.each(recently_viewed, function() {
      if(this.title.match(current_page.title)) {
        found = true;
      }
      return !found;
    });
    
    return found;
  };

  recently_viewed = getHistory();

  if(hasHistory()) {
    var history_list = $('<ul></ul>');
    
    $.each(recently_viewed, function() {
      $('<a></a>', {
        text: this.title,
        href: this.url
      }).appendTo($('<li></li>').appendTo(history_list));
    });
    
    container.append(history_list).show();
  }
  
  if(!inHistory()) {
    storeHistory();
  }
  
};

$(function() {
  recently_viewed();
});
