/**
 * Userstream @ Supertopic
 * @created 22.06.2008
 * @updated 28.10.2008
 * @author 	Matthias Kunze
 */

var lastTimestamp = 0; // timestamp of last item
var lastUserID = 0; // user-id of last item
var intervalIndex = []; // haystack of interval indexes
var streamStarted = false; // stream already started?
var newTimeout = 0; // timeout for mouseout (default: 2 sec.)
var isMultiple = false; // multiple activities for one user
var showNewImages = true; // display new stream images
var countImages = 0; // current number of images
var panelHidden = true; // is the options panel hidden?

var enableDebug = false;

var currentItem = {};
var itemDivProperties = {
		fromTop : 0,
		fromLeft : 0,
		width : 0,
		height : 0
};

var ajaxFile = rootdir + '/app/widgets/userstream/ajax.stream.php';

/**
 * interval for displaying new activities
 */

var interval = getCookie('stream-interval') || 5; // in seconds

/**
 * init
 */

$j(document).ready(function () {
		$j('input[type=submit].abort').bind('click', abortStreamOptions);
		$j('.stream-options-trigger').bind('click', toggleOptionsPanel);
		$j('.stream-reload-trigger').bind('click', reloadStream);
		$j('#stream-options-form').bind('submit', saveStreamOptions);

		itemDivProperties = {
				fromTop : $('outer').offsetTop,
				fromLeft : $('outer').offsetLeft,
				width : $('outer').offsetWidth,
				height : $('outer').offsetHeight
		};

		bindMouseEvents();
		startStream();
});

function bindMouseEvents() {
		$j('.stream-outer').bind('mouseover', function (e) {
				checkOverAndOut(e);
		});
		$j('.stream-outer').bind('mouseout', function (e) {
				checkOverAndOut(e);
		});
}

function unbindMouseEvents() {
		$j('.stream-outer').unbind('mouseover').unbind('mouseout');
}

/**
 * check cursor position on mouseover and -out
 */

function checkOverAndOut(event) {

		// cursor position
		var cursor = getPosition(event);

		// mouseover
		if (cursor.y >= itemDivProperties.fromTop
			&& cursor.y < (itemDivProperties.fromTop + itemDivProperties.height)
			&& cursor.x >= itemDivProperties.fromLeft
			&& cursor.x < (itemDivProperties.fromLeft + itemDivProperties.width)) {
				// stop interval
				stopStreamInterval();
				jQuery('.stream-options-trigger').fadeIn('fast');
				jQuery('.stream-reload-trigger').fadeIn('fast');
		}
		// mouseout
		else {
				newTimeout = setTimeout("startStreamInterval()", 2000);
				jQuery('.stream-options-trigger').fadeOut('fast');
				jQuery('.stream-reload-trigger').fadeOut('fast');
		}
}

/**
 * get cursor position
 * @param event trigger
 */

