/**
 *
 * Diogo Barioni Abdalla
 * Em: http://www.alfaiataria.net/
 *
 */

// SETUP

$(document).ready(function(){

	$('#twitradarArea').data('hashtagPrefix', '#TwitRadar');
	$('#twitradarArea').data('tweetURL', 'http://twitter.com/home?status=');
	$('#twitradarArea').data('limit', 10);
	$('#twitradarArea').data('url', 'http://bit.ly/3VNAaZ');

	$('.teamRadioLi').click(selectTeam);

	$('#tweetMessage').keydown(onTweetWrite);
	$('#tweetMessage').blur(onTweetWrite);

	$('#btnSend').click(sendTweet);
});

var setHTMLInterface = function(json)
{
	var teams = json['current'];
	var $lis = $('#tweetInt').children('li');

	var actteams = 0;

	for(var t = 0; t < 4; t++)
	{
		var defs = json['teams'][teams[t]];

		if(defs != undefined)
		{
			$($lis[t]).attr('htag', defs['hashtag']);
			$($lis[t]).children('label').html(defs['label']);
			$($lis[t]).children('img').attr('src', defs['thumb']);

			actteams++;
		}//if defs
		else
		{
			$($lis[t]).hide();
		}
	}//for t

	if(actteams < 4)
	{
		$('#twitradarArea').data('url', 'http://bit.ly/8SRTmq');
		$('.selectTime').css('background', '');
	}

	$('.htmlInt').slideDown(1000);
}//setHTMLInterface

// FUNCTIONS

var selectTeam = function()
{
	$(this).children('input').attr('checked', 'checked');

	$('#curTeam').html($(this).children('label').html());
	$('#curTeamTag').html($('#twitradarArea').data('hashtagPrefix') + $(this).attr('htag'));

	$('#tweetMessage').removeAttr('disabled');

	onTweetWrite();
}//selectTeam

var onTweetWrite = function()
{
	var text =  $('#tweetMessage').val() + ' ' + $('#curTeamTag').html() + ' ' + $('#twitradarArea').data('url');

	var tlen = text.length;
	var left = 144 - tlen;

	if(left < 0)$('#tweetChars').addClass('busted');
		else $('#tweetChars').removeClass('busted');

	$('#twitradarArea').data('charsLeft', left);

	$('#btnSend').attr('href', $('#twitradarArea').data('tweetURL') + Url.encode(text));

	$('#tweetChars').html(left);
}//onTweetWrite

var sendTweet = function()
{
	if($(this).attr('href') == '#')return false;
}//sendTweet

// FLASH FUNCTIONS

var getFlash = function(movieName)
{
    if(navigator.appName.indexOf("Microsoft") != -1)
    {
        return window[movieName];
    }//if IE
    else
    {
    	if(document[movieName][1] == undefined)return document[movieName];
    		else return document[movieName][1];
    }//else others
}//getFlash

var searchTwitter = function(query, mon_id, inst_id, since_id, callback)
{
	var params = {cache:false, rpp:50};
	if(since_id != 0)params['since_id'] = since_id;

	//$.twitter.search(query, searchTwitterReceive, params);
	var searches = query.split('||');

	$(document).data('monID', mon_id);
	$(document).data('query', query);
	$(document).data('tparams', params);
	$(document).data('tseaches', searches);
	$(document).data('tresults', []);

	$(document).data('tsearchCbk', callback);

	queueSearch();
}//searchTwitter

var queueSearch = function()
{
	var searches = $(document).data('tseaches');

	var query = searches.shift();
	var params = $(document).data('tparams');

	$.twitter.search(query, queueSearchReceive, params);
}//queueSearch

var queueSearchReceive = function(data, status)
{
	if(data['results'] != undefined)
	{
		var results = data['results'];
		results = results.concat($(document).data('tresults'));
		$(document).data('tresults', results);
	}//if results

	var searches = $(document).data('tseaches');
	if(searches.length > 0)queueSearch();
	else
	{
		if(results != undefined)
		{
			results.sort(sortByID);
			searchTwitterReceive({results:results});
			//saveToCache(results);
		}//if results
	}//else
}//queueSearchReceive

var searchTwitterReceive = function(data, status)
{
	var method = $(document).data('tsearchCbk');
	var flash = getFlash('twitradar');

	if(data['results'] != undefined)
	{
		if(data['results'][0] != undefined)
		{
			try
			{
				flash[method](data);
			}//try
			catch(e)
			{
				alert(method + ' NOT FOUND IN ' + flash);
			}//catch error

			$('#tweetUL').data('lastResults', data['results']);

			setInterval(updateTweetList, 3000);
		}//if results
	}//if results
}//searchTwitterReceive

var sortByID = function(a, b)
{
	var ida = Number(a['id']);
	var idb = Number(b['id']);

	return (ida > idb)?(-1):(1)
}//sortByID

