/*global document, clearInterval, escape, jQuery, setInterval, twip_1, window */

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

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

String.prototype.linkify = function() {
	
  return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&;\?\/.=]+/g,function(m){
    return m.link(m);
  });
	
};

String.prototype.linkuser = function() {
	
  return this.replace(/[@]+[A-Za-z0-9-_]+/g,function(u){
    return u.link("http://twitter.com/"+u.replace("@",""));
  });
	
};

String.prototype.linktag = function() {

  return this.replace(/[]+[A-Za-z0-9-_]+/,function(t){
    return t;
  });
  
};

function query_string(qs) {
	
  return escape( qs );
	
}

function Twip(num) {

  this.twipnum = num;
  this.lastid = 0;
  this.gettimer = "";
  this.displaytimer = "";
  this.tweetcount = 0;
  this.geo = "";
  this.tweets = [];
  this.units = "";
  this.radius = "";
  this.location = "";

}

Twip.prototype.get_tweets = function() {

  var twipnum = this.twipnum;
  var selfobject = this;
  
  var search_criteria = query_string( document.getElementById('criteria_' + twipnum).value );
  var url = "http://search.twitter.com/search.json?rpp=20&since_id=" + this.lastid + "&q=" + search_criteria + "&callback=?";
  
  if( document.getElementById('location').value ) {
	  
    var units = document.getElementById('units').value;
    var radius = document.getElementById('radius').value;
    
    var getgeo = new String(this.geo);
    var sp = getgeo.split(",");
    
    if( sp[0] !== "none" ) {
	    
	    var geocode = sp[1] + "%2C" + sp[0] + "%2C" + radius + units;
	    url = "http://search.twitter.com/search.json?rpp=20&since_id=" + this.lastid + "&geocode=" + geocode + "&q=" + search_criteria + "&callback=?";
	  
    }
	    
  }
  
  jQuery.getJSON(url, 
    function(data) {
	    
	var results = data.results;
	
	if ( results[0] ) {
		
	  selfobject.lastid = results[0].id;
	  results.reverse();

	  for ( var i = 0; i < results.length; i++ ) {
		
	    selfobject.tweets.push( results[i] );
		    
	  }
	
	}
	
  });
	
  return false;	
	
};

Twip.prototype.update_location = function() {

  var li = document.createElement("li");
  var p = document.createElement("p");
  
  if( this.location ) {
  
    var units = document.getElementById('units').value;
    var radius = document.getElementById('radius').value;
	  
    p.innerHTML = 'Tweets containing "' + document.getElementById('criteria_' + this.twipnum).value + '" within ' + radius + units + ' of ' + this.location + '.';
	  
  } else { 
  
    p.innerHTML = 'Tweets containing "' + document.getElementById('criteria_' + this.twipnum).value + '".';
  
  }
	  
  p.setAttribute("class", "used_above");
  p.style.cssText = "display: inline; vertical-align: bottom;";
  li.appendChild(p);

  var img = document.createElement("img");
  img.src = 'img/rss.png';
  img.setAttribute("class", "rss");
  img.style.cssText = "width: 10px; height: 10px; margin: 0px; margin-left: 10px; float: none;";
  
  var a = document.createElement("a");
  a.href = 'http://search.twitter.com/search.atom?q=' + query_string( document.getElementById('criteria_' + this.twipnum).value );
  a.target = '_blank';
    
  a.appendChild(img);
  
  li.appendChild(a);
  
  document.getElementById('twitext_' + this.twipnum).insertBefore(li, document.getElementById('twitext_' + this.twipnum).firstChild);
      
  
  this.get_tweets();	
	
};

Twip.prototype.set_geocode = function() {
	
  var twipnum = this.twipnum;
  var selfobject = this;
  
  var apikey = 'ABQIAAAAH4aiN2FBAiXu-LcrpMH6lBRBm7PnioRkZ1m3CHUGLCNlDanM-hRv8-Y0ILlEvXp0k_Dph5acLp78tA';	
  
  jQuery.getJSON("http://maps.google.com/maps/geo?q=" + escape( document.getElementById('location').value ) + "&output=json&oe=utf8&sensor=false&key=" + apikey + "&callback=?", 
  function(data) {
	
    if( data.Status.code === 200 ) {
		
      if( data.Placemark === undefined ) {

        selfobject.location = "";	
	selfobject.geo = "none";
	      
      } else { 
      
	selfobject.location = data.Placemark[0].address;
	selfobject.geo = data.Placemark[0].Point.coordinates;
      
      }
      
      selfobject.update_location();
      
    } else {
	
      selfobject.location = "";	    
      selfobject.geo = "none";
      selfobject.update_location();
	    
    }
	
  });
	
};

