// jQuery-based Javascript layer for asynchronous gallery navigation
// Copyright 2009 Barney Carroll

var thisUri = window.location.href;
var colour;

// Get URI parameters
function gup(name,uri){
  name = name.replace(/[\[]/,'\\\[').replace(/[\]]/,'\\\]');
  var regex = new RegExp('[\\?&]'+name+'=([^&#]*)');
  var results = (uri) ? regex.exec(uri)  : regex.exec(thisUri);
  return (results == null) ? '' : results[1];
}

// Replace URI parameters based on same-page navigation
function rup(theOld,theNew){
  var links = document.getElementsByTagName('a');
  for(i=0;i<links.length;i++){
    var param = theOld.split('=')[0];
    var ulId = $('a').eq(i).parents('ul').attr('id');
    if(
      !(param === 'context' && ulId === 'contextNav') ||
      !(param === 'gallery' && ulId === 'galleryNav') ||
      !(param === 'image' && ulId === 'imageNav') ||
      !(param === ('p' || 's' || 'm') && ulId === 'galleryControls')
    ){
      var oldHref = links[i].href;
      var getRidOf = new RegExp(theOld);
      links[i].href = oldHref.replace(getRidOf, theNew);
    }
  }
}

// Extract page variables from URI query string if defined, or set defaults
var contextId = gup('context') ? gup('context') : 'About';
var galleryId = gup('context') ? gup('gallery') : 'Surfaces';
var imageNumber = gup('image') ? gup('image') : 1;
var maximised = gup('m') ? gup('m') : 0;
var playing = gup('p') ? gup('p') : 0;
var shuffle = gup('s') ? gup('s') : 0;

// If PHP is telling the gallery slideshow to play via HTTP refresh, stop it
if(playing === '1')  location.href = thisUri.split('&p=1')[0] + thisUri.split('&p=1')[1];

// Build an asynchronous iamge loader into jQuery for chainability
$.fn.imgLoad = function(src,callback){
  return this.each(function(){
      var newImg = new Image();
      this.appendChild(newImg);
      newImg.onload = callback;
      newImg.onreadystatechange = callback;
      newImg.src = src.replace('&amp;', '&');
  });
}

// Fade out current image and replace with a new one
function switchImg(imgLink, leaveNav){
  var imgFileName = $(imgLink).children('span').html();
  var imgTitle = $(imgLink).attr('title');
  var imgNumber = imgTitle.split(' ')[1];
  $('#gallery img').stop();
  if(!imgNumber) imgNumber = function(){
    var navLinkTitle = $('span:contains('+imgFileName+')').parent('a').attr('title');
    return navLinkTitle.split(' ')[1];
  }
  $('#gallery img').fadeOut(600, function(){
    $('#gallery img').remove();
    if(!leaveNav) $('#imageNav li').stop().removeClass('current').animate({backgroundColor:'#777'}).children('a').animate({opacity:.5});
    $('#gallery a').imgLoad(galleryId+'/'+imgFileName, function(){
      if(!leaveNav) $('#imageNav li').eq((imgNumber*1)-1).stop().addClass('current').animate({backgroundColor: colour}).children('a').animate({opacity:0});
      $('h3 span.index').html(imgNumber);
      $('#gallery img').attr('alt', galleryId+' photo '+imgNumber).css({'display':'block'}).hide().fadeIn(600);
      if(playing === 1) slideshow();
    })
  })
  // Edit: change title to reflect new image
  $('title').html('Anne-Marie Carroll | Photographer | '+galleryId+' '+imgNumber);
}

// Slideshow mechanism
function slideshow(command){
  if(command === 'stop'){
    window.clearInterval(galleryPlay);
    playing = 0;
  } else {
    if(playing === 1) window.clearInterval(galleryPlay);
    galleryPlay = window.setInterval('nextImg()',4000);
    playing = 1;
  }
}

function nextImg(){
  $('#gallery a').click();
}

