$(document).ready(init) ;

var animations = true ;

function init()
{
  // lazyLoadImages();
  // fadeLoadImages();
  
  // quick fixes
  $('.content:last').css('margin-bottom', '0');
  $('#menu a:last').css({float: 'right'});
  if ($.browser.opera) $('#wrapper').css({fontSize: '1.5em'});
  $('#portfolio-items .panel-wrapper:last').css('margin-bottom', 0);
  
  // ie fix
  $('a.portfolio_item').bind('click', function(e)
  {
    location = $(this).attr('href');
  });

  initDynamicHeaderHeight();  
  
  initImages();
  
  initPortfolioSlider();
  initHomeSlider();
  
  updateSliderHeightInterval = setInterval('updateSliderHeight()', 500);
}

var updateSliderHeightInterval = 0;
function updateSliderHeight()
{
  $('.coda-slider').each(function () 
  {
     var h = $(this).find('.panel-active:first').height();
     $(this).stop().animate({height: h}, 500);
  });
}

function fadeLoadImages()
{
  $('.img').css({opacity: 0}).bind('load', function(e)
  {
    $(this).animate({opacity: 1}, 500);
  });
}

var lazyImageLoading = 0;
function lazyLoadImages()
{        
  // prevent images being loaded    
  $('img').each(function()
  {
    $(this)
      .attr('source', $(this).attr('src'))
      .removeAttr('src')
      .bind('load', loadNextLazyImage)
    ;
  }); 
  loadNextLazyImage(); 
}

function loadNextLazyImage(e)
{
  var img = $('img:eq(' + lazyImageLoading + ')');
  if (img.length > 0)
  {
    img.attr('src', img.attr('source'));
    lazyImageLoading++;
  }
}

function initImages(slide)
{
  if (slide == true)
  {
    $('.images').each(function() 
    {
      var imgs = $(this).find('img');
      if (imgs.length > 1)
      {
        imgs.addClass('panel-wrapper').wrap('<div class="panel" />');
        $(this)
          .addClass('coda-slider preload')
          .wrap('<div class="coda-slider-wrapper left"></div>')
          .codaSlider({
            dynamicArrows: false,
            dynamicTabs: false,
            autoSlide: !animations,
            autoSlideInterval: 3000,
            slideHorizontal: false,
            onPanelChanged: onPanelChanged,
            continuous: false
          })              
        ;
      }      
    });     
  }
  else
  {
    $('.images').imageFader();
  }
  
  // fix height issue
  $('#portfolio-item .images').each(function() 
  {
    var h = 0;
    $(this).find('img').each(function() 
    {
       h = Math.max(h, $(this).height());
    });
    $(this).animate({height: h}, 100);
  });
  
  // adjust container height on each load
  $('.images img').bind('load', function()
  {
    var p = $(this).parent();
    var h = 0;
    p.find('img').each(function()
    {
       h = Math.max(h, $(this).height());
    });
    p.height(h);
  });
}

var smallHeader = null;
function initDynamicHeaderHeight()
{
  var ua = navigator.userAgent.toLowerCase();
  if (ua.indexOf('ipad') >= 0 || ua.indexOf('iphone') >= 0)
  {
    $('body').removeClass('small');
    return;
  }

  $(window).bind('resize', function(e)
  {
    var t = smallHeader == null ? 0 : 500;
    var h = $(window).height();
    if (h < 600 && smallHeader != true)
    {
      $('#header').stop().animate({height: 55}, t);
      $('#adds').stop().animate({width: 410, height: 70}, t);
      $('#menu').stop().animate({height: 44, fontSize: '2.7em'}, t); 
      $('#menu a:last').css({float: 'left'});    
      smallHeader = true;
    }
    else if (h >= 600 && smallHeader == true)
    {
      $('#header').stop().animate({height: 155}, t);
      $('#adds').stop().animate({width: 200, height: 165}, t);
      $('#menu').stop().animate({height: 200, fontSize: '4.9em'}, t);
      $('#menu a:last').css({float: 'right'}); 
      smallHeader = false;
    }   
    
    $('#header').toggleClass('small', smallHeader == true);
    
    $('body').delay(t).removeClass('small');
         
    // hack to trigger resets in IE
    $('.content').animate({opacity: 1}, t);
    
    // remember
    $.cookie('smallHeader', smallHeader ? '' : null, {path: '/'});
  });
  
  // first run
  $(window).trigger('resize'); 
}