Twip.prototype.display_tweets = function() {
	
  if( this.tweets[0] ) { 
	  
    var twip_tweets = this.tweets;
	  
    var li = document.createElement("li");
    
    var img = document.createElement("img");
    img.src = twip_tweets[0].profile_image_url;
    img.width = '48';
    
    var p = document.createElement("p");
    p.innerHTML = twip_tweets[0].text.linkify().linkuser().linktag();
    
    var a = document.createElement("a");
    a.href = 'http://twitter.com/' + twip_tweets[0].from_user;
    a.innerHTML = twip_tweets[0].from_user;
    a.target = '_blank';
    
    var b = document.createElement("a");
    b.href = 'http://twitter.com/home?status=@' + twip_tweets[0].from_user + '&in_reply_to_status_id=' + twip_tweets[0].id + '&in_reply_to=' + twip_tweets[0].from_user_id;
    b.innerHTML = "[Reply]";
    b.setAttribute("class", "profile");
    b.style.cssText = "color: #b1b2b5; font-size: 0.9em; padding-left: 5px;";
    b.target = '_blank';
    
    var c = document.createElement("a");
    c.href = 'http://twitter.com/home?status=RT%20@' + twip_tweets[0].from_user + ':%20' + escape( twip_tweets[0].text );
    c.innerHTML = "[Retweet]";
    c.setAttribute("class", "profile");
    c.style.cssText = "color: #b1b2b5; font-size: 0.9em; padding-left: 5px;";
    c.target = '_blank';
    
    var e = document.createElement("a");
    e.href = 'http://www.twitter.com/' + twip_tweets[0].from_user;
    e.innerHTML = "[Profile]";
    e.setAttribute("class", "profile");
    e.style.cssText = "color: #b1b2b5; font-size: 0.9em; padding-left: 5px;";
    e.target = '_blank';
    
    var l = document.createElement("p");
    l.setAttribute("class", "links");
    l.appendChild(a);
    l.appendChild(b);
    l.appendChild(c);
    l.appendChild(e);
    
    
    var d = document.createElement("p");
    d.setAttribute("class", "dates");
    d.style.cssText = "	margin-top: 3px; color: #b1b2b5; font-size: 0.9em;";
    d.innerHTML = twip_tweets[0].created_at;
    
    var g = document.createElement("div");
    
    g.appendChild(l);
    g.appendChild(d);
    
    li.appendChild(img);
    li.appendChild(p);
    li.appendChild(g);
    
    var tweet_list = document.getElementById('twitext_' + this.twipnum);
    
    tweet_list.insertBefore(li, tweet_list.firstChild);
    
    twip_tweets.splice(0, 1);
    
    if(this.tweetcount >= 19) { 
    
	    tweet_list.removeChild(tweet_list.lastChild);
    
    } else {
	    
	this.tweetcount ++;
	
    }
    
  }
	
};

Twip.prototype.change_criteria = function() {

  this.set_geocode();
  
  clearInterval(this.gettimer);
  clearInterval(this.displaytimer);
  
  this.lastid = 0;
  this.tweets = [];
  
  var selfobject = this;
  
  this.gettimer = setInterval(function() { selfobject.get_tweets(); }, 20000);
  this.displaytimer = setInterval(function() { selfobject.display_tweets(); }, 2000);
  
  var tw_value = document.getElementById('criteria_' + this.twipnum).value;
  createCookie("twip_" + this.twipnum, tw_value, 30);
  
};

function pause() {

  clearInterval(twip_1.gettimer);
  clearInterval(twip_1.displaytimer);
  document.getElementById('criteria_1').onchange = "";
  
  clearInterval(twip_2.gettimer);
  clearInterval(twip_2.displaytimer);
  document.getElementById('criteria_2').onchange = "";

  clearInterval(twip_3.gettimer);
  clearInterval(twip_3.displaytimer);
  document.getElementById('criteria_3').onchange = "";
  
  document.getElementById('location').onchange = "";
  
  document.getElementById('twipause').onclick = function() { play(); };
  document.getElementById('twipause').value = "Play";
	
}

function play() {

  twip_1.change_criteria();
  document.getElementById('criteria_1').onchange = function() { twip_1.change_criteria(); };
  	
  twip_2.change_criteria();
  document.getElementById('criteria_2').onchange = function() { twip_2.change_criteria(); };
  	
  twip_3.change_criteria();
  document.getElementById('criteria_3').onchange = function() { twip_3.change_criteria(); };
  
  document.getElementById('location').onchange = function() {
  
    twip_1.change_criteria();
    twip_2.change_criteria();
    twip_3.change_criteria();
    
    createCookie("twip_location", this.value, 30);
    createCookie("twip_units", document.getElementById('units').value, 30);
    createCookie("twip_radius", document.getElementById('radius').value, 30);
  
  };
  
  document.getElementById('twipause').onclick = function() { pause(); };
  document.getElementById('twipause').value = "Pause";
  
}

addLoadEvent(function() {
		
  window['twip_' + 1] = new Twip(1);
  if( readCookie("twip_1") ) { document.getElementById('criteria_1').value = readCookie("twip_1"); }
  
  window['twip_' + 2] = new Twip(2);
  if( readCookie("twip_2") ) { document.getElementById('criteria_2').value = readCookie("twip_2"); }
  
  window['twip_' + 3] = new Twip(3);
  if( readCookie("twip_3") ) { document.getElementById('criteria_3').value = readCookie("twip_3"); }
  
  if( readCookie("twip_location") ) {
  
  	document.getElementById('location').value = readCookie("twip_location");
	document.getElementById('radius').value = readCookie("twip_radius");
	document.getElementById('units').value = readCookie("twip_units");
  
  }
  
  play();
  
});