var updateTweetList = function()
{
	if($('#tweetUL').length == 0)return;

	//alert('UPDATE, PLEASE');

	var results = $('#tweetUL').data('lastResults');
	if(results == null)return;

	var total = (results.length < $('#twitradarArea').data('limit'))?(results.length):($('#twitradarArea').data('limit'));

	var tpl = $('#tweetUL').data('tweetHTML');
	if(tpl == undefined)
	{
		tpl = $('#tweetTemplate').html();
		$('#tweetTemplate').remove();
		$('#tweetUL').data('tweetHTML', tpl);
	}//if !tpl

	//alert('UPDATING ' + total);

	for(var t = total - 1; t >= 0; t--)
	{
		var tweet = results[t];

		// Feio, mas r�pido

		var lihtml = tpl;

		lihtml = lihtml.replace('#SRC#', tweet['profile_image_url']);
		lihtml = lihtml.replace('#USER_HREF#', 'http://twitter.com/' + tweet['from_user']);
		lihtml = lihtml.replace('#USER#', '@' + tweet['from_user']);
		lihtml = lihtml.replace('#TEXT#', tweet['text']);
		lihtml = lihtml.replace('#TIME#', relative_time(tweet['created_at']));

		lihtml = lihtml.replace('#STATUS_HREF#', 'http://twitter.com/' + tweet['from_user'] + '/status/' + tweet['id']);

		$('#tweetUL').prepend('<li class="newTweet" style="display:none">' + lihtml + '</li>');
	}//for t

	$('#tweetUL').data('lastResults', null);
	$('.newTweet').fadeIn(2000, onTweetsIn);

	var limit = Number($('#twitradarArea').data('limit'))
	var li = $('#tweetUL').children('li');
	var tt = li.length;

	for(var t = tt - 1; t > limit; t--)$(li[t]).remove();
}//updateTweetList

var onTweetsIn = function()
{
	$(this).removeClass('newTweet');
}//onTweetSlide

var saveToCache = function(results)
{
	var params = {};

	var mon_id = $(document).data('monID');

	params['monID'] = mon_id;
	params['query'] = $(document).data('query');
	params['results'] = serialize(results);

	var url = 'http://twitradar.com/monitor/savecache';

	try
	{
		$.ajax({url:url, data:params, type:'POST', dataType:'json'});
	}//try sending
	catch(e)
	{
		alert(e)
	}//catch e
}//saveToCache

/**
	ALIENS!
*/

/*
	Por: Gissur Simonarson
	Em: http://www.gissisim.com/2009/03/live-jquery-twitter-feed/
*/

function relative_time(time_value)
{
    var values = time_value.split(" ");
    time_value = values[2] + " " + values[1] + ", " + values[3] + " " + values[4];
    var parsed_date = Date.parse(time_value);
    var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
    var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
    delta = delta + (relative_to.getTimezoneOffset() * 60);

    var r = '';
    if (delta < 60) {
      r = 'a minute ago';
    } else if(delta < 120) {
      r = 'couple of minutes ago';
    } else if(delta < (45*60)) {
      r = (parseInt(delta / 60)).toString() + ' minutes ago';
    } else if(delta < (90*60)) {
      r = 'an hour ago';
    } else if(delta < (24*60*60)) {
      r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
    } else if(delta < (48*60*60)) {
      r = '1 day ago';
    } else {
      r = (parseInt(delta / 86400)).toString() + ' days ago';
    }

    return r;
}//relative_time

/**
*
*  URL encode / decode
*  Em: http://www.webtoolkit.info/
*
**/

var Url = {

	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},

	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}

// Returns a string representation of variable (which can later be unserialized)
//
// version: 910.813
// discuss at: http://phpjs.org/functions/serialize

function serialize(mixed_value)
{
    var _getType = function (inp) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            match = cons.match(/(\w+)\(/);
            if (match) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';

    switch (type) {
        case "function":
            val = "";
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            //val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            //break;
        case "string":
            //mixed_value = this.utf8_encode(mixed_value);
            val = "s:" + encodeURIComponent(mixed_value).replace(/%../g, 'x').length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            /*
            if (type == "object") {
                var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = this.serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            */
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") {
                    continue;
                }

                okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
                vals += this.serialize(okey) +
                        this.serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
        case "undefined": // Fall-through
        default: // if the JS object has a property which contains a null value, the string cannot be unserialized by PHP
            val = "N";
            break;
    }
    if (type != "object" && type != "array") {
        val += ";";
    }
    return val;
}//serialize

// Encodes an ISO-8859-1 string to UTF-8
//
// version: 909.322
// discuss at: http://phpjs.org/functions/utf8_encode

function utf8_encode(argString)
{
    var string = (argString+''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");

    var utftext = "";
    var start, end;
    var stringl = 0;

    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;

        if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }

    if (end > start) {
        utftext += string.substring(start, string.length);
    }

    return utftext;
}//utf8_encode

