/* Author: Matt Woodfield
 * Cubic Studio
 */

$(document).ready(function() {
    
    $('.main-col').each(function(e)
    {
      $(this).hide();
      $(this).fadeIn();
    });
    
    $('.ptt-logo').click(function(e)
    {
      window.location.href = '/';
    });

 		$('.ie6 .main-col .projects li:nth-child(3n+3), .ie7 .main-col .projects li:nth-child(3n+3), .ie8 .main-col .projects li:nth-child(3n+3)').css('margin-right', '0px');
		$('.ie6 .main-col .clients li:nth-child(4n+4), .ie7 .main-col .clients li:nth-child(4n+4), .ie8 .main-col .clients li:nth-child(4n+4)').css('margin-right', '0px');

		$('.cb-mt').each(function() 
    {
      var title = $(this).attr('title');
      var link = title;
      link = link.replace(/ dot /gi, '.');
      link = link.replace(/ at /gi, '@' );
      if(title == $(this).html())
      {
        $(this).html(link);
      }
      $(this).attr('title', 'Get in touch');
      $(this).attr('href', "mailto:"+link);
    });

});

// Slideshow
var Slideshow = function() 
{
  
    var slideshow, slides;
    var slideNum, currentSlide;
    var slideButtons, buttons;
    var timer, paused;
  
    function init(slideshowEl)
    {
      slideshow = slideshowEl;
      slides = slideshow.children('.slide');
      slideNum = slides.length;
      currentSlide = slideNum-1;
      paused = false;
      
			if(slideNum > 1)
			{
      	slideshow.mouseenter(handleSSMouseEnter);
      	slideshow.mouseleave(handleSSMouseLeave);
    	}

      buildSlideButtons();
      
      slides.css('display', 'none');
      slides.last().css('display', 'block');
            
      // Start timer
			if(slideNum > 1)
			{
      	startSlideshow();
			}
    };
    
    function handleSSMouseEnter()
    {
      if(slideButtons)
      {
        slideButtons.fadeIn();
      }
    };
    
    function handleSSMouseLeave()
    {
      if(slideButtons)
      {
        slideButtons.fadeOut();
      }
    };
    
    function buildSlideButtons()
    {
      buttons = new Array();
      slideButtons = $('<ul class="slide-buttons"></ul>');
      for(var i = 0; i < slideNum; i++)
      {
        var slideButton;
        if(i == slideNum-1)
        {
          slideButton = $('<li id="slide-'+i+'" class="current"><!-- button --></li>');
        }
        else
        {
          slideButton = $('<li id="slide-'+i+'"><!-- button --></li>');
        }
        
        buttons.push(slideButton);
        slideButtons.append(slideButton);
      }
        
      slideButtons.children('li').mouseenter(handleSlideButtonEnter)
      slideButtons.children('li').mouseleave(handleSlideButtonLeave);
      slideshow.append(slideButtons);
      slideButtons.css('left', (slideshow.width()*0.5)-(slideButtons.width()*0.5));
    };
    
    function handleSlideButtonEnter()
    {
      var id = $(this).attr('id');
      id = parseInt(id.replace('slide-', ''));
      pauseSlideshow();
      showSlide(id);
    }
    
    function handleSlideButtonLeave()
    {
      var id = $(this).attr('id');
      id = id.replace('slide-', '');
      startSlideshow();
    }
    
    function pauseSlideshow()
    {
      paused = true;
      clearTimeout(timer);
    }
    
    function startSlideshow()
    {
      paused = false;
      timer = setTimeout(nextSlide, 5000);
    }
    
    function nextSlide()
    {
      if(!paused)
      {
        showSlide(-1);
      }
    }
    
    function showSlide(index)
    {
      var slide = $(slides[currentSlide]);
      if(currentSlide != index)
      {
        slide.fadeOut(1300);
      }
      
      if(index != -1)
      {
        currentSlide = index;
      }
      else if(currentSlide == 0)
      {
        currentSlide = slideNum-1;
      }
      else
      {
        currentSlide--;
      }
      slideButtons.children('li.current').removeClass('current');
      buttons[currentSlide].addClass('current');
      slide = $(slides[currentSlide]);
      slide.fadeIn(1300);
      
      if(!paused)
      {
        startSlideshow();
      }
    }
    
    // Go go go…
    init($('.slideshow'));
};

