(function($) {
	$(function() {
	
		var tpId = "#tooltip",
			tpIsHidden = true,
			tpTimeout,
			offset = 12,
			getX = function(mouseX,popupWidth) {
				var totalWidth = mouseX + popupWidth + offset + 17; //hack
				return totalWidth >= $(window).width() ? mouseX-popupWidth-(offset/2) : mouseX+offset;	
			},
			getY = function(mouseY,popupHeight) {
				var totalHeight = mouseY + popupHeight + offset + 17;
				return totalHeight >= $(window).height() ? mouseY-popupHeight-(offset/2) : mouseY+offset;
			};
			
		// custom overlay
		
		var overlay = function() {
			$("body").append('<div id="overlay"><div id="overlay-clip"><div id="overlay-close"></div><div id="overlay-content"></div></div></div>');
			this.$container = $("div#overlay");
			this.$content = $("div#overlay-content");
			this.$clip = $("div#overlay-clip");
			this.$close = $("div#overlay-close");
			var self=this;
			this.$close.click(function(){
				self.close();
			});
			this.inited = 0;
		}
		
		overlay.prototype = {
			init: function(el,$refEl) {
				this.$refEl = $refEl; //the element to base offset on
				this.$container.css({top: this.offsetTop(),
					left: this.offsetLeft()
				}).show();
				
				var self = this;
				
				this.$clip.css({
					top: this.$container.height()/2, 
					left: this.$container.width()/2, 
					width: 0, 
					height: 0
				}).animate({
					left:0,
					top:0,
					width:this.$container.width(),
					height:this.$container.height()
				},function() { 
					self.$content.css({overflow:'auto'}).empty()
						.append(self.getOverlay(el)).children('div').fadeIn();
						
					//close overlay on 'esc'
					$(document).keypress(function(e) {
						var key=logicbox.keyCode(e);
						if(key && key == 27) {
							self.close();
						}
					});
					//resize is prematurely fired in IE
					$(window).resize(
						function(){self.resize();}
					);
				});
				
				if (activePanel !== null)
					panelIn(activePanel);
				
				this.inited=1;
			},
			set: function(el,$refEl) {
				if (!this.inited) {
					this.init(el,$refEl);
				} else {
					//display stuff
					this.$content.empty().append(this.getOverlay(el)).children('div').show();
				}
				var page = $(el).attr('href').match(/#([a-z0-9]+)$/).pop();
				logicbox.pageTrack(el,null,'portfolio/' + page);
			},
			resize: function() {
				this.$container.css({left: this.offsetLeft()});
			},
			close: function() {
				var self = this;
				this.$content.css({overflow:'hidden'}).children('div').hide();
				this.$clip.animate({
					top: this.$container.height()/2, 
					left: this.$container.width()/2, 
					width: 0, 
					height: 0
				},function(){
					self.$container.hide();
					self.$content.empty()
					$(window).unbind('resize');
					$(document).unbind('keypress');
					self.inited=0;
				});
			},
			offsetTop: function() {
				var offset = this.$refEl.offset();
				return Math.round(offset.top)-this.$container.height();
			},
			offsetLeft: function() {
				var offset = this.$refEl.offset();
				var posX = (Math.round(offset.left)+(344/2))-this.$container.width()/2;
				if ((posX + this.$container.width())>$(window).width()) {
					posX -= (posX + this.$container.width()) - $(window).width();
				}
				return posX;
			},
			getOverlay: function(el) {
				var target = $(el).attr('href').match(/#[a-z0-9]+$/).pop();
				return $(target).clone(true);
			}
		}
		
		var portfolio = new overlay();
		
		
		$("#projects li a").each(function() {
			this.tooltip = $(this).attr('title');
			/*$(this).removeAttr('title').children('img').removeAttr('alt')*/;
			
		}).mouseover(function(e) {
				
			clearTimeout(tpTimeout);
				
			if (!$(tpId).length) { //insert html first-time
				$("body").append('<div id="tooltip"></div>');
			}
				
			$(tpId).text(this.tooltip);
			if (tpIsHidden) {
				var posX = getX(e.pageX,$(tpId).width());
				var posY = getY(e.pageY,$(tpId).height());
				$("#tooltip").css({top: posY,left: posX}).fadeIn(200);
			}
					
		}).mouseout(function() {
			//hide if not activated again within 50ms
			tpTimeout = setTimeout(function() {
				$(tpId).fadeOut(200);
				tpIsHidden=true;
			},50);
							
		}).mousemove(function(e) {
			var posX = getX(e.pageX,$(tpId).width());
			var posY = getY(e.pageY,$(tpId).height());
			$(tpId).css({top: posY,left: posX});
			
		}).click(function(e) {
			portfolio.set(this,$(this).parent().parent().parent());	
			return false;
		});
		
		$("#projects").simplyScroll({
			className: 'logicbox',
			autoMode: 'loop',
			pauseOnHover: false
		});	
		var activePanel = null,
		autoClose = true,
		tab1 = $(".tab-1")[0],
		tab2 = $(".tab-2")[0],
		panelOut = function(el) {
			el.state = 'out';
			var $el = $(".panel:eq("+ el.pos +")");
			$(el).prependTo($el);
			$($el).animate({left: "-250px"},800,function() {	
				if (autoClose)
					logicbox.pageTrack(el,null,$(el).text().toLowerCase());
			});
			if (activePanel!==null && el!==activePanel && autoClose) {
				panelIn(activePanel);
			}
			activePanel = el;
		},
		panelIn = function(el) {
			el.state = 'in';
			activePanel=null;
			$(el).parent().animate({left: 0},800,function() {
				//restore tab state
				if (el.pos==0 && activePanel!==null) {
					$(el).hide().prependTo(".tabs").fadeIn('slow');
				} else {
					$(el).prependTo(".tabs");
				}
			});
		},
		panelIt = function(el) {
			if (typeof el.state == "undefined" || el.state == "in") {
				panelOut(el);
			} else {
				panelIn(el);
			}
		},
		interval = null,
		animCount = 0,
		panelAnim = function() {
			animCount++;
			panelIt((animCount % 2 ? tab1 : tab2));
			
		},
		panelAnimInit = function() {
			autoClose = false;
			panelAnim();
			interval = setInterval(panelAnim,800);
			$('<div>Welcome! Use the konami code again to stop!</div>"').css({
				position: 'absolute',
				fontSize: '12px',
				fontWeight: 'bold',
				color: '#000000',
				backgroundColor: '#FFCC00',
				width: '280px',
				padding: '8px',
				display: 'none'
			}).appendTo('body').fadeIn();
			
		},
		panelAnimStop = function() {
			autoClose = true;
			clearInterval(interval);
			animCount=0;
			$("div:last").remove();
		};
		
		$(".tab")
			.each(function() {
				this.pos = $(".tab").index(this);
			})
			.click(function(){
				panelIt(this);
				return false;
		});
			
		var kkeys = [], konami = "38,38,40,40,37,39,37,39,66,65";
		$(window).bind("keydown", function(e) {
			kkeys.push( logicbox.keyCode(e) );
            if ( kkeys.toString().indexOf( konami ) >= 0 ) {
				(animCount>0) ? panelAnimStop() : panelAnimInit();
				kkeys = [];
			}
		});
				
	});
})(jQuery);
