var SkylabPage = Class.create(
{
	initialize: function() 
	{
		this.menu 		            		= $('menu');
		this.header				            = $('header');
		this.htmlElement              = document.body.parentNode;
		this.isMenuAttached		        = true;
		this.hasDetachedBefore 	      = false
		this.previousScroll 	        = 0;
		this.isTVShowing		          = false;
		//this.tvHeight			            = 0;
		this.isScrollBeingObservered  = false;		
		//this.isIE6                    = Prototype.Browser.IE && !window.XMLHttpRequest;
		
    if (globals.device == 'iphone')
    {
      Element.observe('tvLink', 'click', function(e) 
			{
			  window.location.href = "http://studioskylab.s3.amazonaws.com/test.mov";
			});
			
			var topLinks = $$('.linkTop');
			
			topLinks.each(function(link)
  		{
  		  Element.observe(link, 'click', function(e) 
  		  {
  		    window.scrollTo(0, 0);
  		  });
  		});
    }
    else
		{
		  var menuLinks = $$('.scroll');
		  
  		menuLinks.each(function(menuLink)
  		{			
  			this.addMenuLinkClickBehavior(menuLink);
			
  			Element.observe(menuLink, 'mouseout', function(e) 
  			{
  			  // Reset link background
  			  menuLink.removeClassName('reset');
  			}.bind(this));
			
  		}.bind(this));
				
		  var workLinks = $$('.workItem');

    	workLinks.each(function(link)
    	{
    		var workObject = new WorkLink(link);		
    	});
    	
    	swfobject.embedSWF("/mediaplayer/player.swf", "video", "960", "458", "9.0.0", "", {}, 
		  {
			  allowScriptAccess:	'always', 
			  allowFullScreen: 	  true,
			  quality: 			      'high',
			  bgcolor: 			      '#000000',
			  id:                	'tvskylab', 
			  wmode:              'transparent', 
			  flashVars:          'file=/rss/tv-our-work/&bufferlength=10&abouttext=Studio Skylab&aboutlink=http://www.studioskylab.com&skin=/mediaplayer/skylab.swf&playlist=right&playlistsize=240&shuffle=true&repeat=always'
		  });
    	
	  }
	},
	
	addMenuLinkClickBehavior: function(menuLink)
	{
	  Element.observe(menuLink, 'click', function(e) 
		{
		  // Turn background off when clicked so that you can see the page title scroll into place
		  menuLink.addClassName('reset');
		  
			var target = menuLink.hash.replace('#', '');

			if (target == 'tvskylab' && !this.isTVShowing)
			{						  
  			  // Get current window y scroll
  				var documentScrollY = document.viewport.getScrollOffsets()[1];
				
  				// Unhide the TV Skylab block
  				var tvSkylab = $('tvskylab');
  				if (tvSkylab) tvSkylab.style.display = 'block';
				
  				if (globals.device != 'IE6') this.startObservingScroll();
				
  				// Move the window Y-scroll position to mask the fact that the TV block is now showing.
  				window.scrollTo(0, tvSkylab.offsetHeight + documentScrollY);
  				this.headerHeight = this.header.offsetHeight;

  				this.isTVShowing = true;			  
			}

      // Scroll to appropriate section.
			new Effect.ScrollTo(target, 
			{ 
			  duration: 1.0, 
			  transition: Effect.Transitions.EaseFromTo
			});

			Event.stop(e);
			
		}.bind(this));
	},
	
	startObservingScroll: function()
	{
	  if (this.isScrollBeingObservered == false && this.menu)
	  {
	    Element.observe(window, 'scroll', function(e) 
  		{	  			
				//console.log(document.viewport.getScrollOffsets()[1])
				
				//if (document.viewport.getScrollOffsets()[1] < 405)
				if (document.viewport.getScrollOffsets()[1] < 460)
				{				
					this.detachMenu();
				}
				else this.attachMenu();			
			  
  		}.bind(this));
  		
  		this.isScrollBeingObservered = true;
	  }
	},
	
	attachMenu: function()
	{
    if (!this.isMenuAttached)
    {
      //console.log('Attach')
      $('menu').setStyle({ position: 'fixed', top: '50px' });
      
      //if (Prototype.Browser.IE) $('block1').setStyle({ paddingTop: '10px' });
      //else $('block1').setStyle({ paddingTop: '6px' });
      //$('block1').setStyle({ paddingTop: '11px' });
  		this.isMenuAttached	= true;
  	}
	},
	
	detachMenu: function()
	{
		if (this.isMenuAttached)
		{
		  //console.log('Detach')
	  	//if (Prototype.Browser.IE) var block1PaddingTop = '10px';
	  	if (Prototype.Browser.IE) var block1PaddingTop = '10px';
	  	else var block1PaddingTop = '6px';
	  	
	  	$('block1').setStyle({ paddingTop: block1PaddingTop });
  		$('menu').setStyle({ position: 'absolute', top: '512px' });
  		$('top').setStyle({ marginTop: 0, paddingTop: '72px', backgroundPosition: '0 -6px' });
		
  		this.isMenuAttached		= false;
  		this.hasDetachedBefore 	= true;
  	}
	}
	
	/*
	attachMenu: function()
	{
    if (!this.isMenuAttached)
    {
      //console.log('Attach')
      $('menu').setStyle({ position: 'fixed', top: '50px' });
      $('block1').setStyle({ paddingTop: '2px' });
  		this.isMenuAttached	= true;
  	}
	},
	
	detachMenu: function()
	{
		if (this.isMenuAttached)
		{
		  //console.log('Detach')
	  	if (Prototype.Browser.IE) var block1PaddingTop = '4px';
	  	else var block1PaddingTop = '0px';
	  	
	  	$('block1').setStyle({ paddingTop: block1PaddingTop });
  		$('menu').setStyle({ position: 'absolute', top: '454px' });
  		$('top').setStyle({ marginTop: 0, paddingTop: '72px', backgroundPosition: '0 -6px' });
		
  		this.isMenuAttached		= false;
  		this.hasDetachedBefore 	= true;
  	}
	}	*/
});

