/*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();
    };
  }
  
}

String.prototype.linkify = function() {
	
  return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&;\?\/.=]+/g,function(m){
    var a = document.createElement("a");
    	return "<a href='" + m +"' target='_blank'>" + m + "</a>";
  });
  	
};

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

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, twhere, howmany, showpic, uselocation, gets, ads) {

  this.twipnum = num;
  this.lastid = 0;
  this.gettimer = '';
  this.displaytimer = '';
  this.tweetcount = 0;
  this.geo = "-78.877875,42.886875,0";
  this.tweets = [];
  this.units = '';
  this.radius = '';
  this.location = '';
  this.firsttime = '';
  this.twhere = twhere;
  this.howmany = howmany;
  this.showpic = showpic;
  this.twipsearch = '';
  this.uselocation = uselocation;
  this.gets = gets;
  this.ads = ads;
  
}

Twip.prototype.get_tweets = function() {
	
  var twipnum = this.twipnum;
  var selfobject = this;
  
  var search_criteria = this.twipsearch;
  search_criteria = search_criteria.split(',');
  
  var searching = '';
  
  for( var i = search_criteria.length; i--; ) {

    searching += search_criteria[i] + " OR ";
	  
  }
  
  searching = searching.substring(0, searching.length - 4);
  
  var units = document.getElementById('units').value;
  var radius = document.getElementById('radius').value;
    
  var getgeo = this.geo;
  
  var sp = getgeo.split(",");
  
  var geocode = sp[1] + "%2C" + sp[0] + "%2C" + radius + units;
  
  var url = "http://search.twitter.com/search.json?rpp=" + this.howmany;
  
  if(this.lastid > 0) {
  
    url = url + "&since_id=" + this.lastid;
  
  }
  
  if(this.uselocation === true ) {

    url = url + "&geocode=" + geocode;
	  
  }
  
  url = url + "&q=" + query_string( searching ) + "&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] );
	    
	  }
	  
	  if(selfobject.firsttime === true) {
		  
	    selfobject.firsttime = false;
	    selfobject.display_tweets();
	    
	  } else {
		  
	  document.getElementById("moreresults_" + selfobject.twipnum).innerHTML = selfobject.tweets.length + " new results. <a href='#' onclick='twip_" + selfobject.twipnum + ".refresh(); return false;'>Refresh</a> to see them.";
		  
	  }
	
	}
	
  });
	
  return false;	
	
};

Twip.prototype.get_tweeple = function() {

  var twipnum = this.twipnum;
  var selfobject = this;

  var url = "inc/tweeple.php?rpp=" + this.howmany;
  
  if(this.lastid > 0) {
  
    url = url + "&since_id=" + this.lastid;
  
  }
  
  jQuery.getJSON(url, 
    function(data) {
	    
	var results = data;
	
	if ( results[0] ) {
		
	  selfobject.lastid = results[0].id;
	  results.reverse();

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

Twip.prototype.get_dms = function() {

  var twipnum = this.twipnum;
  var selfobject = this;

  var url = "inc/dms.php?rpp=" + this.howmany;
  
  if(this.lastid > 0) {
  
    url = url + "&since_id=" + this.lastid;
  
  }
  
  jQuery.getJSON(url, 
    function(data) {
	    
	var results = data;
	
	if ( results[0] ) {
		
	  selfobject.lastid = results[0].id;
	  results.reverse();

	  for ( var i = 0; i < results.length; i++ ) {
		
	    selfobject.tweets.push( results[i] );
	    
	  }
	  
	   if(selfobject.firsttime === true) {
		  
	    selfobject.firsttime = false;
	    selfobject.display_tweets();
	    
	  } else {
		  
	  document.getElementById("moreresults_" + selfobject.twipnum).innerHTML = selfobject.tweets.length + " new results. <a href='#' onclick='twip_" + selfobject.twipnum + ".refresh(); return false;'>Refresh</a> to see them.";
		  
	  }
	
	}
	
  });
	
  return false;	
	
}

Twip.prototype.display_tweets = function() {
	
  if( this.tweets[0] ) {
	
    var fragment = document.createDocumentFragment();
    var speed = this.tweets;
    var locads = ads;
    var ifads = this.ads;
    
    for( var i = speed.length; i--; ) {
	    
      if(ifads === true) {
	      
	      if(locads[0]) {
		
	if(i % 5 == 0) {
	
	  var ran = Math.floor( Math.random() * locads.length)
		
	  var ad = document.createElement("li");
	  
	  var p2 = document.createElement("p");
          p2.innerHTML = locads[ran].ad_body;
    
	  ad.appendChild(p2);
	  
	  var a2 = document.createElement("a");
	  a2.href = locads[ran].url;
	  a2.innerHTML = locads[ran].title;
	  a2.target = '_blank';
	  
	  var p3 = document.createElement("p");
	  p3.style.cssText = "margin-top: 6px;";
	  p3.appendChild(a2);
	  
	  ad.appendChild(p3);
	  
	  fragment.appendChild(ad);
			    
        }
		    
	      }    
      
      }
	    
    var twip_tweets = speed[i];
	 
    if(this.gets == "get_tweeple") { 

      var from_user = twip_tweets.user.screen_name;
      var from_user_id = twip_tweets.user.id

    } else if(this.gets == "get_dms") { 

      var from_user = twip_tweets.sender.screen_name;
      var from_user_id = twip_tweets.sender.id

    } else { 

      var from_user = twip_tweets.from_user;
      var from_user_id = twip_tweets.from_user_id;

    }
    
    var li = document.createElement("li");
    
    var img = document.createElement("img");
    img.src = twip_tweets.profile_image_url;
    img.width = '48';
    
    var p = document.createElement("p");
    p.innerHTML = twip_tweets.text.linkify().linkuser().linktag();
    
    var a = document.createElement("a");
    a.href = 'http://twitter.com/' + from_user;
    a.innerHTML = from_user;
    a.target = '_blank';
    
    var b = document.createElement("a");
    b.href = 'http://twitter.com/home?status=@' + from_user + '&in_reply_to_status_id=' + twip_tweets.id + '&in_reply_to=' + from_user_id;
    b.innerHTML = "[Reply]";
    
    if( document.getElementById('status') ) { 
    
	    function stuff2(from_user) { 
	      return function () { 
	        document.getElementById('status').value = "@" + from_user + " ";
	        return false; };
	    };
	    b.onclick = stuff2(from_user);
    
    };
    
    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@' + from_user + ':%20' + escape( twip_tweets.text );
    c.innerHTML = "[Retweet]";
    
    if( document.getElementById('status') ) { 
    
	    function stuff(item, from_user) { return function () { document.getElementById('status').value = "RT @" + from_user + ': ' + item.text; return false; }; };
	    c.onclick = stuff(twip_tweets, from_user);
    
    };
    
    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/' + 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);
    
    if(this.gets !== "get_dms") {
    
    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;";
    
    var thetime=new Date(Date.parse(twip_tweets.created_at));
    var tHour=thetime.getHours();
    if(tHour>12){
	tHour=tHour-12;
	tUnit='PM';
    } else{
	if(tHour==0){
		tHour=12;
	}
		tUnit='AM';
    };
    var tMin=thetime.getMinutes();
    if(tMin<10){
		tMin='0'+tMin;
    };
    
    var tMonth = thetime.getMonth();
    var tFullMonth;
    
    switch (tMonth) {
    	case 11:
		tFullMonth = "December";
		break;
	case 10:
		tFullMonth = "November";
		break;
	case 9:
		tFullMonth = "October";
		break;
    	case 8:
		tFullMonth = "September";
		break;
	case 7:
		tFullMonth = "August";
		break;
	case 6:
		tFullMonth = "July";
		break;
    	case 5:
		tFullMonth = "June";
		break;
	case 4:
		tFullMonth = "May";
		break;
	case 3:
		tFullMonth = "April";
		break;
    	case 2:
		tFullMonth = "March";
		break;
	case 1:
		tFullMonth = "February";
		break;
	case 0:
		tFullMonth = "January";
		break;
	default:
		tFullMonth = "January";
    }
    
    
    var thetimestr = tHour + ':' + tMin + ' ' + tUnit + ' ' + tFullMonth + ' ' + thetime.getDate() + ' ' + thetime.getFullYear();
    
    d.innerHTML = thetimestr;
    
    var g = document.createElement("div");
    
    g.appendChild(l);
    g.appendChild(d);
    
    if(this.showpic === true) { li.appendChild(img); }
   
    li.appendChild(p);
    li.appendChild(g);
    
    fragment.appendChild(li);
    
    }
    
    var tweet_list = document.getElementById(this.twhere);
    tweet_list.insertBefore(fragment, tweet_list.firstChild);
    
    this.tweets = [];
    
  }
	
};

Twip.prototype.change_criteria = function(criteria) {
  
  this.twipsearch = criteria;
  
  clearInterval(this.gettimer);
	
  this.lastid = 0;
  this.tweets = [];
  this.firsttime = true;
  
  document.getElementById(this.twhere).innerHTML = "";
  if(!this.gets) { document.getElementById("moreresults_" + this.twipnum).innerHTML = "&nbsp;"; }
  
  var selfobject = this;
  
  switch (this.gets) {
    case "get_tweeple":
	selfobject.get_tweeple();
	this.gettimer = setInterval(function() { selfobject.get_tweeple(); }, 30000);
	break;
    case "get_dms":
	selfobject.get_dms();
	this.gettimer = setInterval(function() { selfobject.get_dms(); }, 30000);
	break;
    default:
	selfobject.get_tweets();
	this.gettimer = setInterval(function() { selfobject.get_tweets(); }, 30000);
  }
  
};

Twip.prototype.refresh = function() {
  
  this.display_tweets();
  document.getElementById("moreresults_" + this.twipnum).innerHTML = "&nbsp;";
  
};

function tabs(title, criteria) {
	
  twip_1.change_criteria(criteria);
  document.getElementById("moreresults_1").innerHTML = title;
	
}

addLoadEvent(function() {
		
  window['twip_' + 1] = new Twip(1, 'twitext_1', 25, true, true, '', true);
  twip_1.change_criteria('');
  document.getElementById('criteria_1').onchange = function() { twip_1.change_criteria( document.getElementById('criteria_1').value ); };
  document.getElementById('units').onchange = function() { twip_1.change_criteria( document.getElementById('criteria_1').value ); };
  document.getElementById('radius').onchange = function() { twip_1.change_criteria( document.getElementById('criteria_1').value ); };
  
  if( document.getElementById('status') ) {
  
    window['twip_' + 2] = new Twip(2, 'tweetsatme', 10, false, false, '', false);
    twip_2.change_criteria('@' + screen_name);
  
    window['twip_' + 3] = new Twip(3, 'tweeple', 20, false, false, 'get_tweeple', false);
    twip_3.change_criteria('');
    
    window['twip_' + 4] = new Twip(4, 'dmstome', 10, false, false, 'get_dms', false);
    twip_4.change_criteria('');
  
  }
  
});
