var gettingFeelings = false;
(function($) {

	var boxes = null;
	var opts;
	var items = new Array();
	var slidePaused = false;

	$.fn.twitbox = function(options) {
		// build main options before element iteration
		opts = $.extend({}, $.fn.twitbox.defaults, options);

		boxes = jQuery(this);
		// iterate and reformat each matched element
		boxes.each(function() {
			$this = jQuery(this);

			// build element specific options
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

			$this.css('position', 'relative');
			$this.css('overflow', 'hidden');

			if ($this.find('ul').length == 0) {
				$this.append('<ul></ul>');
			}
			var list = $this.find('ul');
			list.css('position', 'relative');
			list.css('margin', '0px');

			setSpace(list, 0, 0);

		});
	};

	$.fn.twitbox.addItem = function(item) {
		if (boxes == null) return false;
		items.push(item);
	};

	$.fn.twitbox.clearItems = function() {
		if (boxes == null) return false;
		items = Array();
	};

	$.fn.twitbox.pauseSlide = function() {
		if (boxes == null) return false;
		slidePaused = true;
	};

	$.fn.twitbox.resumeSlide = function() {
		if (boxes == null) return false;
		slidePaused = false;
	};

	$.fn.twitbox.startSlide = function() {
		if (boxes == null) return false;

		if (items.length > 0 && !slidePaused) {
			// iterate and reformat each matched element
			return boxes.each(function() {
				$this = jQuery(this);
				var list = $this.find('ul');

				if (parseInt(list.css('top')) == 0) {
					var item = items.shift();
					item = jQuery(item);

					// prepend item
					list.prepend(item);

					if ($this.twitbox.beforeAnimate) {
						$this.twitbox.beforeAnimate(item, list);
					}

					var height = item.outerHeight( { margin: true } );
					setSpace(list, -parseInt(height), 0);

					list.animate({paddingTop: height}, opts.speed);

					setTimeout(function() {
						setSpace(list, 0, 0);
						var i = 1;
						list.children('li').each(function() {
							if (i++ >= opts.maxsize && items.length > 0)
								jQuery(this).animate({opacity: 0}, opts.speed, function() {jQuery(this).remove();});
						});

						setTimeout(function() {$this.twitbox.startSlide();}, 100);
					}, opts.delay + (item.text().length) * 25);
				} else {
					setTimeout(function() {$this.twitbox.startSlide();}, 100);
				}
			});
		} else {
			setTimeout(function() {$this.twitbox.startSlide();}, 100);
			if (!gettingFeelings && items.length == 0) {
				jQuery.fn.getFeelings(currentFeeling, currentPage + 1);
			}
		}
	};

	function setSpace(list, top, padding) {
		list.css('top', top + 'px');
		list.css('padding-top', padding + 'px');
	}

	//
	// plugin defaults
	//
	$.fn.twitbox.defaults = {
		maxsize: 3,
		speed: 500,
		delay: 2000
	};

})(jQuery);

