/*


Dynamic Application of Functions to DOM
*/
var _debugMode = false;
document.observe('dom:loaded', init);
Event.observe(window, 'load', initAfterImages);
document.observe('window:loaded', window_load);


function init () {
  applyPngHack();
    
  new AttachmentFuImageSwap('large-image-target', 'thumbs-container-scroll');
  document.observe('ImageSwap:image_change', updatePicTitle);
}

function initAfterImages () {
  document.fire('window:loaded');
}

function window_load() {
  var adjust = $('adjustWidth')
  if (adjust) adjust.adjustWidth();
  
  checkHeight();
}

function checkHeight() {
  var bodyBgHeight = 735;
  var footYDiff = $('foot').cumulativeOffset().top - bodyBgHeight;
  if (footYDiff < 0) 
    $('text-content').setStyle({
      height: ($('text-content').getHeight() + Math.abs(footYDiff)) + 'px'
    });
}

function updatePicTitle(e) {
  var altText = $('large-image-target').readAttribute('alt');
  if (altText.strip() == '') return;
  $('alt-text-target').update(altText);
  checkHeight();
}

function applyPngHack() {
  $$('#featured-image').flatten().compact().invoke('pngHack');
}

Element.addMethods({
  adjustWidth: function(el) {
    var totalWidth = el.childElements().inject(0, function(acc, el) {
      return acc + el.getWidth() + 
        Number(el.getStyle('margin-right').gsub('px', '')) +
        Number(el.getStyle('margin-left').gsub('px', ''));
    });
    el.setStyle({width: totalWidth + 'px'});
  }
});