(function()
{
	var self = $();
	
	LotusUI = function(options)
	{
		var defaults = {};
		self = this;
		
		self.$options = $.extend(defaults, options);
		self.$container = $('#container');
		self.$imageList = $('#image_list');
		self.$thumbs = $('#thumb_list');
		self.$thumbList = $('#thumb_list .horizontal');
		self.$header = $('#header');
		self.$shareUtil = self.$header.find('div.share_util');
		self.$socialBar = $('ul.social_bar.large');
		self.$shortcuts = self.$header.find('div.shortcuts');
		self.$search = self.$header.find('div.search ul.menu li:first-child input.txt');
		self.$searchInput = self.$header.find('form input.txt');
		self.$searchButton = self.$header.find('form a.button');
		self.$activeChannelPanel = $('#active_channel');
		self.$channels = self.$activeChannelPanel.find('ul.menu');
		self.$activeChannels = new Array();
		self.$nsfwToggle = self.$header.find('div.panel.nsfw');
		
		self.$imageTemplate = $('#img_template');
		self.$thumbTemplate = $('#t_template');
		self.$arrow_left = $('#arrow_left');
		self.$arrow_right = $('#arrow_right');
		
		// Because of absolute positioning we can't rely on document.body.height()
		self.$documentHeight = self.$thumbs.offset().top + self.$thumbs.outerHeight();
		self.$documentWidth = $(document.body).width();
		self.$thumbMargin = 10;
		self.$thumbWidth = 0;
		self.$groupWidth = 0;
		self.$headerHeight = self.$header.height();
	
		// Secondary Canvas
		self.$stableOpacity = false;
		self.$stableZIndex = false;
	
	}
	
	LotusUI.prototype.initialize = function(lotus)
	{
		self.$lotus = lotus;
		
		// Left right arrow aesthetics
		$('.arrow').hover(self.arrowMouseOver, self.arrowMouseOut);
		
		// Delete the tooltip if it already exists
		if(self.$shortcuts.data("qtip")) 
			self.$shortcuts.qtip("destroy");
		
		// Setup a tooltip for the keyboard shortcuts
		self.$shortcuts.qtip({
			content: "Using your left and right arrow keys will navigate between images.",
			position: {
				corner: {
				 tooltip: 'topRight',
				 target: 'bottomMiddle'
				}
			},
			style: {
				border: {
					width: 5,
					radius: 10
				},
				padding: 10, 
				textAlign: 'center',
				tip: true,
				name: 'dark'
			}
		});
		
		// Setup a tooltip for the nsfw filter
		self.$nsfwToggle.qtip({
			content: "Toggle for NSFW feeds",
			position: {
				corner: {
				 tooltip: 'topRight',
				 target: 'bottomMiddle'
				}
			},
			style: {
				border: {
					width: 5,
					radius: 10
				},
				padding: 10, 
				textAlign: 'center',
				tip: true,
				name: 'dark'
			}
		});
		self.$socialBar.find('li')
			.hover(self.socialBarMouseOver, self.socialBarMouseOut);
			
		$(window).resize(self.autoResize);
		$(document).bind('keyup', self.handleKeys);
		
		//Trigger it on page load
		self.autoResize();
		
		//$('.next, .prev').hover(highlightNextOrPrevious, removeHighlightNextOrPrevious);
		//$('.next, .prev').mouseleave(stopHighlightNextOrPrevious);
		
		self.$arrow_right.click(self.$lotus.nextImage);
		self.$arrow_left.click(self.$lotus.previousImage);
		
		self.$channels.find('li.channel').click(self.channelItemClick);
		self.$channels.find('li.channel ul.feeds li.feed').click(self.feedItemClick);
		self.$search.click(self.handleSearchClick);
		
		//Handle panels 
		self.$header.find('div.panel.toggle').click(self.handlePanelToggle);
		self.$nsfwToggle.click(self.handleNSFWToggle);
	}
	
	// Ads
	LotusUI.prototype.showAdUnit = function(el)
	{
		self.$imageList.find('div.adUnit iframe').remove();
		
		document.write = function(data)
		{
			el.find('div.ibg').append(data);
		}
		
		el.append($('<script language="javascript" type="text/javascript" src="http://social.bidsystem.com/displayAd.js"></script>'));
		
		self.$lotus.$lockSelection = true;
		setTimeout(self.unlockKeyboard, 6000);
	}
	
	LotusUI.prototype.unlockKeyboard = function()
	{
		self.$lotus.$lockSelection = false;
	}
	
	// <- -> Directional hotkeys
	// <- 37
	// -> 39
	LotusUI.prototype.handleKeys = function(e)
	{
		if(!self.$lockSelection)
		{
			self.$imageList.find('div.image').stop(true, true);
			
			if(e.which == 39)
			{
				self.$lotus.nextImage(e);
			}
			if(e.which == 37)
			{
				self.$lotus.previousImage(e);
			}
		}
	}
	
	LotusUI.prototype.alignThumbnails = function()
	{
		if(self.$lotus.$activeThumb.attr('id'))
		{
			var center = (self.$thumbs.width() / 2) - (self.$lotus.$activeThumb.outerWidth() / 2);
			var offset = (self.$thumbWidth + self.$thumbMargin) * self.$lotus.getAbsoluteIndex(self.$lotus.$activeThumb);
			var firstAvailableGroup = self.$lotus.getFirstAvailableGroup().thumbGroup;
			var firstAvailablePage = parseInt( firstAvailableGroup.attr('page') );	
			var ghostOffset = (firstAvailablePage - 1) * self.$groupWidth;
			var marginLeft = (center - offset) + ghostOffset;
			
			//console.log("center: " + center + " offset: " + offset + " firstPage: " + firstAvailablePage + " groupWidth: " + self.$groupWidth + " ghostOffset: " + ghostOffset);
			//console.log("marginLeft: " + marginLeft + " group: " + firstAvailableGroup.attr('id'));
			
			self.$thumbList.stop(true, true);
			self.$thumbList.animate({
				marginLeft: marginLeft + "px"
			});
		}
	}
	
	LotusUI.prototype.alignSocialBar = function() 
	{
		var top = self.$socialBar.offset().top;
		var width = self.$socialBar.width();
		var left = (self.$documentWidth / 2) - (width / 2);
				
		self.$socialBar.css({
			left: left + 'px',
		}).fadeIn(2000);
	}
	
	// Auto resize
	LotusUI.prototype.autoResize = function()
	{
		var thumbHeight = self.$thumbs.outerHeight();
		var headerHeight = self.$header.outerHeight();
		
		// Update values
		self.$documentWidth = $(document.body).width();
		self.$documentHeight = self.$thumbs.offset().top + thumbHeight;
		
		// Keep UI components correctly sized
		self.$header.width( self.$documentWidth );
		self.$thumbs.width( self.$documentWidth );
		self.$imageList.height( self.$documentHeight - thumbHeight - headerHeight);
		
		// Social plugins
		self.alignSocialBar();
		
		//Thumbnails
		self.alignThumbnails();
		
		// Visible images
		self.$lotus.updateImageState();
		
		// Position arrows
		$('.arrow').css({
			marginTop:	'-' + (thumbHeight) + 'px'
		});
	}
	
	LotusUI.prototype.checkArrows = function()
	{
		var prevThumb = self.$lotus.getPreviousThumb(self.$lotus.$activeThumb);
		
		if(prevThumb.attr('id') != self.$lotus.$activeThumb.attr('id'))
		{
			self.$arrow_left.css('display', 'block');
		}
		else
		{
			self.$arrow_left.css('display', 'none');
		}
		
		var nextThumb = self.$lotus.getNextThumb(self.$lotus.$activeThumb);
		
		if(nextThumb.attr('id') != self.$lotus.$activeThumb.attr('id'))
		{
			self.$arrow_right.css('display', 'block');
		}
		else
		{
			self.$arrow_right.css('display', 'none');
		}
	}
	
	LotusUI.prototype.highlightArrow = function(direction)
	{
		$('.arrow').stop(true, true);
		
		if(direction > -1)
		{
			self.$arrow_right.animate({
				opacity: 1
			}, 50, function()
			{
				self.$arrow_right.animate({
					opacity: 0.3
				}, 50);
			});
		}
		else
		{
			self.$arrow_left.animate({
				opacity: 1
			}, 50, function()
			{
				self.$arrow_left.animate({
					opacity: 0.3
				}, 50);
			});
		}
	}
	
	LotusUI.prototype.thumbMouseOver = function()
	{
		var background = $(this).attr('thumb_url');
		
		$(this)
		.find('div.tbg')
		.css({
			background: 'url(' + background + ') 50% 50% no-repeat'
		});
	}
	
	LotusUI.prototype.thumbMouseOut = function()
	{
		var background = $(this).attr('thumb_gs');
		
		if(!$(this).hasClass('active'))
		{
			$(this)
			.find('div.tbg')
			.css({
				background: 'url(' + background + ') 50% 50% no-repeat'
			});
		}
	}
	
	LotusUI.prototype.socialBarMouseOver = function()
	{
		self.$socialBar
			.find('li')
			.stop(true, true);
	
		$(this).animate({
			marginTop: '-10px',
			paddingBottom: '10px'
		}, 100);
	}
	
	LotusUI.prototype.socialBarMouseOut = function()
	{
		self.$socialBar
			.find('li')
			.stop(true, true);
	
		$(this).animate({
			marginTop: '0px',
			paddingBottom: '0px'
		}, 100);
	}
	
	LotusUI.prototype.handlePanelToggle = function(e) 
	{		
		if($(this).hasClass('active')) 
		{
			$(this).removeClass('active');
		} 
		else
		{
			self.$header.find('.panel.menu.toggle').removeClass('active');
			$(this).addClass('active');		
		}	
		e.stopPropagation();
	}
	
	LotusUI.prototype.channelItemClick = function(e)
	{
		var all = $(this).hasClass('all');
		var checked = $(this).hasClass('checked');
		
		if(all)
		{
			if(checked)
			{
				self.$channels.find('li').removeClass('checked')
			}
			else
			{
				self.$channels.find('li').addClass('checked');
			}
		}
		else
		{
			self.$channels.find('li.channel.all:first-child, li.channel.all:first-child li').removeClass('checked');
			
			if(checked)
			{
				$(this).removeClass('checked');
			}
			else
			{
				$(this).addClass('checked');
			}
		}
		
		if(!$(this).hasClass('checked'))
			$(this).find('ul.feeds li').removeClass('checked');
		else
			$(this).find('ul.feeds li').addClass('checked');
		
		self.updateActiveChannel();
		self.updateActiveFeed();
		
		e.stopPropagation();
	}
	
	LotusUI.prototype.feedItemClick = function(e)
	{
		var all = $(this).hasClass('all');
		var checked = $(this).hasClass('checked');
		var parent = $(this).parents('li.channel');
		var parentChecked = parent.hasClass('checked');
		
		if(!parentChecked)
		{
			parent.addClass('checked')
		}
		
		if(all)
		{
			if(checked)
			{
				parent.find('ul.feeds li').removeClass('checked');
			}
			else
			{
				parent.find('li').addClass('checked');
			}
		}
		else
		{
			parent.find('li.all').removeClass('checked');
			
			if(checked)
				$(this).removeClass('checked');
			else
				$(this).addClass('checked');
		}
		
		if(parent.find('li.checked').length <= 0)
		{
			parent.removeClass('checked');
		}
		
		self.updateActiveChannel();
		self.updateActiveFeed();
		
		e.stopPropagation();
	}

	LotusUI.prototype.updateActiveChannel = function()
	{
		
	}
	
	LotusUI.prototype.updateActiveFeed = function()
	{
		
	}
	
	LotusUI.prototype.handleSearchClick = function(e)
	{
		var def = 'e.g. porcupines';
		
		if($(this).val() == def)
			$(this).val('');

		e.stopPropagation();
	}
	
	LotusUI.prototype.handleNSFWToggle = function()
	{
		if($(document.body).hasClass('nsfw'))
		{
			$(document.body).removeClass('nsfw');
		}
		else
		{
			$(document.body).addClass('nsfw');
		}
	}
	
	LotusUI.prototype.arrowMouseOver = function() { $(this).addClass('hover'); }
	LotusUI.prototype.arrowMouseOut = function() { $(this).removeClass('hover'); }
	
})();