jQuery(function() {

	var container = jQuery('#feelingsContainer');

	currentFeeling = 0;
	currentPage = -1;

	var viewMode = jQuery('.viewMode.selected').attr('id');
	var imageDetails = jQuery('#imageDetails');

	jQuery.fn.hideFeeling = function() {
		jQuery('#feelingDetails')
			.animate({opacity: 0}, 200, function() {
				jQuery(this).hide();
				jQuery('#feelingModal').animate({opacity: 0}, 200, function() {jQuery(this).hide();});
			});
	}

	jQuery.fn.fixSize = function(img) {
		var pL = jQuery(window).height() / 2 - img.height / 2;
		var pT = jQuery(window).width() / 2 - img.width / 2;

		jQuery('#feelingDetails')
			.css('height', 'auto')
			.animate({top: pL - 60, left: pT - 40, right: pT - 60}, 300, function() {
				jQuery(this).find('.feelingHolder')
							.css('position', 'fixed')
							.css('color', '#fff')
							.css('background-color', '#000')
							.css('opacity', 0)
							.css('font-size', '18px')
							.css('font-weight', 'bold');
				if (window.ActiveXObject) {
					jQuery(this).find('.feelingHolder').animate({top: img.height / 2 + 30, left: 50, width: img.width, opacity: .7});
				} else { 
					jQuery(this).find('.feelingHolder').animate({top: pL + img.height / 2, left: pT + 20, right: pT + 5, opacity: .7});
				}
				jQuery(this).find('#feelingImage').animate({opacity: 1});
				jQuery(this).find('.previewActions').show();
			});
	};


	jQuery.fn.showFeeling = function(image) {
		var img = new Image();
		img.src = jQuery(image).attr('rel');

		jQuery('#feelingModal')
			.css('opacity', 0)
			.css('cursor', 'pointer')
			.attr('title', 'click to close')
			.show()
			.animate({opacity: .5});

		var pT = jQuery(window).height() / 2 - 100;
		var pL = jQuery(window).width() / 2 - 100;

		jQuery('#feelingDetails')
			.html('<div class="feelingHolder" style="opacity: 0;">' + unescape(jQuery(image).attr('title')) + '</div>' 
				+ '<div class="imageHolder"><img src="' + jQuery(image).attr('rel') + '" style="opacity: 0;" onload="jQuery.fn.fixSize(this);" id="feelingImage" /></div><div class="previewActions" style="display: none; text-align: right;"><a href="#" onclick="jQuery.fn.hideFeeling(); return false;">close</a></div>')
			.css('z-index', 999)
			.css('top', pT)
			.css('left', pL)
			.css('right', pL)
			.css('height', 200)
			.css('opacity', 0)
			.show()
			.animate({opacity: 1})
			.click(jQuery.fn.hideFeeling);

	}

	jQuery('#feelingModal').click(jQuery.fn.hideFeeling);

	function getFeelings(feelingId, page) {
		gettingFeelings = true;
		switch (viewMode) {
			case 'wordsView' :
				jQuery.post('/feelings/fetch', {feelingId: feelingId, page: page}, function(response) {
					if (response.total && response.total > 0) {
						for (var i in response.feelings) {
							if (response.feelings[i].sentence) {
								feeling = response.feelings[i];
								feelingDiv = jQuery('<li><div class="ltrFlngContTop">&nbsp;</div><div class="feelingHolder"><div class="feelingTitle"><strong style="color: ' 
														+ feeling.color + ';">' + feeling.title + '</strong>, ' + feeling.timeago + '</div>' 
														+ feeling.sentence + '</div><div class="imageHolder"><img src="' 
														+ feeling.imageurl +  '_thumb.jpg" rel="' + feeling.imageurl + '_original.jpg" title="' 
														+ escape(feeling.sentence) + '" onerror="this.style.display=\'none\';" onclick="jQuery.fn.showFeeling(this)" style="cursor: pointer;" /></div>' + '<br style="clear: both;" /><div class="ltrFlngContBottom">&nbsp;</div></li>');
								container.twitbox.addItem(feelingDiv);
							}
						}
						currentFeeling = feelingId;
						currentPage = page;
						container.twitbox.beforeAnimate = function(item, list) {
						};
					} else if (response.total == 0) {
						getFeelings(currentFeeling, 0);
					}
					gettingFeelings = false;
					container.find('ul').removeClass('ltrPicuresViewmode');
				}, 'json');
			break;
			case 'picturesView' : 
				jQuery.post('/feelings/fetch', {feelingId: feelingId, page: page, picturesOnly: true}, function(response) {
					if (response.total && response.total > 0) {
						feelingDiv = jQuery('<li></li>');
						var count = 0;
						for (var i in response.feelings) {
							if (response.feelings[i].sentence) {

								feeling = response.feelings[i];
								image = jQuery('<img src="' + feeling.imageurl + '_thumb.jpg" rel="' + feeling.imageurl 
									+ '_original.jpg" width="60" height="40" onclick="jQuery.fn.showFeeling(this)" onerror="this.src=\'/img/generic/no_image.jpg\';" title="' 
									+ escape(feeling.sentence) + '" style="cursor: pointer;" />');
								feelingDiv.append(image);
								if (++count == 10) {
									container.twitbox.addItem(feelingDiv);
									feelingDiv = jQuery('<li></li>');
									count = 0;
								}
								image.hover(
									function(e) {
										imageDetails
											.html(unescape(jQuery(this).attr('title')))
											.css('top', e.pageY - (window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop) + 50)
											.show();
										container.twitbox.pauseSlide();
									}, 
									function() {
										imageDetails.hide();
										container.twitbox.resumeSlide();
									}
								);
							}
						}
						currentFeeling = feelingId;
						currentPage = page;
						container.twitbox.beforeAnimate = function(item, list) {
						};
					} else if (response.total == 0) {
						getFeelings(currentFeeling, 0);
					}
					gettingFeelings = false;
					if (!container.find('ul').hasClass('ltrPicuresViewmode')) {
						container.find('ul').addClass('ltrPicuresViewmode');
					}
				}, 'json');
			break;
			case 'slideView' : 
				jQuery.post('/feelings/fetch', {feelingId: feelingId, page: page, picturesOnly: true}, function(response) {
					if (response.total && response.total > 0) {
						for (var i in response.feelings) {
							if (response.feelings[i].sentence) {

								feeling = response.feelings[i];
								feelingText = jQuery('<div class="feelingText" style="opacity: 0;">' + feeling.sentence + '</div>');
								feelingDiv = jQuery('<li style="text-aling: center;"></li>');
								image = jQuery('<a href="' + feeling.posturl + '" target="_blank"><img src="' + feeling.imageurl + '_full.jpg" rel="' + feeling.imageurl 
									+ '_original.jpg" onerror="this.src=\'/img/generic/no_image.jpg\';" title="' 
									+ escape(feeling.sentence) + '" class="feelingImage" style="cursor: pointer; width: 460px !important; height: auto !important; clear: both;" /></a>');
								feelingDiv.append(image);
								feelingDiv.append(feelingText);
								container.twitbox.addItem(feelingDiv);
								feelingText
									.css('position', 'relative')
									.css('clear', 'both')
									.css('z-index', 999)
									.css('color', '#fff')
									.css('background-color', '#000')
									.css('font-size', '18px')
									.css('font-weight', 'bold')
									.css('text-align', 'center')
									.css('top', -170)
									.css('left', 7)
									.css('width', 450)
									.css('opacity', .7);
							}
						}
						currentFeeling = feelingId;
						currentPage = page;
					} else if (response.total == 0) {
						getFeelings(currentFeeling, 0);
					}
					gettingFeelings = false;
					if (!container.find('ul').hasClass('ltrPicuresViewmode')) {
						container.find('ul').addClass('ltrPicuresViewmode');
					}
				}, 'json');
			break;
		}
	};

	jQuery.fn.getFeelings = getFeelings;

	jQuery('.feelingId').click(function() {
		jQuery('.feelingId.selected').each(function() {
			jQuery(this).removeClass('selected');
			jQuery(this).css('color', jQuery(this).css('background-color'))
			jQuery(this).css('font-weight', 'normal');
			jQuery(this).css('background-color', '');
		});

		jQuery(this).addClass('selected');
		jQuery(this).css('background-color', jQuery(this).css('color'))

		var color = jQuery(this).css('color');
		colors = color.substr(3).replace('(', '').replace(')', '').replace(' ', '').split(',');
		if (((parseInt(colors[0]) + parseInt(colors[1]) + parseInt(colors[2])) / 3) > 128) {
			jQuery(this).css('color', '#000');
		} else jQuery(this).css('color', '#fff');

		jQuery(this).css('font-weight', 'bold');
		container.twitbox.clearItems();
		getFeelings(jQuery(this).attr('id'), 0);
		return false;
	});

	jQuery('.feelingId.selected').each(function() {
		jQuery(this).css('background-color', jQuery(this).css('color'))
		jQuery(this).css('color', '#333');
	});

	jQuery('.viewMode').click(function() {
		if (jQuery(this).hasClass('selected')) return false;
		viewMode = jQuery(this).attr('id');
		container.twitbox.clearItems();
		container.empty();
		getFeelings(currentFeeling, currentPage);
		switch (viewMode) {
			case 'wordsView' :
				container.twitbox( { maxsize: 4, speed: 500, delay: 1000 } );
			break;
			case 'picturesView' : 
				container.twitbox( { maxsize: 11, speed: 500, delay: 4000 } );
			break;
			case 'slideView' : 
				container.twitbox( { maxsize: 1, speed: 1000, delay: 4000 } );
			break;
		}

		jQuery('.viewMode.selected').removeClass('selected');
		jQuery(this).addClass('selected');
		return false;
	});

	switch (viewMode) {
		case 'wordsView' :
			container.twitbox( { maxsize: 4, speed: 500, delay: 1000 } );
		break;
		case 'picturesView' : 
			container.twitbox( { maxsize: 11, speed: 500, delay: 4000 } );
		break;
		case 'slideView' : 
			container.twitbox( { maxsize: 1, speed: 1000, delay: 4000 } );
		break;
	}

	container.twitbox.startSlide();

});