var RuTvit = (function(){
	var $body, $header,
		tvits = [],
		tvitsAmount = 0,
		paused = false,
		options = {
			backgroundColor: '#fff',
			borderColor: '#69f',
			height: '400px',
			nickname: 'RuTvit'
		},
		timeOut,
		sinceId = 0,
		params = {};

	if (!window.jQuery) document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>');
	document.write('<link rel="stylesheet" href="http://rutvit.ru/css/widget.css" type="text/css"/>');		// /!\
	document.write('<div id="rutvit-widget"></div>');

	function init(_) {
		$('#rutvit-widget').html('<div id="rutvit-header"></div><div id="rutvit-tvits"></div><div id="rutvit-footer"><a href="http://rutvit.ru/">Присоединиться к обсуждению</a></div>');
		$('head').append('<style>#rutvit-widget{'
			+ (_.shellBackground ? 'background:#'+_.shellBackground+'!important;border-color:#'+_.shellBackground+'!important' : '')
			+ (_.width ? ';width:' + ( _.width == 'auto' ? 'auto' : (_.width + 'px') ) + '!important' : '')
			+ '}'
			+ (_.shellText ? '#rutvit-header *, #rutvit-footer a{color:#'+_.shellText+'!important}' : '')
			+ '#rutvit-tvits{' + (_.tvitBackground ? 'background:#'+_.tvitBackground+'!important' : '')
			+ (_.height ? ';height:'+_.height+'px!important' : '')
			+ (_.tvitText ? ';color:#'+_.tvitText : '') + '}'
			+ (_.tvitLink ? '#rutvit-tvits a{color:#'+_.tvitLink+'!important}' : '')
		+'</style>');
		$body = $('#rutvit-tvits')
			.bind('mouseenter', function(){ paused = true })
			.bind('mouseleave', function(){ paused = false }),
		$header = $('#rutvit-header');
		options.nickname = _.nickname;
		options.interval = _.interval || 5000;
		options.rotate = _.rotate;
		options.behavior = _.behavior || 'default';
		options.live = _.live || false;
		if (_.count) options.count = _.count;
		update();
	}
	
	function update(){
		if (options.count) params.count = options.count;
		$.getJSON('http://api.rutvit.ru/statuses/user_timeline.json?id='+options.nickname+'&callback=?',	// /!\
			params,
			function (_){
				// console.log(_)
				tvits = _;
				tvitsAmount = tvitsAmount || tvits.length;
				
				if (tvits.length) {
					$header.html('<a href="http://rutvit.ru/'+tvits[0].user.screen_name+'"><img src="'+tvits[0].user.profile_image_url+'"></a><p>'
						+(tvits[0].user.name||'')+'</p><a href="http://rutvit.ru/'+tvits[0].user.screen_name
						+'" class="rutvit-name">'+tvits[0].user.screen_name+'</a>');
				}
				
				sinceId = tvits[0] && tvits[0].id || sinceId;
				
				if (options.behavior == 'all') {
					var s = '';
					while (tvits.length) s += tvitTemplate(tvits.shift());
					s && $(s).prependTo($body);
				} else timer();

				if (options.live) {
					params.since_id = sinceId;
					setTimeout(update, 60000)
				}				
			}
		);
	}
	
	
	function tvitTemplate(tvit){
		var link = 'http://rutvit.ru/' + tvit.user.screen_name + '/tvit/' + tvit.unix_timestamp;
		return '<div>' + tvit.text_formatted
				+ '<i><a href="' + link + '?reply=on" class="reply">ответить</a>'
				+ '<a href="' + link + '">' + tvit.created_at_human_readable.replace(/ \+.*/, '') + '</a></i></div>';
	}
	
	function display() {
		$(tvitTemplate(tvits.pop())).css('display', 'none').prependTo($body).slideDown();
	}
	
	function rotate() {
		$('div:last', $body).slideUp(function(){
			$(this).prependTo($body).slideDown()
		});
	}
	
	function timer() {
		if (!paused)
			if (tvits.length)
				display();
			else
				if (tvitsAmount >= 10 && options.rotate) rotate();
		timeOut = setTimeout(timer, options.interval);
	}
	
	function reinit(params){
		$('#rutvit-widget').html('');
		clearTimeout(timeOut);
		RuTvit.init(eval('(' + params + ')'));
	}

	return {
			init: init,
			reinit: reinit
	}	
})();