var WorkLink = Class.create(
{
	initialize: function(linkElement) 
	{
		this.linkElement 	= linkElement;
		this.status 		  = 'closed';
		this.overlay 		  = linkElement.next();
		this.image			  = linkElement.down();
		this.imageHeight	= this.image.offsetHeight;
		
		this.overlay.setStyle({ width: this.image.offsetWidth + 'px', top: (this.imageHeight/2) + 'px', height: 0 });

		//this.overlay.setStyle({ width: this.image.offsetWidth + 'px', top: '0px', height: '107px' });
		
		Element.observe(this.overlay, 'click', function(e) 
		{
			location.href = this.linkElement.href;
		}.bind(this));
		
		Element.observe(linkElement, 'mouseover', function(e) 
		{		
			//if (this.isMouseLeaveOrEnter(e, this.overlay))
			if (true)
			{
				this.open();
			}
			//else console.log('no leaving/entering')
			
			Event.stop(e);
		}.bind(this));
		
		Element.observe(this.overlay, 'mouseout', function(e) 
		{
			if (this.isMouseLeaveOrEnter(e, this.overlay))
			{
				this.close();
			}
			
			Event.stop(e);
			
		}.bind(this));
		
		
		Element.observe(linkElement, 'mouseout', function(e) 
		{		
			if (this.isMouseLeaveOrEnter(e, this.overlay))
			{
				this.close();
			}
			
			Event.stop(e)
		}.bind(this));
	},
	
	isMouseLeaveOrEnter: function(e, handler) 
	{ 
		if (e.type != 'mouseout' && e.type != 'mouseover') return false; 
		
		var reltg = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ? e.toElement : e.fromElement; 

		while (reltg && reltg != handler && reltg.parentNode) reltg = reltg.parentNode; 

		//if (reltg == handler)
		//{
		//	console.log(e.relatedTarget)
		//}
		return (reltg != handler); 
	},
	
	open: function()
	{		
		if (this.status == 'closing' && this.closeEffect)
		{
			this.closeEffect.cancel();
		}
		
		this.status = 'animating';
		this.openEffect = new Effect.Parallel
		(
			[
				new Effect.Opacity(this.overlay, { sync: true, to: 1 }),
		  	new Effect.Morph(this.overlay, { sync: true, style: 'top: 0; height: ' + this.imageHeight + 'px' })
			], 
			{ 
		  		duration: 0.8,
				transition: Effect.Transitions.EaseTo,
				afterFinish: function()
				{
					this.status = 'open';
					this.openEffect = null;		
				}.bind(this)
			}
		);
	},
	
	close: function()
	{
		if (this.status != 'closing')
		{
			if (this.openEffect) this.openEffect.cancel();

			this.closeEffect = new Effect.Parallel
			(
				[
					new Effect.Opacity(this.overlay, { sync: true, to: 0 }),
			  	new Effect.Morph(this.overlay, { sync: true, style: 'top: ' + this.imageHeight/2 + 'px; height: 0px' })
				], 
				{ 
			  		duration: 1,
					transition: Effect.Transitions.EaseFromTo,
					afterFinish: function()
					{
						this.status = 'closed';
					}.bind(this)
				}
			);
		
			this.status = 'closing';
		}
	}
});

/*
function isMouseLeaveOrEnter(e, handler) 
{ 
	if (e.type != 'mouseout' && e.type != 'mouseover') return false; 
	
	var reltg = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ? e.toElement : e.fromElement; 
	
	while (reltg && reltg != handler && reltg.parentNode) reltg = reltg.parentNode; 
	
	return (reltg != handler); 
}*/