function initHomeSlider()
{         
  $('.home_item').addClass('panel-wrapper').wrap('<div class="panel" />');
  $('#home')    
    .addClass('coda-slider preload')
    .wrap('<div class="coda-slider-wrapper" />')
    .codaSlider({
      dynamicArrows: false,
      dynamicTabs: false,
      onPanelChanged: onPanelChanged,
      continuous: false
    })        
  ; 
  
  if ($('.home_item').length < 2) $('#home_nav').hide();
  
  // show all home items after home slide is done, were previously hidden in php
  $('.home_item').show(); 
}

function onPanelChanged(e, data)
{   
  // stop all image faders
  $(e.target).find('.images').each(function()
  {
    if (this.stopImageFader) this.stopImageFader();
  });
  
  // start image fader in current panel
  $(data.currentPanel).find('.images').each(function()
  {
    if (this.startImageFader) this.startImageFader();
  });
  
  $('.nav_prev, .nav_next').removeClass('disabled');
  if (data.currentIndex == 0) $('.nav_prev').addClass('disabled');
  if (data.currentIndex == data.panelCount - 1) $('.nav_next').addClass('disabled');
}

function initPortfolioSlider()
{
  // run only on specific pages
  if ($('#portfolio-item').length == 0) return;

  // wrap 5 items
  var root = $('#portfolio-items');
  var items = $('.portfolio_item');
  var active_panel = 1; // active panel
  var group_size = 5;
  
  for (var i=0; i<items.length; i++)
  {    
    if ($(items[i]).hasClass('portfolio_item_active')) active_panel = Math.floor(i/group_size + 1);   
  }
  
  root
    .addClass('coda-slider preload')
    .wrap('<div class="coda-slider-wrapper" />')
    .codaSlider({
      firstPanelToLoad: active_panel,
      dynamicArrows: false,
      dynamicTabs: false,
      onPanelChanged: onPanelChanged,
      continuous: false
    })      
  ;
  
  if (items.length <= group_size) $('#portfolio_nav').hide();
}

jQuery.fn.outerHTML = function(s) 
{
  return (s)
  ? this.before(s).remove()
  : jQuery("<p>").append(this.eq(0).clone()).html();
};

var imageFaderCount = 0;
var imageFaders = [];
jQuery.fn.imageFader = function(options) 
{
  settings = $.extend({
		delay: 4000,
		fade: 500,
		autoStart: false,
		index: 0,
		interval: 0
	}, options);   
  
  return this.each(function()
  {		
    if ($('img', this).length > 1)
    {             	
  		var img_max_height = 0;
  		var img_max_width = 0;
  		
      $(this).find('img').each(function() 
      {   
        img_max_height = Math.max(img_max_height, $(this).height());
        img_max_width = Math.max(img_max_width, $(this).width());  
      });
      
      $(this).css({position: 'relative' , height: img_max_height, width: img_max_width});
      $(this).find('img:gt(0)').css({opacity: 0, position: 'absolute'});          
      
      nextImage = function(id)
      {
        var e = $('.image-fader-' + id);
        e.find('img').stop(true, false).animate({opacity: 0}, e.data('fade'));
        e.find('img:eq(' + e.data('index') + ')').stop(true, false).animate({opacity: 1}, e.data('fade'));
        e.data('index', e.data('index') + 1);
        if (e.data('index') >= $(e).find('img').length) e.data('index', 0);
      };
      
      this.stopImageFader = function()
      {
        //clearInterval(this.interval);
        $(this).stopTime('nextImage');
      };   
      
      this.startImageFader = function()
      {
         //if (animations) this.interval = setInterval('nextImage(' + imageFaderCount + ')', $(this).data('delay'));
         $(this).everyTime(
          $(this).data('delay'),
          'nextImage',
          function()
          {
            var e = $(this);
            e.find('img').stop(true, false).animate({opacity: 0}, e.data('fade'));
            e.find('img:eq(' + e.data('index') + ')').stop(true, false).animate({opacity: 1}, e.data('fade'));
            e.data('index', e.data('index') + 1);
            if (e.data('index') >= $(e).find('img').length) e.data('index', 0);  
          }
         );
      };
      
      if (animations && settings.autoStart) this.startImageFader();
      
      
      // fixes for ie setInterval
      $(this).data(settings).addClass('image-fader-' + imageFaderCount);      
      imageFaders['image-fader-' + imageFaderCount] = this;
      imageFaderCount++;
    }
  });         
}       

