var scrollTimeout;
var globalElem, globalPrevWidth;
var openBubble = true;

$(document).ready(function(){
	$("#tickerscroll").draggable({axis: 'x',drag: function(){
			var newLeft = parseInt($("#tickerscroll").css("left")) - 1;
			var firstElem = $(".tickeritem").eq(globalElem);
			if(newLeft<(0-(globalPrevWidth+firstElem.width()))){
				firstElem.clone().appendTo("#tickerscroll");
				globalPrevWidth += firstElem.width();
				globalElem++;
			} else if(newLeft>0){
				$("#tickerscroll").draggable('disable');
				$("#tickerscroll").mouseup();
			}
			clearTimeout(scrollTimeout);
			$("#tickerscroll").stop(true);
			openBubble = false;
		},
		stop: function(){
			rotate1(globalElem,globalPrevWidth);
			$("#tickerscroll").draggable('enable');
			setTimeout("openBubble = true",100);
		}
	});
	
	$(".tickeritem").unbind("click").live("click", function(e){
		if(openBubble){
			clearTimeout(scrollTimeout);
			$("#tickerscroll").stop(true);
			if($(this).attr('news_img')!=''){
				var width = $(this).attr("fullwidth");
				var height = $(this).attr("fullheight");
				var newWidth, newHeight, margin;
				if(width/height > 3.44){
					newWidth = 186;
					newHeight = height*(186/width);
				} else {
					newHeight = 54;
					newWidth = width*(54/height);
				}
				margin = (186-newWidth)/2;
				$("#newspopimage").attr({src: 'http://www.situationmarketing.com/content/news_images/'+$(this).attr('news_img'), width: newWidth, height: newHeight});
				$("#newspopimage").css({marginLeft: margin + "px"});
			} else {
				$("#newspopimage").attr({src: '/images/defaultnewspop.jpg', width: 186, height: 54});
			}
			$("#newspoptitle").text($(this).attr('news_title').substr(0,27) + "...");
			$("#newspoplink").attr({href: $(this).attr('news_link')});
			$("#newspop").css({left: e.pageX-88, display: 'block'});
			$("#tickerscroll").draggable('disable');
		}
	});
	
	$("#closenews").click(function(){
		$("#newspop").css({display: 'none'});
		$("#tickerscroll").draggable('enable');
		rotate1(globalElem,globalPrevWidth);
	});
	
	rotate1(0,0);
});

function rotate1(elem,prevWidth){
	var newLeft = parseInt($("#tickerscroll").css("left")) - 1;
	var firstElem = $(".tickeritem").eq(elem);
	if(newLeft<(0-(prevWidth+firstElem.width()))){
		firstElem.clone().appendTo("#tickerscroll");
		rotate1(elem+1,prevWidth+firstElem.width());
	} else {
		$("#tickerscroll").animate({left: "-=1px"},25,"linear");
		globalElem = elem;
		globalPrevWidth = prevWidth;
		scrollTimeout = setTimeout("rotate1("+elem+","+prevWidth+")",25);
	}
}