// All the contextual stuff
function dynamicFx(callback){
  colour = $('li.'+galleryId+' span').html();
  // Dynamic hover effects
  $('h1 a').hover(function(){
  	$(this).stop().animate({opacity: 1}, 600);
  }, function(){
  	$(this).stop().animate({opacity: 0}, 600);
  });
  $('#contextBlock li > a:first-child').add('#galleryNav a').hover(function(){
    var relevance = ($(this).parents('div').attr('id') === 'contextBlock') ? contextId : galleryId;
    var endOpacity = ($(this).parent('li').hasClass(relevance)) ? 1 : 0.75;
    $(this).stop().animate({opacity: endOpacity}, 300);
  }, function(){
    var relevance = ($(this).parents('div').attr('id') === 'contextBlock') ? contextId : galleryId;
    var endOpacity = ($(this).parent('li').hasClass(relevance)) ? 1 : 0.5;
    $(this).stop().animate({opacity: endOpacity}, 300);
  })
  $('#galleryControls li a').hover(function(){
    $(this).stop().animate({opacity: 0.75}, 300);
  }, function(){
    $(this).stop().animate({opacity: 0.5}, 300);
  })
  $('#imageNav li a').hover(function(){
    $(this).stop().animate({opacity: 0}, 300);
  }, function(){
    if(!$(this).parent('li').hasClass('current')){
      $(this).stop().animate({opacity: 0.5}, 300);
    }
  })
  $('#messageNext').hover(function(){
    $(this).stop().animate({opacity: 1}, 300);
  }, function(){
    $(this).stop().animate({opacity: 0.75}, 300);
  })
  $('li.News .copy div').hover(function(){
  	$(this).children('p').stop().css({opacity:0,'display':'block'}).animate({opacity:1},600);
  	$('li.News .copy div').css({'z-index':'0'});
  	$(this).css({'z-index':'1'});
  	$(this).children('h3').stop().animate({color:'#000'}, 300);
  },function(){
  	$(this).children('p').stop().animate({opacity:0}, 600, 'linear', function(){
  		$(this).hide();
  	});
  	$(this).css({'z-index':'0'});
  	$(this).children('h3').stop().animate({color: '#999'}, 300);

  })

  // Whenever a context navigational link is activated...
  $('#contextNav li > a:first-child').add('li.Purchase a').click(function(event){
    event.preventDefault();
    // ...stop any current context animations...
    $('#contextNav li').add('.copy').stop();
    // ...ascertain new context...
    var newContext = $(this).parents('li').attr('class');
    if(newContext === 'Purchase' && $(this).parents('div').hasClass('copy')){newContext = 'Contact'}
    // ...hide other contexts...
    $('li[class!='+newContext+'] .copy:visible').add('li[class!='+newContext+'] .copy:animated').each(function(){
      $(this).css({'overflow-x':'hidden'});
      $(this).parents('li').animate({height:24}, 750).children('a:first-child').animate({opacity:0.5}, 750);
    }).fadeOut(750, function(){
      // ...reveal new context...
      var newHeight = 47 + ($('li.'+newContext).children('.copy').height())*1;
      if(newHeight > 340) newHeight = 340;
      $('li.'+newContext).animate({height:newHeight}, 750)
        .children('a:first-child').animate({opacity:1}, 750)
        .siblings('.copy').fadeIn(750, function(){
          $(this).css({'overflow-x':'auto'});
        });
      // ...clear transitional values update page variables as to new context:
      $('#contextNav li').attr('style','');
      $('body').removeClass(contextId).addClass(newContext);
      rup('context='+contextId,'context='+newContext);
      contextId = newContext;
    })
  })

  // Same for gallery links
  $('#galleryNav a').click(function(event){
    var source = $(this);
    event.preventDefault();
    var newGallery = $(this).parents('li').attr('class');
    var oldColour = $('li.'+galleryId+' span').text();
    var newColour = $(this).siblings('span').text();
    if (newGallery != galleryId){
      $('#imageNav').fadeOut(600,function(){$(this).remove()});
      $.get('index.php', 'gallery='+newGallery, function(response){
        $('#galleryDash').append($(response).find('#imageNav'));
        $('#imageNav').hide().fadeIn(600);
        $('#imageNav li.current').css({backgroundColor: oldColour}).stop().animate({backgroundColor: newColour}, 600);
        dynamicFx();
        var firstImg = $(response).find('#imageNav li:first-child a');
        switchImg(firstImg,'leaveNav');
        $('h3 span.total').html($(response).find('#imageNav li').length);
      })
      $('#galleryNav').add('#galleryNav li').add('#gallery ul').stop().animate({borderTopColor: newColour, borderRightColor: newColour, borderBottomColor: newColour}, 600);
      $('#galleryNav a').not(this).animate({opacity:0.5});
      $(this).animate({opacity:1});
      $(source).parents('li').animate({borderRightColor: '#fff'}, 300);
      $('body').removeClass(galleryId).addClass(newGallery);
      rup('gallery='+galleryId,'gallery='+newGallery);
      galleryId = newGallery;
      colour = newColour;
      // Edit: change title to reflect new gallery
      $('title').html('Anne-Marie Carroll | Photographer | '+galleryId+' 1');
    }
  })

  // Image navigation
  $('#imageNav a').click(function(event){
    event.preventDefault();
    switchImg($(this));
  })

  $('#gallery a').add('#galleryNext a').add('#galleryPrev a').click(function(event){
    event.preventDefault();
    var totalImgs = $('#imageNav li').length;
    if(shuffle === 1){
      switchImg($('#imageNav li').eq(Math.floor(Math.random()*totalImgs)).children('a'));
    } else {
      var thisTitle = $('#gallery img').attr('alt');
      var nextImg = (thisTitle.split('photo ')[1])*1;
      if($(this).parent('li').attr('id') === 'galleryPrev') nextImg -= 2;
      if(nextImg < 0) nextImg += totalImgs;
      switchImg($('#imageNav li').eq(nextImg % totalImgs).children('a'));
    }
  })

  $('#galleryShuffle').click(function(event){
    event.preventDefault();
    shuffle = 1;
    $(this).fadeOut(600);
    $('#galleryShuffleOff').fadeIn(600);
  })

  $('#galleryShuffleOff').click(function(event){
    event.preventDefault();
    shuffle = 0;
    $(this).fadeOut(600);
    $('#galleryShuffle').fadeIn(600);
  })

  $('#galleryStart').click(function(event){
    event.preventDefault();
    slideshow('start');
    $(this).fadeOut(600);
    $('#galleryStop').fadeIn(600);
  })

  $('#galleryStop').click(function(event){
    event.preventDefault();
    slideshow('stop');
    $(this).fadeOut(600);
    $('#galleryStart').fadeIn(600);
  })

  if(callback && typeof(callback) === 'string'){
    eval(callback);
  }
}

$(document).ready(function(){
  // Tell CSS JS is active
  $('body').removeClass('unscripted');
  // Set up cool stuff
  dynamicFx();
})