var BOSH_SERVICE = '/http-bind';
var connection = null;

function log(msg) 
{
//alert(msg);
//	console.log(msg);
	/*
		Div = document.createElement('div');
		Div.update('<div></div>' + document.createTextNode(msg)
    Element.insert($('log').insert('<div></div>').insert(document.createTextNode(msg));
		*/

   // $('#log').append('<div></div>').append(document.createTextNode(msg));
}

function onConnect(status)
{
		//log(connection.jid);
    if (status == Strophe.Status.CONNECTING) {
			//log('Most Recent is connecting.');
			if($('comet-message')) $('comet-message').show();
    } else if (status == Strophe.Status.CONNFAIL) {
			//log('Most Recent failed to connect.');
    } else if (status == Strophe.Status.DISCONNECTING) {
			//log('Most Recent is disconnecting.');
    } else if (status == Strophe.Status.DISCONNECTED) {
			//log('Most Recent is disconnected.');
    } else if (status == Strophe.Status.CONNECTED) {
			//log('Most Recent is connected.');
			if ($('comet-message')) $('comet-message').hide();

			//console.log('BOT: Send a message to ' + connection.jid + ' to talk to me.');

			connection.addHandler(onMessage, null, 'message', null, null,  null); 
			connection.send($pres().tree());

			if ($('comet'))
			{
				update({memo: {replace: true }});
			}
    }
}

function onMessage(msg) {
    var to = msg.getAttribute('to');
    var from = msg.getAttribute('from');
    var type = msg.getAttribute('type');
    var elems = msg.getElementsByTagName('body');

		//console.log('chat', to, from, type, msg.innerHTML);

    if (type == "chat" && elems.length > 0) 
		{
			var body = elems[0];

			var text = Strophe.getText(body);
			//console.log('BOT: I got a message from ' + from + ': ' + text);

			if (text)
			{
				eval('var obj=' + text);

				//console.log(obj.length, buffer.length);

				if (init == null && ! obj.length)
				{
					init = 1;
					process(obj);

				} else
				if (! obj.length)
				{	
					//process(obj);
					buffer.push(obj);
				} else 
				{	
					buffer = obj; 

					process(obj[0], true);
				}

				/*
				{	
					fisherYates(obj); 
				
					buffer = obj; 
					
					//process(obj[0], true);
				}
				*/

				/* else switch (obj.length)
				{
					case 9: 
					case 10: $('comet').innerHTML = '';
									for (var i=obj.length-1; i>-1; i--)
											process(obj[i]);
									//stack = true; 
									break;

					default: fisherYates(obj); buffer = obj; process(obj[0], true); break;
			
				} */

			}


				
			//var reply = $msg({to: from, from: to, type: 'chat'})
			//          .cnode(Strophe.copyElement(body));
			//connection.send(reply.tree());

			//log('ECHOBOT: I sent ' + from + ': ' + Strophe.getText(body));
    }

    // we must return true to keep the handler alive.  
    // returning false would remove it after it finishes.
    return true;
}


//$(document).ready(function () {


function trim(stringToTrim) {
		return stringToTrim.replace(/^\s+|\s+$/g,"");
}

var init = null;
var stack = true;
var buffer = [];
var last_id = null;
var recent_timer = null;
var recent_cancel = true;


