redflex = {
	
	init: function(){
		redflex.tooltips.init();
		redflex.autogrow.init();
		redflex.smoothScroll.init();
		redflex.gallery.init();
		
	},
	
	
	
	tooltips: {
		gravity: 's',
		animate: true,
		fade: 250,
		fadeOutTimer: undefined,
		
		
		init: function(){
			$('.tooltip')
				.live("mouseover", function(){
					var elem = $(this);
					var title = elem.attr('title');
					
					clearTimeout(redflex.tooltips.fadeOutTimer);
					$('div.tip').stop().remove();
					var tip = $('<div class="tip"><div class="tip-inner"/></div');
					
					if (elem.attr('type') == 'image') {
						tip.find('.tip-inner').html('<img src="'+title+'" style="max-width:100px" />');
					} else {
						tip.find('.tip-inner').text(title);
					};
					
					tip.css({position: 'absolute', zIndex: 100000});
					elem.attr('original-title', title || '').attr('title', '');
					
					var pos = $.extend({}, elem.offset(), {width: elem.width(), height: elem.height()});
					tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).appendTo(document.body);
					var actualWidth = tip.width(), actualHeight = tip.height();
					
					var paddingV = parseInt(elem.css('paddingTop')) + parseInt(elem.css('paddingBottom'));
					pos.height += paddingV;
					
					var paddingH = parseInt(elem.css('paddingLeft')) + parseInt(elem.css('paddingRight'));
					pos.width += paddingH;
					
					var gravity = redflex.tooltips.gravity;
					if (elem.attr('gravity')){
						gravity = elem.attr('gravity');
					}
					
					var defaultCSS = {opacity: 0, display: "block", visibility: "visible"};
					switch (gravity.charAt(0)) {
	                	case 'n':
		                    tip.css({top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 - 5}).addClass('tip-north');
							var gravityCSS = {marginTop: '5px'};
		                    break;
		                case 's':
		                    tip.css({top: pos.top - actualHeight - 10, left: pos.left + pos.width / 2 - actualWidth / 2 - 5}).addClass('tip-south');
							var gravityCSS = {marginTop: '-5px'};
		                    break;
		                case 'e':
		                    tip.css({top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth - 12}).addClass('tip-east');
							var gravityCSS = {marginLeft: '-5px'};
		                    break;
		                case 'w':
		                    tip.css({top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width + 2}).addClass('tip-west');
							var gravityCSS = {marginLeft: '5px'};
		                    break;
		            }
		
					elem.data('gravity', gravity);
					
					if (redflex.tooltips.fade) {
						if (redflex.tooltips.animate) {
							var gravityCSS = $.extend(defaultCSS, gravityCSS || {});
							tip.css(gravityCSS).animate({opacity: 0.8, marginTop: 0, marginLeft: 0}, redflex.tooltips.fade);
						} else {
							tip.css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: 0.8}, redflex.tooltips.fade);
						};
						
					} else {
						tip.css({visibility: 'visible'});
					};
					
				})
				.live("mouseout", function(){
					var elem = $(this);
					var title = elem.attr('original-title');
					elem.attr('title', title).attr('original-title', '');
					
					redflex.tooltips.fadeOutTimer = setTimeout(function(){
						var tip = $('.tip');
						
						if (redflex.tooltips.fade) {
							if (redflex.tooltips.animate) {
								var defaultCSS = {opacity: 0};
								
								switch (elem.data('gravity').charAt(0)) {
									case 'n':
										var gravityCSS = {marginTop: '5px'};
										break;
									
									case 's':
										var gravityCSS = {marginTop: '-5px'};
										break;
									
									case 'e':
										var gravityCSS = {marginLeft: '-5px'};
										break;
									
									case 'w':
										var gravityCSS = {marginLeft: '5px'};
										break;
								}
								
								var gravityCSS = $.extend(defaultCSS, gravityCSS || {});
								tip.stop().animate(gravityCSS, redflex.tooltips.fade, function(){
									$(this).remove();
								});
								
							} else {
								tip.stop().fadeOut(redflex.tooltips.fade, function(){
									$(this).remove();
								});
								
							};
						} else {
							tip.remove();
						};
						
					}, 100);
					
				});
			
		},
		
	},
	
	
	
	panel: {
		panels: [],
		ticker: undefined,
		timeout: 7000,
		count: 0,
		
		init: function(){
			var i = 0;
			$('.panel-container .panel').each(function(){
				var panel = $(this);
				
				redflex.panel.panels[i] = {
					image: (panel.find('img').attr('src') || ''),
					content: (panel.find('.content').html() || '')
				}
				
				i += 1;
				
				panel.remove();
				
			});
			
			
			
			$('.panel-container').css({
				position: 'relative',
				overflow: 'hidden'
			}).html('<img class="panel-img" src="'+redflex.panel.panels[0].image+'" /><div id="panel-text">'+redflex.panel.panels[0].content+'</div><div id="panel-counter">1/'+redflex.panel.panels.length+'</div>');
			
			
			redflex.panel.ticker = setTimeout(redflex.panel.changeNext, redflex.panel.timeout);
			
		},
		
		
		
		changeNext: function(){
			var panelContainer = $('.panel-container');
			var panelTextContainer = $('#panel-text');
			var panelCountContainer = $('#panel-counter');
			var panelImage = $('.panel-img');
			
			redflex.panel.count = (redflex.panel.count == (redflex.panel.panels.length -1)) ? 0 : redflex.panel.count + 1;
			
			panelTextContainer.animate({
				top: '-'+parseInt(panelTextContainer.height())+'px'
			}, 400, function(){
				panelTextContainer
					.hide()
					.html(redflex.panel.panels[redflex.panel.count].content)
					.css({
						top: '-'+parseInt(panelTextContainer.height())+'px'
					});
				
				panelTextContainer
					.show()
					.animate({
						top: 0
					}, 400, function(){
						redflex.panel.ticker = setTimeout(redflex.panel.changeNext, redflex.panel.timeout);
					});
				
			});
			
			
			setTimeout(function(){
			panelImage.animate({
				opacity: '0'
			}, 400, function(){
				$(this).remove();
			});
			}, 400);
			
			
			$('<img/>')
				.attr('src', redflex.panel.panels[redflex.panel.count].image || '')
				.addClass('panel-img')
				.hide()
				.appendTo(panelContainer)
				.fadeIn(800);
			
			
			
			panelCountContainer.animate({
				top: '-'+ (parseInt(panelCountContainer.height()) + 5) +'px'
			}, 400, function(){
				panelCountContainer
					.hide()
					.html((redflex.panel.count+1)+'/'+redflex.panel.panels.length)
					.show()
					.animate({
						top: 0
					}, 400);
					
			});
			
		},
		
	},
	
	
	
	autogrow: {
		minHeight: 100,

		init: function(){
			$('textarea.autogrow').css({overflow: 'hidden'});

			$('textarea.autogrow').each(function(){
				redflex.autogrow.grow($(this));
			})

			$('textarea.autogrow').live('keyup',function(){
				redflex.autogrow.grow($(this))
			});

		},

		grow: function(textarea){
			//var textarea = $(this);
			var div = $('<div/>');

			var width = textarea.width();
			var text = textarea.val();

			text = text.replace(/\n/g,"<br />");

			div.addClass('textarea-autogrow').css({width: width}).html(text + '&nbsp;').hide();
			div.appendTo(document.body);

			var height = parseInt(div.height()) + 14;

			div.remove();

			if (parseInt(height) < redflex.autogrow.minHeight) {
				height = redflex.autogrow.minHeight;
			}
			textarea.height(height);
		},

	},
	
	
	
	twitterBar: {
		lastStatusID: 0,
		tweetStack: [],
		tweetDisplayTicker: undefined,
		tweetGetTicker: undefined,
		first: true,
		
		init: function(query){
			redflex.twitterBar.query = query;
			redflex.twitterBar.getData();
			redflex.twitterBar.tweetDisplayTicker = setInterval(redflex.twitterBar.displayTweet, 5000);
			
		},
		
		
		getData: function(){
			$.getJSON('http://search.twitter.com/search.json?callback=?&q='+redflex.twitterBar.query+'&since_id='+redflex.twitterBar.lastStatusID+'&clientsource=TWITTERINC_WIDGET',
				function(json){
					for (var i in json.results) {
						// create the tweet container
						var tweet = $('<a/>');
						
						tweet
							.addClass('tweet')
							.attr('href', 'http://twitter.com/'+json.results[i].from_user+'/status/'+json.results[i].id)
							.attr('target', '_blank')
							.html('<img src="'+json.results[i].profile_image_url+'" class="tweet-image" /><span class="tweet-text"><strong>'+json.results[i].from_user+':</strong> '+json.results[i].text+'</span>');
						
						
						redflex.twitterBar.tweetStack.push(tweet);
						
						
						// update the last status ID
						if (json.results[i].id > redflex.twitterBar.lastStatusID) redflex.twitterBar.lastStatusID = json.results[i].id;
						
					}
					
					redflex.twitterBar.tweetGetTicker = setTimeout(redflex.twitterBar.getData, 60000);
					
				});
			
		},
		
		
		displayTweet: function(){
			var tweet = redflex.twitterBar.tweetStack.pop();
			
			if (tweet != undefined) {
				var firstTweet = $('#tweet-container .tweet:first-child');
			
				tweet.prependTo('#tweet-container').hide();
			
				var tweetTextWidth = parseInt(tweet.width());
				var newWidth = tweetTextWidth/4 + 100;
			
				tweet.width(newWidth).css({marginTop: '-60px'});
				
				if (!redflex.twitterBar.first) {
					firstTweet.animate({
						marginLeft: newWidth+'px'
					},500,function(){
						firstTweet.css({marginLeft: 0});
						tweet.css({marginTop: 0}).fadeIn(500);
					});
					
				} else {
					tweet.css({marginTop: 0}).fadeIn(500);
					redflex.twitterBar.first = false;
					
				}
			}
			
		},
		
		
	},
	
	
	
	smoothScroll: {
		init: function(){
			$('a[href*="#"]').live('click', function(){
				if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
					$(this).blur();
					
					var $target = $(this.hash);
					$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');

					if ($target.length) {
						var targetOffset = $target.offset().top;
						$('html,body').animate({
							scrollTop: targetOffset
						}, 500);
						return false;
					}
				}
				
			});
			
		},
		
	},
	
	
	
	gallery: {
		init: function(){
			$('.thumbnail').live('mouseover', function(){
				redflex.gallery.show($(this));
				return false;
			});
			
			
			$('.thumbnail').live('click', function(){
				redflex.gallery.show($(this));
				return false;
			});
			
			
			$('.fullsize-link').live('click', function(){
				redflex.gallery.showFullsize($(this));
				return false;
			});
			
			
			$('.gallery').each(function(){
				var gallery = $(this);
				var images = [];
				var fullsize = $('<li/>');
				var thumbnailStrip = $('<li/>');
				var first = true;
				var firstImg = '';
				
				gallery.find('li').each(function(){
					var li = $(this);
					var img = li.find('img');
					var title = li.find('.title').html();
					var description = li.find('.description').html();
					
					
					var fullsizeLink = (img.attr('fullsize') == undefined) ? '' : ' fullsize="'+img.attr('fullsize')+'"';
					
					thumbnail = $('<img src="'+img.attr('src')+'" class="thumbnail"'+fullsizeLink+'" />')
									.data('title', title)
									.data('description', description);
									
					thumbnail.appendTo(thumbnailStrip);
					
					li.remove();
					
				});
				
				thumbnailStrip
					.addClass('thumbnails')
					.appendTo(gallery);
				
				fullsize
					.addClass('preview')
					.appendTo(gallery);
					
					
				thumbnailStrip.find('img:first-child').click();
				
			});
			
		},
		
		
		show: function(thumbnail){
			var thumbnailStrip = thumbnail.parent();
			var gallery = thumbnailStrip.parent();
			var preview = gallery.find('li.preview');
			
			thumbnailStrip.find('img').removeClass('active');
			thumbnail.addClass('active');
			
			var src = thumbnail.attr('src');
			var fullsize = '';
			if (thumbnail.attr('fullsize') != undefined) {
				fullsize = ' fullsize="'+thumbnail.attr('fullsize')+'" class="fullsize-link"';
			}
			
			var title = (thumbnail.data('title') == null) ? '' : '<h2 class="align-center" style="margin-bottom:10px">'+thumbnail.data('title')+'</h2>';
			var description = (thumbnail.data('description') == null) ? '' : thumbnail.data('description');
			
			preview.html(title+'<img src="'+src+'"'+fullsize+' />'+description);
			
		},
		
		
		showFullsize: function(thumbnail){
			var div = $('<div/>');
			var img = $('<img/>');
			
			var height = window.innerHeight - 20;
			var width = window.innerWidth - 20;
			
			div
				.css({
					position: 'fixed',
					height: '100%',
					width: '100%',
					top: '0',
					left: '0',
					zIndex: '5000',
					cursor: 'pointer',
					textAlign: 'center'
				})
				.attr('title', 'Click to close')
				.click(function(){
					$(this).animate({
						opacity: 0
					}, 400, function(){
						$(this).remove();
					});
				});
			
			img
				.attr('src', thumbnail.attr('fullsize'))
				.css({
					maxHeight: height,
					maxWidth: width,
					marginTop: '5px',
					cursor: 'pointer',
					border: '5px solid #2089cc'
				});
				
				
			div.hide().append(img).appendTo('body').fadeIn(400);
			
			return false;
		}
		
	},
	
	
	
};


$(document).ready(function(){
	redflex.init();
})