function getPosition(e) {
	    e = e || window.event;
	    var cursor = {x:0, y:0};
	    if (e.pageX || e.pageY) {
		        cursor.x = e.pageX;
		        cursor.y = e.pageY;
	    }
	    else {
		        var de = document.documentElement;
		        var b = document.body;
		        cursor.x = e.clientX +
		            	(de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
		        cursor.y = e.clientY +
		            	(de.scrollTop || b.scrollTop) - (de.clientTop || 0);
	    }
	    return cursor;
}

/**
 * start stream with new images
 */

var picIndex = 0;
var userImages = [];
var prevPicLink = '';

function startStream() {

		var helperArray = [];

		$j.get(ajaxFile, {
            ts : lastTimestamp,
            ui : lastUserID
        }, function (data) {
                userStream = data;

							if (userStream.length == 0) {
							     if (lastTimestamp == 0 && lastUserID == 0) {
							            jQuery('.streampfeil').fadeOut();
                                        jQuery('#stream-images').fadeOut();
                                        jQuery('#stream-text').html('<span class="stream-text">Es wurden keine Aktivitäten gefunden.</span>');
                                        return false;
							     }
							     else {
							             lastTimestamp = 0;
							             lastUserID = 0;
							             return startStream();
							     }
							}

							jQuery('.streampfeil').fadeIn();
							jQuery('#stream-images').fadeIn();

							var counter = 0;
							jQuery.each(userStream, function () {
									if (counter == 0 || this.piclink != prevPicLink) {
											helperArray[counter] = { image : this.image, piclink : this.piclink, items : [] };
											helperArray[counter].items.push(this);
											counter++;
									}
									else {
											helperArray[counter-1].items.push(this);
									}

									prevPicLink = this.piclink;
							});

							userStream = helperArray;
							prevPicLink = '';
							showNewImages = true;
							itemCounter = 0;

							startStreamInterval();
		}, 'json');

		return false;
}

function startStreamInterval() {
		// if stream not started yet
		if (streamStarted === false) {
				parseStream();
				intervalIndex.push(setInterval("parseStream()", (interval * 1000)));
				streamStarted = true;
		}
}

function stopStreamInterval() {
		// stop all collected intervals
		while (intervalIndex.length) {
				clearInterval(intervalIndex.shift());
		}
		clearTimeout(newTimeout);
		streamStarted = false;
}

var itemIndex = 0;
var itemCounter = 0;

function parseStream() {
        if (picIndex == userStream.length) {
                stopStreamInterval();
				picIndex = 0;
				startStream();
				return false;
		}

		var arrowFromLeft = picIndex % 5;

		if (arrowFromLeft == 0 && itemCounter == 0) {
				// lade bilder
				var userImages = [];
				for (var i = picIndex; i < (picIndex + 5); i++) {
						// save new images
						userImages.push(
								'<a href="' + userStream[i].piclink + '"><img src="' + userStream[i].image + '" alt="" border="0" class="streampic" width="75" height="75" /></a>'
						);
						if (typeof(userStream[(i+1)]) === 'undefined') {
								break;
						}
				}
				jQuery('#stream-images')
						.animate({'opacity': .6}, 'fast')
						.html(userImages.join(''))
						.animate({'opacity': 1}, 'fast');
		}

		var newLeft = (75 * arrowFromLeft) + 'px';

		// move the arrow to the next image
		jQuery('.streampfeil').animate({'left': newLeft}, 'normal');

		currentItem = userStream[picIndex].items[itemIndex];

		showActivityItem(currentItem);
		itemCounter++;
		if (itemIndex == userStream[picIndex].items.length) {
				picIndex++;
				itemIndex = 0;
				itemCounter = 0;
		}
}

/**
 * generate the html
 */

function showActivityItem(object) {

		var itemText = object.text;
		var text = '<span class="stream-text">' + itemText + '</span><br/>'
				 + '<span class="stream-time">' + object.relative + '</span>';

		var div = cE('div');
		div.innerHTML = text;
		div.style.visibility = 'hidden';
		div.id = 'strDiv';

		// display new text
		$('stream-text').update();
		$('stream-text').appendChild(div);
		globalFadeOn('strDiv');

		// get the dimensions of the stream text div
		// for mouseover and -out events
		itemDivProperties = {
				fromTop : $('outer').offsetTop,
				fromLeft : $('outer').offsetLeft,
				width : $('outer').offsetWidth,
				height : $('outer').offsetHeight
		};

		// save the last timestamp
		lastTimestamp = object.time;
		lastUserID = object.userid;
		itemIndex++;
		//alert(itemIndex);
}

function toggleOptionsPanel() {
		return panelHidden === true ? showOptionPanel() : hideOptionPanel();
}

function showOptionPanel() {
		stopStreamInterval();
		jQuery('.streamoptions').fadeIn('fast', unbindMouseEvents);
		panelHidden = false;
		return false;
}

function hideOptionPanel() {
		jQuery('.stream-options-trigger').fadeOut('fast');
		jQuery('.stream-reload-trigger').fadeOut('fast');
		jQuery('.streamoptions').fadeOut('fast', function () {
				newTimeout = setTimeout("startStreamInterval()", 2000);
				bindMouseEvents();
		});
		panelHidden = true;
		return false;
}

function abortStreamOptions() {
		$('stream-options-form').reset();
		return hideOptionPanel();
}

function reloadStream() {
		abortStreamOptions();
		picIndex = 0;
		startStream();
		return false;
}

/**
 * saving the stream settings
 */

function saveStreamOptions() {
		jQuery.post(
				ajaxFile,
				jQuery('#stream-options-form').serialize(),
				function () {
						lastTimestamp = 0;
						lastUserID = 0;
						interval = jQuery('select[name=interval]').val();
						jQuery('.stream-options-trigger').fadeOut('fast');
						jQuery('.stream-reload-trigger').fadeOut('fast');
						jQuery('.streamoptions').fadeOut('fast', bindMouseEvents);
						panelHidden = true;
						picIndex = 0;
						setTimeout("startStream()", 700);
				}
		);
		return false;
}