var botboot = function () {

		if (connection == null)
		{
    	connection = new Strophe.Connection(BOSH_SERVICE);

    // Uncomment the following lines to spy on the wire traffic.
    //connection.rawInput = function (data) { console.log('RECV: ' + data); };
    //connection.rawOutput = function (data) { console.log('SEND: ' + data); };

    // Uncomment the following line to see all the debug output.
    //Strophe.log = function (level, msg) { log('LOG: ' + msg); };

	  	connection.connect('user@redgage.com', 'redgage', onConnect);
		}

if (! recent_timer)
	recent_timer = new PeriodicalExecuter(function(pe) 
	{
		if(! $('comet') || ! connection) return;

		//console.log('recent cancel = ', recent_cancel, buffer.length);
		
		if (buffer.length < 2) {
			//console.log('buffer length low, replenishing...');

			reply = $msg({from: connection.jid, to: 'user@recent.redgage.com', type: 'chat'})
								.c('body').t('six');

			connection.send(reply.tree());
		} else
		if (! recent_cancel)
		{
			fisherYates(buffer);
			process(buffer.pop(), true);
		}

		if (recent_cancel)
			recent_cancel = false;

	}, 8);

		 /*
    $('#connect').bind('click', function () {
	var button = $('#connect').get(0);
	if (button.value == 'connect') {
	    button.value = 'disconnect';

	    connection.connect($('#jid').get(0).value,
			       $('#pass').get(0).value,
			       onConnect);
	} else {
	    button.value = 'connect';
	    connection.disconnect();
	}
    });
	*/

};

document.observe('dom:loaded', botboot);


var batch = function (username, service)
{

	if (connection && connection.connected)
	{
			reply = $msg({from: connection.jid, to: 'import@' + service + '.redgage.com', type: 'chat'})
								.c('body').t(username);

			connection.send(reply.tree());

	} else
	{
		setTimeout(function() { batch(username, service); }, 3000);
	}
}


var update = function(event)
{
	if (! $('comet')) return;

	if (! connection)
		botboot();

	if (event.memo.replace)
	{
		var to = connection.jid.replace(/localhost/, 'localhost');
		var from = connection.jid;
		var reply = $msg({from: to, to: 'user@recent.redgage.com', type: 'chat'})
		          .c('body').t('one');

		connection.send(reply.tree());

	}
};

document.observe('rapid:update', update);




function fisherYates ( myArray ) {
  var i = myArray.length;
  if ( i == 0 ) return false;
  while ( --i ) {
     var j = Math.floor( Math.random() * ( i + 1 ) );
     var tempi = myArray[i];
     var tempj = myArray[j];
     myArray[i] = tempj;
     myArray[j] = tempi;
   }
}

