var currentClient = null;
var mainImages = [];
var currentCategory = 'all';
var photoContent = [];
var projectContent = []; // This holds all the project contents (images, etc) to be dynamically loaded

function addMainImage(clientid, saturated, desaturated, alt) {
  mainImages.push( {clientid: clientid,
                     saturated: saturated,
                     desaturated: desaturated} );
  $.imgpreload([desaturated, saturated], function() {
    $(function() {
      $('#client-thumb-' + clientid).mouseover(function() {
          $(this).attr('src', desaturated);
      }).mouseout(function() {
        $(this).siblings('div.caption').removeClass('caption-over');
        if( $('#client-' + clientid).is(':visible') || (currentCategory !== 'all' && !$('#client-thumb-' + clientid).hasClass(currentCategory)) ) { return; }
        $(this).attr('src', saturated);
      }).parent().click(function() {
        toggleClient(clientid);
        return false;
      });
      if( currentCategory !== 'all' && $('#client-thumb-' + clientid).hasClass(currentCategory) ) {
        $('#client-thumb-' + clientid).replaceWith($('#client-thumb-' + clientid).clone().attr('src', saturated));
      } else {
        $('#client-thumb-' + clientid).attr('src', saturated);
      }
    });
  });
}

function addProjectContent(clientid, html) {
  projectContent.push( {clientid: clientid,
                        html: html } );
}

function findProjectContent(clientid) {
  for( i = 0 ; i < projectContent.length ; i++ ) {
    if( projectContent[i].clientid == clientid ) { return projectContent[i]; }
  }
}

function addPhotoContent(clientid, photoid, title, body) {
  photoContent.push( {clientid: clientid,
                      photoid: photoid,
                      title: title,
                      body: body } );
}

function findMainImage(clientid) {
  for( i = 0 ; i < mainImages.length ; i++ ) {
    if( mainImages[i].clientid == clientid ) { return mainImages[i]; }
  }
}

function findClientPhoto(photoid) {
  for( i = 0 ; i < photoContent.length ; i++ ) {
    if( photoContent[i].photoid == photoid ) { return photoContent[i]; }
  }
}

function findPhotosForClient(clientid) {
  var photos = [];
  for( i = 0 ; i < photoContent.length ; i++ ) {
    if( photoContent[i].clientid == clientid ) { photos.push(photoContent[i]); }
  }
  return photos;
}

function toggleClient(id, callback) {
  // The next line prevents the link from being clicked when it's category is inactive
  //if( $('#client-thumb-' + id).hasClass('inactive') ) return false;
  var client = $('#client-' + id);
  if( client.is(':visible') ) {
    slideItUp(id, callback);
    currentClient = null;
  } else {
    // Only add the slider once (bx-wrapper hasn't been inserted)
    if( client.find('.bx-wrapper').length < 1 ) {
      var project = findProjectContent(id);
      client.html(project.html);
      setSizeForPhotoContent(id);
      if( $('#client-' + id).find('.gallery-images').children().length == 0 ) { return; }
      var slider = $(client.find('.gallery-images')[0]).bxSlider({
        mode: 'horizontal',
        pager: true,
        controls: false,
        onAfterSlide: function(currentSlideNumber, totalSlideQty, currentSlideHtmlObject) {
          showContentForPhoto(id, currentSlideHtmlObject.attr('id'));
        }
      });
    
      $('a.pager-link').html('&nbsp;&nbsp;');
	  
      slider.find('img').click(function() {
        slider.goToNextSlide();
      });
      
      setTimeout(function() {
        // Make sure all videos fill the bxWindow
        // Timed out to give the slider time to load and get a height
        var windowHeight = client.find('.bx-window').height();
        var iframes = client.find('iframe');
        iframes.each(function(i, iframe) {
          iframe = $(iframe);
          var paddingTop = windowHeight - iframe.height();
          iframe.parent().css({'padding-top': paddingTop, 'background': '#000000', 'height': iframe.height()});
        });
      }, 500);
    }

    if( currentClient ) {
      $('#client-thumb-' + currentClient).attr('src', findMainImage(currentClient).desaturated);
      slideItUp(currentClient,function() {
        slideItDown(id, function() {
          scrollTo(id);
        });
      });
    } else {
      slideItDown(id, function() {
        scrollTo(id);
      });
    }
    currentClient = id;
  }
  
  if( ! currentClient && $('#client-thumb-' + id).hasClass(currentCategory) ) {
    $('#client-thumb-' + id).attr('src', findMainImage(id).desaturated);
  }
}

