var _value = "";

function updateUrl( event ) {
	var value = event.value;
	if( value.charAt(0) != "/" )
	{
		$.address.value( "/"+ value );
	}
	else
	{
		if( ( _value != value || !_value ) && value )
		{
			try {
				if( value != "/" && swfobject.getObjectById("nudge").isDirty() )
				{
					if( !confirm("You wanted to change to another inudge. You will loose your current composition, are you sure you want to do that?") )
					{
						$.address.value(_value);
						return;
					}
				}
			} catch( e ) {}
			_value = value;
			updateFlash();
		}
	}
}
function updateFlash()
{
	try {
		swfobject.getObjectById("nudge").content( _value.substring(1) );
	} catch( e ) {}
}

function storeNudgeContent( string ) {
	$.address.value( string );
}

function restart( properties ) {
	setTimeout( function(){ updateTwitter( properties ) }, 1000 * 60 );
}

function updateTwitter( properties ) 
{
	$.ajax({
		url: "http://search.twitter.com/search.json?q="+properties.query+"&rpp="+properties.count,
		dataType:'jsonp',
		success: function( data, status )
		{
			if( data && data.results && data.results.length > 0 )
			{
				properties.data = data.results;
				renderTwitters( properties.data, properties);
			}
			restart( properties );
		},
		error: function(e) {
			restart( properties );
		}
	});
}

$.twitterQuery = function( properties )
{
	updateTwitter( properties );
}

function createNudges( ids, max, hits ) {
	var nudges = [];
	for( var i=0; i<ids.length && i < max; ++i)
	{
		var title = "iNudge #/"+ids[i];
		if( hits )
		{
			title += " "+hits[i]+" hits today";
		}
		nudges.push( $('<a href="#/'+ids[i]+'" class="nudgeLink" title="'+title+'"><img title="'+title+'" src="/inudgemicro.image.png?img[inudge_id]='+ids[i]+'"/></a>') );
	}
	return $(nudges);
}

$(document).ready( function() {
	$.address.init( updateUrl );
	$.address.change( updateUrl );
	$.twitterQuery({
		twitterTarget: "news-content",
		query: "inudge",
		clearContents: true,
		newwindow: true,
		count: 3,
		enableLinks: true,
		template: '<span class="text">%text%</span><span class="subline">by %from_user_link%  <a href="http://twitter.com/%from_user%/statuses/%id%" target="_blank" title="Open this tweet at twitter" class="time">%time%</a></span>',
	});
	var list1 = new NudgeList({
		url: "/inudge-latest-api",
		amount: 10,
		update: function( ids ) {
			createNudges( ids, 5 ).appendTo( $("#newlist").empty() );
		}
	});
	var list2 = new NudgeList({
		url: "/inudge-mostlistened-api",
		amount: 10,
		update: function( ids, hits ) {
			createNudges( ids, 5, hits ).appendTo( $("#hotlist").empty() );
		}
	});
});

swfobject.registerObject( "nudge", "10.0.0" );