function process (Data, Stale)
{
	if (! Data || ! $('comet')) return;

	if (! recent_cancel)
	{
		recent_cancel = true;
		//setTimeout(function () { recent_cancel = false; }, 1000);
	}

	if (last_id == null
	||  last_id != Data.content_id)
		last_id = Data.content_id;
	else
		return;

	if (Data.skip_recent == "1")
	{
		//console.log("Skipping: " + Data.title);
		return;
	}

	var e = document.getElementById('comet');
	//e.innerHTML = '<p><h3>' + Data.title + '</h3>' + Data.content + '</p>' + e.innerHTML;

	if (Data.username)
	{

		var types = [0, 'photos', 'videos', 'blogs', 'documents', 'links'];
		var type = types[Data.content_type_id];
		var l_username  = Data.username.toLowerCase();
		var type_icon = '<img src="http://static.redgage.com/images/icon_' +type+ '.png" class="type_icon" />';
		var url_title = (Data.url) ? Data.url + '.html' : trim(Data.title).toLowerCase().replace(/-/g, '=').replace(/ /g, '-');
		var thumbnail = Data.thumbnail;

		//console.log(url_title);

		if (thumbnail)
		{
			if (type != 'links' && type != 'blogs' && type != 'videos')
			{
				if (type == 'documents') type = 'papers';

				thumbnail = '<img src="http://redgage-' +type+ '.s3.amazonaws.com/' +l_username+ '/thumbnails/'
									+ thumbnail + '" class="search_icon" />';

				if (type == 'papers') type = 'documents';

			} else
			{
				if (thumbnail.indexOf('bg_img_thumb.jpg') > -1)
				{
					thumbnail = '<span class="thumbnailer search_icon search_thumb_text search_thumb" style="height: 87px"><div class="smallbr">&nbsp;</div>' +Data.content.stripTags().substring(0, 500)+ '</span>'; 

				} else
				{

					if (type == 'videos')
						ext = '.jpg';
					else
						ext = thumbnail.substr(thumbnail.length-4);

					thumbnail = '<img class="search_icon" src="http://redgage-' +type+ '.s3.amazonaws.com/' 
										+ l_username +'/'+ MD5.hexdigest(thumbnail) + ext + '" />';

				}

			}

		} else
		{
					thumbnail = '<span class="thumbnailer search_icon search_thumb_text search_thumb" style="height: 87px"><div class="smallbr">&nbsp;</div>' +Data.content.stripTags().substring(0, 500)+ '</span>'; 
		}

		if (thumbnail.startsWith('<span')) type_icon = type_icon.replace('type_icon', 'type_icon type_icon_text');

		var template = new Template(''
		+	'<div class="section bottom">'
		+ '	<a href="/#{type}/#{l_username}/#{url_title}.html" class="trigger-pager.pageForwarder maroon search_icon search_thumb">'
		+ '		#{thumbnail}'
		+ '		#{type_icon}'
		+ '	</a>'
		+ '	<div class="results_details">'
		+ '		<p class="content-title" style="display:inline;"><a href="/#{type}/#{l_username}/#{url_title}.html" class="trigger-pager.pageForwarder maroon">#{title}</a></p>'
		+ '		<p class="dark_gray content-description">#{description}</p>'
		+ '		<div class="byline"> By: <a href="/#{username}" class="light-maroon trigger-pager.forward username">#{username}</a> </span></div>'
		//+ '		<div class="byline"> By: <a href="/#{username}" class="light-maroon trigger-pager.forward username">#{username}</a> | Views: <span class="dark_gray">#{titan_views}</span> | Earned: <span class="dark_gray">$#{money_earned}</span></div>'
		+ '	</div>'
		+ '	<div class="clear"></div>'
		+ '</div>');
		//<div class="section_tile"></div>');

		var show = {type: type, l_username: l_username, type_icon: type_icon, url_title: url_title,
								//titan_views: Data.view_count, money_earned: Data.money_earned, 
								thumbnail: thumbnail,
								username: Data.username, title: Data.title, description: Data.description};

		//e.innerHTML = template.evaluate(show) + e.innerHTML;

		var rand_id = 'new_text_' + Math.floor(Math.random() * 10000 + 1);

		e.insert({ top: '<div class="new-text" style="display:none" id="' + rand_id + '">' +  template.evaluate(show) + '</div><div class="section_tile"></div>' });
		//e.insert({ top: '<div class="new-text" id="' + rand_id + '">' +  template.evaluate(show) + '</div><br class="newbr" /><div class="section_tile"></div>' });

var height = $(rand_id).getDimensions().height;
		if (! stack)
		{
			$(rand_id).setStyle("height: "+height+"px;display:block" );
			
		} else
		{

			NList = $('comet').select('div.new-text');
			NSize = NList.length;

			SList = $('comet').select('div.section_tile');
			SSize = SList.length;

			var F = function ()
			{
				if (NSize >= 10)
				{
						NList[NSize-1].hide().remove();
						SList[SSize-1].hide().remove();
				}
			};


			new Effect.Parallel(
				[ 
				  new Effect.SlideDown(rand_id, {duration:1, fps: 35, scaleContent: false}),
				  new Effect.BlindUp($('comet').select('div.new-text')[$('comet').select('div.new-text').length-1], {duration:1, fps: 35, scaleContent: false})
				],

			{ duration: 1, afterFinish: F });

			if (! Stale)
			 	new Effect.Highlight(rand_id, {duration:2});


		/*
			an3 = new Animator({
				transition: Animator.makeEaseIn(3),
				duration: 300,
				onComplete: F
				}).addSubject(new CSSStyleSubject(
					$(rand_id),
					"height: 1px;display:block",
					"height: "+height+"px;display:block" ));

			an3.play();
		*/
			//new Effect.SlideDown(rand_id, {duration:1, scaleContent: false, scaleMode: 'box', afterFinish: F});
			//new Effect.Highlight(rand_id, {duration:2});
		}

	}

}