function showContentForPhoto(clientid, photoid) {
  var photo = findClientPhoto(photoid);
  var content = '<h1>' + photo.title + '</h1>' + photo.body;
  $('#client-' + clientid + ' .photo-content').html(content);
}

function slideItDown(id, callback) {
  $('#client-' + id).fadeIn(1000,callback);
}

function slideItUp(id, callback) {
  $('#client-' + id).fadeOut('slow',callback);
}

function scrollTo(id, callback){
  // Can not use $('#client-thumb-' + id).offset().top here because jQuery returns the incorrect top on iPad
  var objectToScroll;
  if( getIEVersion() != -1 ) objectToScroll = $('body');
  else objectToScroll = $('html,body');
  objectToScroll.animate({scrollTop: document.getElementById('client-thumb-' + id).offsetTop + 100},600,'linear',callback);
}

function showOnlyCategory(category) {
  currentCategory = category;
  for( i = 0 ; i < mainImages.length ; i++ ) {
    if( category == 'all' ) {
      $('#client-thumb-' + mainImages[i].clientid).attr('src', mainImages[i].saturated);
    } else if( $('#client-thumb-' + mainImages[i].clientid).hasClass(category) ) {
      $('#client-thumb-' + mainImages[i].clientid).attr('src', mainImages[i].saturated);
    } else {
      $('#client-thumb-' + mainImages[i].clientid).attr('src', mainImages[i].desaturated);
    }
  }

  // Change the state of the subnavigation links
  $('#portfolio-' + category).siblings('span').each(function() {
    $(this).replaceWith('<a href="#' + $(this).html().toLowerCase() + '" id="portfolio-' + $(this).html().toLowerCase() + '">' + $(this).html().toUpperCase() + '</a>');
  });
  $('#portfolio-' + category).replaceWith('<span class="active" id="portfolio-' + category.toLowerCase() + '">' + category.toUpperCase() + '</span>');
}

function preShowOnlyCategory(category) {
  if( currentClient ) { toggleClient( currentClient, function () { showOnlyCategory(category); }) }
  else { showOnlyCategory(category); }
}

function setSizeForPhotoContent(clientid) {
  var photoContent = findPhotosForClient(clientid);
  var maxHeight = 0;
  var client = $('#client-' + clientid);
  for( var j = 0 ; j < photoContent.length ; j++ ) {
    var content = '<h1>' + photoContent[j].title + '</h1>' + photoContent[j].body;
    client.find('.photo-content').html(content);
    client.show();
    var contentHeight = client.find('.photo-content').height();
    client.hide();
    if( contentHeight > maxHeight ) { maxHeight = contentHeight; }
  }
  client.find('.photo-content').css('height', maxHeight + 'px');
}

$(function() {
  
  $('#portfolio-all').live('click', function() {
    preShowOnlyCategory('all');
  });
  /*
  $('#portfolio-projects').live('click', function() {
    preShowOnlyCategory('projects');
  });
  
  $('#portfolio-various').live('click', function() {
    preShowOnlyCategory('various');
  });
  */
  $('#portfolio-new').live('click', function() {
    preShowOnlyCategory('new');
  });
  
  $('.close-client').live('click', function() {
    toggleClient(currentClient);
  });
  
  $('#toggle-captions').click(function() {
    if( $('.img-container .caption').is(':visible') ) {
      $('.img-container .caption').hide();
      $('#toggle-captions').html('<img src="' + templateDir + '/images/captions-off.png" />');
    } else {
      $('.img-container .caption').show();
      $('#toggle-captions').html('<img src="' + templateDir + '/images/captions-on.png" />');
    }
  });
  
  // Check if there is a bookmarked link
  if( self.document.location.hash ) {
    showOnlyCategory(self.document.location.hash.substring(1).toLowerCase());
  }

  $.fx.prototype.curOriginal = $.fx.prototype.cur;
  $.fx.prototype.cur = function( force ) {
    if ($(this.elem).is("body") && this.prop == "scrollTop") return $(window).scrollTop();
    return this.curOriginal(force);
  }
});