// Projects
var Projects = function() 
{
    
    $('.projects li').mouseenter(function()
    {
      var overlay = $(this).find('.overlay');
      overlay.fadeIn('fast');
    });
    
    $('.projects li').mouseleave(function()
    {
      var overlay = $(this).find('.overlay');
      overlay.fadeOut('slow');
    });
    
    $('.ie .projects li').click(function()
    {
      var link = $(this).children('a.link').attr('href');
      window.location.href = link;
      return false;
    });
};

// Scroller
var Scroller = function() 
{
    
    var floater, floaterTop, backToTop;
    var units, numUnits;
    var windowWidth;
    var trackChapter, currentChapter;
    var currentUnit;
    
    function isiPad(){
        return (navigator.platform.indexOf("iPad") != -1);
    }
    
    function init(floatingEl, unitEls, trackCh)
    {
      // Vars
      floater = floatingEl;
      units = unitEls;
      numUnits = units.length;
      trackChapter = trackCh;
      floaterTop = $(floatingEl).offset().top-3; // -3 compensate for small jump
      backToTop = floater.children('.back-to-top');
      currentUnit = 0;
      
      if(numUnits <= 1) $('.scroll-units li').css('cursor', 'default');
      
      // Event binders
      $(window).scroll(handleScroll);
      $(window).resize(handleWindowResize);
      $('html').keydown(handleKeyDown);
      units.click(handleUnitClick);
      units.mousemove(handleUnitMouseMove);
      units.mouseleave(handleUnitMouseLeave);
      if(trackChapter) floater.find('a').click(trackAndGo);
      
      // Quick fire
      setTimeout(handleWindowResize, 500);
    };
    
    function handleScroll(e)
    {
      // Get current window scroll pos
      scrollTop = $(window).scrollTop();
      
      // If browser window is large enough to not chop menu off
      if($(window).height() > floater.height() && !isiPad())
      {
        if(scrollTop > floaterTop)
        {
          floater.addClass('floater');
          floater.css('left', $('.side-col').position().left);
          backToTop.fadeIn(); //css('opacity', '1.0');
        }
        else
        {
          floater.removeClass('floater');
          floater.css('left', '0px');
          backToTop.fadeOut(); //css('opacity', '0.0');
        };
      };
      
      // Check which units should be visible
      checkVisible();
    };
    
    function checkVisible()
    {
      // Cycle through units
      for(var i = 0; i < numUnits ; i++)
      {
        var unit = $(units[i]);
        var offset= 0
        if(trackChapter)
        {
          offset = unit.offset();
          if(scrollTop > offset.top-60)
          {
            if(unit.attr('id'))
            {
              currentChapter = unit.attr('id');
              var currentLink = floater.find('a[href="#'+currentChapter+'"]');
              if(!currentLink.hasClass('active'))
              {
                floater.find('a.active').removeClass('active');
                currentLink.addClass('active');
              }
            }
          }
        }
        
        if(!unit.hasClass('showing-content'))
        {
          offset = unit.offset();
          
          // Get inner content
          var content = unit.children('.unit-content');
          
          // Check if unit is showing and has not already been revealed
          if(scrollTop+windowHeight-50 > unit.offset().top)
          {
            // Prevent it from being shown again
            unit.addClass('showing-content');
            
            // Fade in
            content.css('opacity', '1.0');
          };
        };
      };
    };
    
    function handleWindowResize(e)
    {
      // Save windowHeight
      windowHeight = $(window).height()+90;
      
      // Keep floater in right place
      if(floater.hasClass('floater'))
      {
        floater.css('left', $('.side-col').position().left);
      }
      
      // Force scroll event
      handleScroll();
    };
    
    function handleKeyDown(e)
    {
      switch(e.keyCode)
      {
        case 37:
        case 38:
          // Left + Up
          var i = -1;
          var destination = 0;
          units.each(function()
          {
            i++;
            var offset = $(this).offset();
            if(offset.top > scrollTop)
            {
              offset = $(this).prev().offset();
              if(offset && offset.top > 150) 
              {
                destination = offset.top-24;
              }
              $.scrollTo( (destination)+'px', 500 );
              return false;
            }
          });
        return false;
        break;
        case 39: 
        case 40:
          // Right + Down
          var i = -1;
          var destination = 0;
          units.each(function()
          {
            i++;
            var offset = $(this).offset();
            if(offset.top-24 > scrollTop)
            {
              destination = offset.top-24;
              $.scrollTo( (destination)+'px', 500 );
              return false;
            }
          });
        return false;
        break;
      }
    }
    
    function handleUnitClick(e)
    {
      // Check this unit is visible
      var destination = 0;
      var offset = $(this).offset();
      if(scrollTop > offset.top-150 && scrollTop < offset.top+150)
      {
        // Get position to scroll to
        offset = $(this).next().offset();
        
        if(offset)
        {
          destination = offset.top-24;
        }
      }
      else
      {
        // Check for next
        var next = $(this).next().offset();
        
        if(offset && offset.top > 150)
        {
          destination = offset.top-24;
        } 
        
        if(!next && $(this).height()+offset.top < scrollTop+windowHeight)
        {
          destination = 0;
        }
      }
      
      // Animate window
      $.scrollTo( (destination)+'px', 500 );
    };
    
    $('.back-to-top').click(function(e)
    {
      // Animate window
      $.scrollTo( '0px', 500 );
    });
    
    function handleUnitMouseMove(e)
    {
      var caption = $(this).children('.unit-caption');
			var captionText = caption.children('p').html();
			if(captionText != '' && captionText != '<!-- no-caption -->')
			{
	      caption.stop().animate({ 'bottom': 0 });
			}
			var bottomLeft = $(this).find('.prompt-arrow');
			if(bottomLeft)
			{
				if(bottomLeft.hasClass('down'))
				{
					bottomLeft.addClass('down-over');
				}
				else if(bottomLeft.hasClass('down-inverse'))
				{
					bottomLeft.addClass('down-inverse-over');
				}
			}
    };
    
    function handleUnitMouseLeave(e)
    {
      var caption = $(this).children('.unit-caption');
      caption.stop().animate({ 'bottom': -35 });
			var bottomLeft = $(this).find('.prompt-arrow');
			if(bottomLeft)
			{
				if(bottomLeft.hasClass('down-over'))
				{
					bottomLeft.removeClass('down-over');
				}
				else if(bottomLeft.hasClass('down-inverse'))
				{
					bottomLeft.removeClass('down-inverse-over');
				}
			}
    };
    
    // Tweak for side nav realtive to page content
    function trackAndGo()
    {
      var href = $(this).attr('href');
      var targetEl = $(href);
      var destination = 0;
      if(href != "#overview")
      {
        destination = targetEl.offset().top-24;
      }
      
      // Animate window
      $.scrollTo( destination+'px', 500 );
      
      floater.find('a.active').removeClass('active');
      $(this).addClass('active');
      
      return false;
    };
    
    // Go go go…
    init($('.more-projects, .chapters, .contact-details'), $('.scroll-units li'), false);
};

// Projects
var Contact = function() 
{
	function init()
	{
		$('.scroll-units li .unit-content').css('opacity', '1.0');
	}
	
	// Go go go…
	init();
};
