var EmbedTweet =
{
  // CONFIGURATION
  enableDebugging: false,
  automaticEmbedding: true, // set to false to disable automatic embedding and use embedClass to manually embed

  // DONT CHANGE THIS
  objRegex: /http(s)?:\/\/twitter\.com\/([a-z0-9]+)\/status(es)?\/([0-9]+)/i, // Regex to find twitter status links
  doEmbedClass: 'EmbedTweet',
  dontEmbedClass: 'dontEmbedTweet',

  $: function(element)
  {
  	var elements = new Array();
  	for (var i = 0; i < arguments.length; i++) {
  		var element = arguments[i];
  		if (typeof element == 'string')
  			element = document.getElementById(element);
  		if (arguments.length == 1)
  			return element;
  		elements.push(element);
  	}
  	return elements;
  },

  addLoadEvent: function(func)
  { 
    var oldonload = window.onload; 
    if (typeof window.onload != 'function') { 
      window.onload = func; 
    } else { 
      window.onload = function() { 
        if (oldonload) { 
          oldonload(); 
        } 
        func(); 
      } 
    } 
  },

  insertAfter: function(newElement,targetElement)
  {    
    
  	//target is what you want it to go after. Look for this elements parent.
  	var parent = targetElement.parentNode;

  	//if the parents lastchild is the targetElement...
  	if(parent.lastchild == targetElement) {
  		//add the newElement after the target element.
  		parent.appendChild(newElement);
  		} else {
  		// else the target has siblings, insert the new element between the target and it's next sibling.
  		// console.log(parent);
  		// console.log(newElement);
  		// console.log(targetElement);
  		// console.log(targetElement.nextSibling);
  		// parent.insertBefore(newElement, targetElement.nextSibling);
  		}
  },

  hide: function(element)
  {
    element = EmbedTweet.$(element);
    element.style.display = 'none';
    return element;
  },
  
  getAnchorsByClassName: function(classname, node)
  {
    if(!node) node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("a");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
  },
  
  getAnchorsWithoutClassName: function(classname, node)
  {
    if(!node) node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("a");
    for(var i=0,j=els.length; i<j; i++)
        if(!re.test(els[i].className))a.push(els[i]);
    return a;    
  },
  
  // FUNCTION - debug
  // Outputs debugging messages
  debug: function(msg)
  {
    if(this.enableDebugging) console.log(msg);
  },
  
  // FUNCTION - handleTweet
  // Every anchor that should me transformed into an embedded Tweet is passed to this function
  handleTweet: function(link)
  {
    if(this.objRegex.test(link.href))
  	{
      // @todo: Transfer classes on the anchor to the generated embedtweet div

    	// get the tweet status id used by Twitter to identify tweets
    	temp = link.href.split(/(\/)/);
    	id = temp[ temp.length - 1 ];

    	// include the embedtweet javascript file
    	// which will call contentLoad to embed itself
    	this.includeScript('http://embedtweet.com/embed/' + id);

    	// give the anchor an id, so we'll know where to place the tweet div
    	// @todo: If the anchor already has an ID it is replaced. Perhaps using a classname is more flexible.
    	link.id	= "embedtweet_link_" + id;

    	// hide original link
    	EmbedTweet.hide(link);
    }
  },

  // FUNCTION - includeScript
  // Includes a javascript file by creating a script-tag.
  includeScript: function(url)
  {
  	var head			= document.getElementsByTagName('head')[0];
  	var script		= document.createElement('script');
  	script.type		= 'text/javascript';
  	script.src		= url;
  	head.appendChild(script);
  },

  // FUNCTION - includeStylesheet
  // Includes a stylesheet by creating a link-tag.
  includeStylesheet: function(url, media)
  {
  	var head		= document.getElementsByTagName('head')[0];
  	var link		= document.createElement('link');
  	link.type		= 'text/css';
  	link.href		= url;
  	link.media	= media;
  	link.rel		= 'stylesheet';
  	head.appendChild(link);
  },

  // FUNCTION - contentLoaded
  // This function is called by the embedtweet js file.
  // It inserts the generated html where the anchor used to be.
  contentLoaded: function(id, tweet_html)
  {
    tweet_div = document.createElement('div');
    tweet_div.innerHTML = tweet_html;
  	EmbedTweet.$("embedtweet_link_" + id).parentNode.insertBefore(tweet_div, EmbedTweet.$("embedtweet_link_" + id));
  },
  
  // FUNCTION - init
  // Sets everything up
  init: function()
  {
    EmbedTweet.debug('EmbedTweet javascript library loaded.');

  	// Include stylesheet
  	// @todo: Include print stylesheet
  	EmbedTweet.includeStylesheet('http://embedtweet.com/stylesheets/embed_v2.css', 'screen');

  	// When the page is loaded, start
  	EmbedTweet.addLoadEvent(function() { EmbedTweet.start(); } );
  },
  
  // FUNCTION - start
  // Loops through all the anchors, checks if it should be transformed and does if necessary
  start: function()
  {
    // Converts all anchors linking to tweets to 'embedded tweets'
    // Links with the dontEmbedTweet are skipped
    EmbedTweet.debug('Initializing EmbedTweet');

    var links = new Array();

    if(this.automaticEmbedding)
    {
      // Find all anchors, except with the ones with dontEmbedClass
      links = EmbedTweet.getAnchorsWithoutClassName(this.dontEmbedClass);
    }
    else
    {
      // No automatic embedding, only embed the ones with doEmbedClass
      links = EmbedTweet.getAnchorsByClassName(this.doEmbedClass);
    }            
    // For each anchor check if it links to a tweet and handle it
    //links.invoke.call('EmbedTweet', 'handleTweet');
    for(var i=0; i < links.length; i++)
    {
      EmbedTweet.handleTweet(links[i]);
    }
  }

};

// initiate EmbedTweet
EmbedTweet.init();