//document.observe("dom:loaded", function() 
Element.observe(window, 'load', function()
{
	var links = $$('a');
	
	links.each(function(link)
	{
		if (!link.hasClassName('noFade'))
		{
			Element.observe(link, 'mouseover', function(e) 
			{
				new Effect.Morph(link, {style: 'color: #ec008c', duration: 0.2});
				Event.stop(e);
			});

			Element.observe(link, 'mouseout', function(e) 
			{
				new Effect.Morph(link, {style: 'color: #00acec', duration: 0.2});
				Event.stop(e);
			});
		}
		
		if (link.hasClassName('blank'))
		{
			Element.observe(link, 'click', function(e) 
			{
				window.open(link.href);
				Event.stop(e);
			});
		}
	});
	
	if (globals.section == 'work') var page = new SkylabPage();

  if (globals.isCommentPreview)
  {
    if (globals.device == 'iphone')
    {
      Element.scrollTo('headingPreview');
    }
    else 
    {      
      var headingElement = $('headingPreview');
      var pos = headingElement.cumulativeOffset();
      window.scrollTo(0, pos[1] - 70);
      
      /*
      new Effect.ScrollTo('headingPreview', 
			{ 
			  duration: 1.0, 
			  transition: Effect.Transitions.EaseFromTo
			});
			*/
    }
  }
});


/* 
transitions.js
Based on Easing Equations v2.0 
(c) 2003 Robert Penner, all rights reserved. 
This work is subject to the terms in http://www.robertpenner.com/easing_terms_of_use.html
Adapted for Scriptaculous by Ken Snyder (kendsnyder ~at~ gmail ~dot~ com) June 2006 
*/

// Overshooting Transitions 

// Elastic (adapted from "EaseOutElastic") 
Effect.Transitions.Elastic = function(pos) { 
    return -1*Math.pow(4,-8*pos) * Math.sin((pos*6-1)*(2*Math.PI)/2) + 1; 
}; 
// SwingFromTo (adapted from "BackEaseInOut") 
Effect.Transitions.SwingFromTo = function(pos) { 
    var s = 1.70158; 
    if ((pos/=0.5) < 1) return 0.5*(pos*pos*(((s*=(1.525))+1)*pos - s)); 
    return 0.5*((pos-=2)*pos*(((s*=(1.525))+1)*pos + s) + 2); 
}; 
// SwingFrom (adapted from "BackEaseIn") 
Effect.Transitions.SwingFrom = function(pos) { 
    var s = 1.70158; 
    return pos*pos*((s+1)*pos - s); 
}; 
// SwingTo (adapted from "BackEaseOut") 
Effect.Transitions.SwingTo = function(pos) { 
    var s = 1.70158; 
    return (pos-=1)*pos*((s+1)*pos + s) + 1; 
};


// Bouncing Transitions 

// Bounce (adapted from "EaseOutBounce") 
Effect.Transitions.Bounce = function(pos) { 
    if (pos < (1/2.75)) { 
        return (7.5625*pos*pos); 
    } else if (pos < (2/2.75)) { 
        return (7.5625*(pos-=(1.5/2.75))*pos + .75); 
    } else if (pos < (2.5/2.75)) { 
        return (7.5625*(pos-=(2.25/2.75))*pos + .9375); 
    } else { 
        return (7.5625*(pos-=(2.625/2.75))*pos + .984375); 
    } 
}; 
// BouncePast (new creation based on "EaseOutBounce") 
Effect.Transitions.BouncePast = function(pos) { 
    if (pos < (1/2.75)) { 
        return (7.5625*pos*pos); 
    } else if (pos < (2/2.75)) { 
        return 2 - (7.5625*(pos-=(1.5/2.75))*pos + .75); 
    } else if (pos < (2.5/2.75)) { 
        return 2 - (7.5625*(pos-=(2.25/2.75))*pos + .9375); 
    } else { 
        return 2 - (7.5625*(pos-=(2.625/2.75))*pos + .984375); 
    } 
};
 
//Gradual Transitions 
 
// EaseFromTo (adapted from "Quart.EaseInOut") 
Effect.Transitions.EaseFromTo = function(pos) { 
    if ((pos/=0.5) < 1) return 0.5*Math.pow(pos,4); 
    return -0.5 * ((pos-=2)*Math.pow(pos,3) - 2);    
}; 
// EaseFrom (adapted from "Quart.EaseIn") 
Effect.Transitions.EaseFrom = function(pos) { 
    return Math.pow(pos,4); 
}; 
// EaseTo (adapted from "Quart.EaseOut") 
Effect.Transitions.EaseTo = function(pos) { 
    return Math.pow(pos,0.25); 
};