(function() {
/*** Start localized code **/

// Global variables
Global = {};
Global.SCROLL_HEIGHT = 200;

// Ran when homepage loads
function initialize() {
  // Set global variables for later use
  Global.contentLeft = $('#content_left_content');
  Global.contentRight = $('#content_right_content');

  // Store html templates
  $.get('content/project_image_template.html', function(html) {
    Global.projectImageTemplate = html;
  });

  $.get('content/scrollbar_template.html', function(html) {
    Global.scrollbarTemplate = html;
  });

  $.iLoop(pollCurrentPage);
}

function updateContentLeft(html, isUrl) {
  var content = Global.contentLeft;
  content.css('height', 0);
  content.html(html);
}

function pollCurrentPage() {
  var hash = location.hash;

  // Check if hash has changed
  if (hash !== Global.lastHash) {
    if (hash) {
      var page = hash.replace('#', '');
      if (page) {
        var parts = page.split('/');
        Global.contentRight.load('content/' + parts[0] + '.html', function() {
          processProject(parts[1]);
        })
      }
    }
    else {
      // Load content via ajax
      $.get('content/portfolio_thumbs.html', function(html) {
        updateContentLeft(html);
        initPortfolioThumbs();
      });
      Global.contentLeft.load('content/portfolio_thumbs.html', initPortfolioThumbs);
      Global.contentRight.load('content/portfolio_details.html');
    }

    Global.lastHash = hash;
  }

  if (Global.scrollbarTemplate) {
    addScrollBar(Global.contentLeft);
  }

  // Return true to keep loop going
  return true;
}

function initPortfolioThumbs() {
  $('#portfolio_thumbs li').click(function() {
    location.hash = '#' + this.id;
  });
}

function processProject(selected) {
  var rowSize = 4;
  var thumbs = $('#project_details .thumbs img');
  selected = parseInt(selected || 0);

  // Enable thumb clicking
  thumbs.each(function(idx) {
    $(this).click(function() {
      projectThumbClick(this);
    });

    // Load inital large image
    if (idx == selected) {
      projectThumbClick(this);
    }

    // Remove margin from last image in row
    if (idx % rowSize == (rowSize - 1)) {
      $(this).parent('li').css('margin-right', 0);
    }
  });

  // Enable expanding description
  $('#project_details .arrow').click(toggleProjectDesc);
}

function projectThumbClick(img) {
  var thumb = $(img);
  var src = thumb.attr('src');
  var str;

  // Need loop in case template has not loaded yet
  $.iLoop(function() {
    str = Global.projectImageTemplate;
    if (str) {
      src = src.replace('thumb', 'large');
      str = str.replace('_PROJECT_IMAGE_', src);
      updateContentLeft(str);
    }
    return !str;
  })
}

function toggleProjectDesc() {
  var arrow = $(this);
  var img = arrow.find('img');
  var src = img.attr('src');
  var desc = $('#project_details .description');
  //var maxHeight = Global.SCROLL_HEIGHT;
  var maxHeight = desc[0].scrollHeight;

  if (!arrow.data('expanded')) {
    // Expand
    img.attr('src', src.replace('down', 'up'));
    if (!arrow.data('height')) {
      // Store original height
      arrow.data('height', desc.height());
    }
    desc.animate({height: maxHeight + 'px'})
    arrow.data('expanded', true);
  }
  else {
    // Collapse
    img.attr('src', src.replace('up', 'down'));
    desc.animate({height: arrow.data('height') + 'px'}) // restore height
    arrow.data('expanded', false);
  }
}

function addScrollBar(container) {
  var buffer = 5;
  var scrollBuffer = 160;
  var maxRange = 1000;
  var viewable = $(window).height() - $('#top_header').height() - buffer;
  var box = $(container);
  var scroll = box.data('scrollbar');
  var wrapper = scroll ? scroll.parent('.scroll_bar') : null;
  var diff = box[0].scrollHeight - viewable;
  var dragging;

  if (wrapper && !wrapper.parent().length) {
    wrapper = scroll = null;
  }

  if (box.height() != viewable) {
    box.height(viewable);
  }

  if (diff > 0) {
    if (!scroll) {
      // Scrollbar doesn't exist. Create it
      wrapper = $(Global.scrollbarTemplate);
      scroll = wrapper.find('.rail');
      box.before(wrapper);
      box.data('scrollbar', scroll);

      box.scroll(function() {
        if (!dragging) {
          var ratio = 1 - box.scrollTop() / diff;
          scroll.slider('value', ratio * maxRange);
        }
      });

      scroll.height(viewable - scrollBuffer);
      scroll.slider({
          orientation: 'vertical',
          min: 0,
          max: maxRange,
          value: maxRange,
          start: function() {dragging = true},
          stop: function() {dragging = false},
          slide: function(ev, ui) {
            var ratio = 1 - (ui.value/maxRange);
            box.scrollTop(ratio * diff);
          }
        });
    }

    if (wrapper.css('display') == 'none') {
      wrapper.css('display', 'block');
    }

    if (Global.scrollDiff !== diff || scroll.height() != viewable - scrollBuffer) {
      Global.scrollDiff = diff;
      scroll.slider('disable');
      box.data('scrollbar', false);
      wrapper.remove();
    }
  }
  else if (wrapper && wrapper.css('display') != 'none') {
      wrapper.css('display', 'none');
  }
}

/* jQuery loop plugin */
jQuery.iLoop = function(fn) {
  ({
    step: fn,
    go: jQuery.fx.prototype.custom
  }).go();
}

/* Call initialize to kick off processing */
$(initialize);

/*** End localized code ***/
})();

