/**
* the 'classic' ui, so-named because it was the first one.
*/

// *********************** original demo specific code *********************************

	var urlPattern = /(https?:\/\/[a-zA-Z0-9;_\-\/\?=\!%\+\'\&|\.#]+)/g;
	var userPattern = /(@[a-zA-Z0-9_\-]+)/g;
	var tagPattern = /(#[a-zA-Z0-9_\-]+)/g;
	
	jsPlumb.DEFAULT_ENDPOINT = new jsPlumb.Endpoints.Dot({radius:5});
	jsPlumb.DEFAULT_PAINT_STYLE = { lineWidth: 1, strokeStyle:'#ccc' };
	HIGHLIGHT_PAINT_STYLE = { lineWidth: 2, strokeStyle:'yellow' };
	jsPlumb.DEFAULT_CONNECTOR = new jsPlumb.Connectors.Bezier(77);
	var tagAnchors = [ jsPlumb.makeAnchor(1,0.5,1,0), jsPlumb.makeAnchor(0,0.5,-1,0)];
	var userAnchors = [ jsPlumb.makeAnchor(0,0.5,-1,0), jsPlumb.makeAnchor(1,0.5,1,0)];

	/**
	 * Callback for Twitter search call.  
	 * @param tweetSet
	 */
	var searchHandler = function(tweetSet) {
		
		jsPlumb.detachEverything();
				
		$("#output").html(""); $("#users").html(""); $("#tags").html("");
		var tweets = tweetSet.getTweets();
		$.each(tweets, function(index) {
			var d = markupTweet(tweets[index]);
			$("#output").append(d);
		});

		// process users (page specific)
		var users = tweetSet.users.getDataInOrder();
		for (var i = 0; i < users.length; i++)
			$("#users").append(tmpl("user_tmpl", {user:users[i][1], index:i}));

		// now process tags (page specific)
		var tags = tweetSet.tags.getDataInOrder();
		for (var i = 0; i < tags.length; i++)
			$("#tags").append(tmpl("tag_tmpl", {tag:tags[i][1], index:i}));

		var ctx = $("#output")[0];
		$(".taggedUser").click(function() {			
			var html = $(this).html().trim();	
			search(html, true);
			return false;
		});			
		$(".tag").click(function() {
			search($(this).html().trim(), true);
			return false;
		});

		$(".from").click(function() {
			search("@" + $(this).html(), true);
			return false;
		});
		
		$(".aTweet,.tag,.taggedUser").hover(function() {
			var cons = jsPlumb.getConnections($(this).attr("id"));
			$.each(cons, function(i) {
				var con = cons[i];
				con.paintStyle = HIGHLIGHT_PAINT_STYLE;
				$(con.source).css("backgroundColor","#fff21b");
				$(con.target).css("backgroundColor","#fff21b");
			});
			jsPlumb.repaint($(this).attr("id"));
		}, function() {
			
			
			var findColor = function(el, c1, c2) {
				if (el.attr("odd") != null) 
					return c1;
				else
					return c2;
			};
			
			var cons = jsPlumb.getConnections($(this).attr("id"));
			$.each(cons, function(i) {
				var con = cons[i];
				con.paintStyle= jsPlumb.DEFAULT_PAINT_STYLE;
				$(con.source).css("backgroundColor",findColor($(con.source), "#f3f3f3", "white"));
				$(con.target).css("backgroundColor",findColor($(con.target), "#f3f3f3", "white"));
			});
			jsPlumb.repaint($(this).attr("id"));
		});
		
		$.each(tweets, function(index) {
			var users = tweets[index].users.getData();
			$.each(users, function(idx) {
				var user = users[idx];
				var t = "u_" + user.substring(1);
				$("#t_" + index).plumb({target:t, anchors:userAnchors, endpointsOnTop:false,draggable:false/*true, dragOptions:{revert:true}*/});
			});
			
			var tags = tweets[index].tags.getData();
			$.each(tags, function(idx) {
				var tag = tags[idx];
				var t = "t_" + tag.substring(1);
				$("#t_" + index).plumb({target:t, anchors:tagAnchors,endpointsOnTop:false,draggable:false/*true, dragOptions:{revert:true}*/});
			});
		});				
	};

	/**
	 * executes a search.
	 */
	function search(value, append) {
		value = value || $("#txtInput")[0].value;
		if (value != null && value.length > 0) {
			$("#txtInput")[0].value = value;
			window.location.hash = encodeURIComponent(value);
			var s = (value.substring(0,1) == '#') ? "\\"  + value : value;
			TweetPlumb.search(s, searchHandler);
			if (append) $("#recent").append(tmpl("recent_tmpl", {term:value}));
		}
	}	

	/**
	* does markupTweet for a Tweet.  this involves adding anchors for users, tags and links.
	*/
	function markupTweet(tweet) {
		// get the markup
		var h = tmpl("tweet_tmpl", tweet.data);
		// make replacements
		h = h.replace(urlPattern, "<a target=\"_blank\" href=\"$1\">$1</a>");
		h = h.replace(userPattern, "<span class=\"taggedUser\">$1</span>");
		h = h.replace(tagPattern, "<span class=\"tag\">$1</span>");
		return h;
	}

// ************************** end of page-specific code **********************************


// ************************** john resig's simple js templating **************************	
// ************************** also page-specific right now in fact. ***********************
// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function(){
  var cache = {};
 
  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :
     
      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +
       
        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +
       
        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");
   
    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();


