// THIS IS ALL COPYRIGHTED YOU SOURCE CODE JUNKIE! //


channel='roelandp';
maxid=0;

var newItemtext;

function setsearch(backchannel) {
		$('#backchannel').val(backchannel);
		$('#submitit').click();
	}

function gettwittertrends() {
	$('#trending').html('');
	url="http://search.twitter.com/trends.json?q=&rpp=10&callback=?&since_id=";
  	$.getJSON(url, function(jsonni) {
			//alert(jsonni);
			$.each(jsonni.trends, function(i,item){
        			showtrend(item);
        	});
	});
			
			
}

function aDelete() {
		
     $(this).fadeOut('slow');
   		
}


  function gettwitterdata() {
  
              
              $("#twitworking").css({'opacity': 0.6 }).fadeIn('fast');
              
              


  	url="http://search.twitter.com/search.json?q="+encodeURIComponent(channel)+"&rpp=10&callback=?&since_id="+maxid;
  	$.getJSON(url,
        function(json){
        	maxid=json.max_id;
   				json.results.reverse(); //Since we prepend, the last one becomes first. Reverse here.
        		$.each(json.results, function(i,item){
        	
        		item.timestamp=(Date.parse(item.created_at)/1000);
        		showitem(item);
				$("#twitworking").fadeOut('fast');
				
				
        	});
        	

				
	setTimeout(getdata,10 * 1000);
		//$("#tweets").jScrollPane();
			$("#twitworking").fadeOut('fast');	});
   
   
  }   
  
  
function urlencode(str) {
return escape(str).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\#/g, '%23').replace(/\//g, '%2F').replace(/@/g, '%40');
}

function urldecode (str) {
    // Decodes URL-encoded string  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/urldecode
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer
    // +      input by: Ratheous
    // +   improved by: Orlando
    // %        note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin van Zonneveld!'
    // *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
    
    var hash_map = {}, ret = str.toString(), unicodeStr='', hexEscStr='';
    
    var replacer = function (search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The hash_map is identical to the one in urlencode.
    hash_map["'"]   = '%27';
    hash_map['(']   = '%28';
    hash_map[')']   = '%29';
    hash_map['*']   = '%2A';
    hash_map['~']   = '%7E';
    hash_map['!']   = '%21';
    hash_map['%20'] = '+';
    hash_map['\u00DC'] = '%DC';
    hash_map['\u00FC'] = '%FC';
    hash_map['\u00C4'] = '%D4';
    hash_map['\u00E4'] = '%E4';
    hash_map['\u00D6'] = '%D6';
    hash_map['\u00F6'] = '%F6';
    hash_map['\u00DF'] = '%DF';
    hash_map['\u20AC'] = '%80';
    hash_map['\u0081'] = '%81';
    hash_map['\u201A'] = '%82';
    hash_map['\u0192'] = '%83';
    hash_map['\u201E'] = '%84';
    hash_map['\u2026'] = '%85';
    hash_map['\u2020'] = '%86';
    hash_map['\u2021'] = '%87';
    hash_map['\u02C6'] = '%88';
    hash_map['\u2030'] = '%89';
    hash_map['\u0160'] = '%8A';
    hash_map['\u2039'] = '%8B';
    hash_map['\u0152'] = '%8C';
    hash_map['\u008D'] = '%8D';
    hash_map['\u017D'] = '%8E';
    hash_map['\u008F'] = '%8F';
    hash_map['\u0090'] = '%90';
    hash_map['\u2018'] = '%91';
    hash_map['\u2019'] = '%92';
    hash_map['\u201C'] = '%93';
    hash_map['\u201D'] = '%94';
    hash_map['\u2022'] = '%95';
    hash_map['\u2013'] = '%96';
    hash_map['\u2014'] = '%97';
    hash_map['\u02DC'] = '%98';
    hash_map['\u2122'] = '%99';
    hash_map['\u0161'] = '%9A';
    hash_map['\u203A'] = '%9B';
    hash_map['\u0153'] = '%9C';
    hash_map['\u009D'] = '%9D';
    hash_map['\u017E'] = '%9E';
    hash_map['\u0178'] = '%9F';
    hash_map['\u00C6'] = '%C3%86';
    hash_map['\u00D8'] = '%C3%98';
    hash_map['\u00C5'] = '%C3%85';

    for (unicodeStr in hash_map) {
        hexEscStr = hash_map[unicodeStr]; // Switch order when decoding
        ret = replacer(hexEscStr, unicodeStr, ret); // Custom replace. No regexing
    }
    
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = decodeURIComponent(ret);

    return ret;
}



function showitem (item) {
            var html="<div class='res' id='item_"+item.id+"' timestamp='"+item.timestamp+"' ><table cellspacing='0' cellpadding='0'><tr><td valign='top'><div class='imageholder'><a href='http://twitter.com/"+item.from_user+"' target='_blank' title='View "+item.from_user+" on Twitter'><img src='"+item.profile_image_url+"' border='0'/></a></div></td><td><div class='itemtext'><div class='twitusername'><a href='http://twitter.com/"+item.from_user+"' target='_blank' title='View "+item.from_user+" on Twitter'>"+item.from_user+"</a></div>";
            html+=replaceURLWithHTMLLinks(item.text)+" <span class='twitsource'>at "+showLocalDate(item.timestamp)+"</span></div></td></tr></table></div>";
              $('#tweets').prepend(html);
              if(newItemtext!=undefined) {
				$('.itemtext').css('font-size', newItemtext);
				$('.twitusername').css('font-size', newTwitusername);
				console.log(newItemtext);
              }
              $('#tweets #item_'+item.id).hide();
              $('#tweets #item_'+item.id).css({'background-color':'#00FFFF'});
             $('#tweets #item_'+item.id).show(500, function(){
  				         $(this).css('background', 'transparent');
						$(this).unbind('click', aDelete).bind('click',aDelete);
               });
              
              
			
}





function callback2() {
	//console.log(this);
}

function callback() {
		

}

function showtrend (item) {
            var html='<div onclick="setsearch(\''+item.name+'\');" class="trend">'+item.name+'</div>';
              $('#trending').append(html);			
}

function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp,"<a href='$1' target='_blank' title='open $1'>$1</a>"); 
}

	function showLocalDate(timestamp)
	{
	  var dt = new Date(timestamp * 1000);
	  
	  
	   hr=dt.getHours();
	  mi=dt.getMinutes();
	  se=dt.getSeconds();
	  if(se<=9) se="0"+se;
	  if(mi<=9) mi="0"+mi;
	  if(hr<=9) hr="0"+hr;
	  var timep=hr+":"+mi+"<span style='font-size: 12px;'>."+se+"</span>";
	  
	  return timep;
	}