initSifr();
function initSifr()
{  
  var hnl = { src: base_dir + '/swf/sifr-helvetica-neu-lite.swf' };
  var hnb = { src: base_dir + '/swf/sifr-helvetica-neu-bold.swf' };
 
  /* 
  sIFR.prefetch(
    base_dir + '/swf/sifr-helvetica-neu-lite.swf',
    base_dir + '/swf/sifr-helvetica-neu-bold.swf'    
  );
  */
  
  sIFR.activate(hnl, hnb); 
  
  sIFR.replace(hnb, {
    selector: '#portfolio-item h1',
    css: [
      '.sIFR-root { background-color: #FFFFFF; font-weight: bold; text-transform: uppercase; color: #747933; font-size: 55; leading: -20; }',
      '.black { color: #000000; }'
    ],     
    wmode: 'opaque',
    offsetTop: -10,
    offsetLeft: 2,
    tuneHeight: -20,
    thickness: 100
  }); 
  
  sIFR.replace(hnb, {
    selector: '.text h1',
    css: [
      '.sIFR-root { background-color: #FFFFFF; font-weight: bold; text-transform: uppercase; color: #747933; font-size: 75; leading: -27; }',
      '.black { color: #000000; }'
    ],     
    wmode: 'opaque',
    offsetTop: -15,
    offsetLeft: 2,
    tuneHeight: -30,
    thickness: 100
  });
  
  sIFR.replace(hnb, {
    selector: '.text h2',
    css: [
      '.sIFR-root { background-color: #FFFFFF; font-weight: bold; text-transform: uppercase; color: #000000; font-size: 12; }'
    ],     
    wmode: 'opaque',
    thickness: 100
  }); 
  
  sIFR.replace(hnl, {
    selector: '.text h3',
    css: [
      '.sIFR-root { background-color: #FFFFFF; color: #000000; font-size: 13; }'
    ],     
    wmode: 'opaque'
  });
  
  sIFR.replace(hnl, {
    selector: '.home_item p, #portfolio-item p',
    css: [
      '.sIFR-root { background-color: #FFFFFF; color: #737373; font-size: 16; }'
    ],     
    wmode: 'opaque'
  }); 
  
  sIFR.replace(hnb, {
    selector: '.portfolio_item  h1',
    css: [
      '.sIFR-root { background-color: #FFFFFF; font-weight: bold; text-transform: uppercase; color: #000000; font-size: 12; cursor: pointer }'
    ],     
    tuneHeight: -5,
    wmode: 'opaque'
  });
  
  sIFR.replace(hnb, {
    selector: '#portfolio_more_links',
    css: [
      '.sIFR-root { background-color: #FFFFFF; font-weight: bold; text-transform: uppercase; color: #000000; font-size: 12; }',
      'a, a:link {color: #000000; text-decoration: none; }',
      'a:hover {color: #747933; }'
    ],     
    tuneHeight: -2,
    fitExactly: true,
    forceWidth: true,
    wmode: 'opaque'
  });
  
  sIFR.replace(hnl, {
    selector: '.portfolio_item  h2',
    css: [
      '.sIFR-root { background-color: #FFFFFF; color: #737373; font-size: 13; cursor: pointer }'
    ],     
    tuneHeight: -5,
    wmode: 'opaque'
  }); 
  
  sIFR.replace(hnl, {
    selector: '#portfolio_more p',
    css: [
      '.sIFR-root { background-color: #FFFFFF; color: #737373; font-size: 13; }'
    ],     
    tuneHeight: -5,
    wmode: 'opaque'
  });        
}