function getdata() {
	gettwitterdata();
}

function submitFormWithEnter(myfield,e)
{
   var keycode;
   if (window.event)
   {
      keycode = window.event.keyCode;
   }
   else if (e)
   {
      keycode = e.which;
   }
   else
   {
      return true;
   }

   if (keycode == 13)
   {
      $('#submitit').click();
      return false;
   }
   else
   {
      return true;
   }
}



$(document).ready(function(){
	
	once();
	
});

once = function() {

	$('#submitit').click(function(){
		if($('#backchannel').val() == '') {
			alert('gots to enter a term before launching a backchannel eeej!');	
		} else {
			$('body').css({'background': 'url(\'imgs/backchannelbglight.gif\') left bottom repeat-x #FFFFFF'});
			$('#start').hide();
			$('#tweetholder').show();
			channel = $('#backchannel').val();
			encodedchannel = urlencode(channel);
			window.location.hash = "#/"+encodedchannel;
			$('#tweetthis').html('<a href="http://twitter.com/?status=watching the topic \''+encodedchannel+'\' live via http://backchannel.us/%23/'+encodedchannel+'" target="_blank" title="retweet this channel to your followers!" id="tweetthis" onclick="javascript:pageTracker._trackPageview(\'retweet_channel\');">Retweet this BackChannel!</a>');
			 pageTracker._trackPageview('/launch_backchannel');
			   	var originalItemtext = $('.itemtext').css('font-size');
				var originalTwitusername = $('.twitusername').css('font-size');
			getdata();
			
		}
	});
	
	
	$('#activatetrends').click(function() {
		gettwittertrends();
	});
	
	  // Reset Font Size
    $("#resetFont").click(function(){
	$('.itemtext').css('font-size', originalItemtext);
	$('.twitusername').css('font-size', originalTwitusername);
  });
  // Increase Font Size
  $("#increaseFont").click(function(){
	newItemtext = parseFloat($('.itemtext').css('font-size'), 10) * 1.2;
	newTwitusername = parseFloat($('.twitusername').css('font-size'), 10) * 1.2
	$('.itemtext').css('font-size', newItemtext);
	$('.twitusername').css('font-size', newTwitusername);

    return false;
  });
  // Decrease Font Size
  $("#decreaseFont").click(function(){
	newItemtext = parseFloat($('.itemtext').css('font-size'), 10) * 0.8;
	newTwitusername = parseFloat($('.twitusername').css('font-size'), 10) * 0.8;
	$('.itemtext').css('font-size', newItemtext);
	$('.twitusername').css('font-size', newTwitusername);

    return false;
  });
  
  var urlReq = document.location.toString();
if (urlReq.match('#')) { // the URL contains an anchor
  // click the navigation item corresponding to the anchor
  var myBc = urldecode(urlReq.split('#')[1].substr(1));
$('#backchannel').val(myBc);
} else {

}

}
