/*


Dynamic Application of Functions to DOM
*/
document.observe('dom:loaded', init);
Event.observe(window, 'load', initAfterImages);

// Fires an event after the window has stopped scrolling for a second
var scrollStoppedID = '';
Event.observe(window, 'scroll', function(e) {
  window.clearTimeout(scrollStoppedID);
  scrollStoppedID = (function() {document.fire('scroll:stopped')}).delay(.5);
});

new SlideShow('listOfImages', {
  pauseOnMouseover: false,
  crossFade: true
});

function init () {
  //check to show and hide the cocologo based on homepage
  if (window.location.pathname == '/') $('cocoDesign').show();
  
  //the following is needed to get ie* to center li's when the dimensions are unknown
  if (Prototype.Browser.IE) $('footer-features').wrap('del', {'style': 'display: inline-block; text-decoration: none; margin: 0 0 20px 0'});
  
  //Handles "sticky" side column
  if ($('movement-switch')) {
    [$('primary'), $('secondary')].equalizeHeights();
    $('glossy-container').makeStickyContainer();
  }
  
  //fake min-height in ie6
  var glossyTopEl = $('glossy-top');
  if (Prototype.Browser.IE && !window.XMLHttpRequest && glossyTopEl)
    if (glossyTopEl.getHeight() < 140) glossyTopEl.setStyle({height: '140px'});
    
  //handles homepage popup
  var triptych = $('boat-triptych');
  if (triptych) {
    var popout = $('popout');
    var appearEffect;
    var animating = false;
    triptych.observe('mouseover', function(e) {
      popout.down('#popout-content').update(e.element().innerHTML);
      if (!popout.visible()) {
        // Prototype.Browser.IE ? popout.show() : popout.appear({duration: .4});
        appearEffect = new Effect.Appear(popout, {
          duration: .4,
          delay: .6,
          beforeStart: function() {
            // ie7 can't handle animating transparent pngs
            if (Prototype.Browser.IE && window.XMLHttpRequest) 
              popout.setStyle({backgroundColor: '#999999'});
          }, 
          beforeUpdate: function() { animating = true; },
          afterFinish: function() {
            if (Prototype.Browser.IE && window.XMLHttpRequest)
             popout.setStyle({backgroundColor: 'transparent'});
          } 
        });
      }
      popout.clonePosition(e.target, {setWidth: false, setHeight: false, setTop: false, offsetLeft: -75}); 
    });
    popout.down('a').observe('click', function(e) {
      e.stop();
      e.target.blur();
      Prototype.Browser.IE ? popout.hide() : popout.fade();
      animating = false;
    });
    $$('#boat-triptych > div').invoke('observe', 'mouseout', function(e){
      if (!animating) appearEffect.cancel();
    });
  }
  
  //handles rollover of boat thumbnails on search
  setupPopup();
  
  //Handles modal window
  setupModal()
  
  //handles vertical carousel
  if ($('vertical_carousel')) {
    new UI.Carousel("vertical_carousel", {direction: 'vertical'});
    new AttachmentFuImageSwap(
      'image-target', 
      'swap-container', 
      { imageThumbString: 'small', imageLargeString: 'normal', fadeDuration: .25, appearDuration: .25});
  }
  
  //handles hiding and showing the features of a boat
  setupAdditionalFeaturesInterface();
  
  //handles the updating of links based on scroll position
  // setupStickyLinks();

  //handle print page link
  var action_links = $('action-links');
  if (action_links) {
    action_links.select('.print').first().observe('click', function(e) {
      if (e.element().readAttribute('href') != '#') return
      e.stop();
      window.print();
    })
  }

  var broker_login = $('login-action');
  if (broker_login) {
    var forms = $$('#login-container form');
    broker_login.observe('click', function(e) {
      e.stop();
      e.element().blur();
      new Effect.Fade(broker_login, { queue: { position: 'end', scope: 'logineffect', limit: 2 } });
      new Effect.Appear('login-container', { queue: { position: 'end', scope: 'logineffect', limit: 2 } });
    });
    $('forgot-password').observe('click', function(e){
      e.stop();
      e.element().blur();
      new Effect.Fade(forms[0], { queue: { position: 'end', scope: 'logineffect', limit: 2} });
      new Effect.Appear(forms[1], { queue: { position: 'end', scope: 'logineffect', limit: 2} });
    });
  }

  if ($('reset')) { 
    $('reset').observe('click', function(e) {
      window.location = '/vessels';
    });
  }
}

function initAfterImages () {
  document.fire('window:loaded')
}

function setupAdditionalFeaturesInterface() {
  if ($('boat-features')) {
    //set positions of headers correctly
    $$('#boat-features > h1').inject(0, function(acc, el) {
      acc += 10;
      el.setStyle({left: acc + 'px'});
      return acc + el.getWidth();
    });

    $('boat-features').observe('click', function(e){
      if (!e.element().match('a') || e.element().up('.scroll-content')) return;
      e.stop();
      e.element().blur();
      if (e.element().up('.sidebar')) {
        var clickedNum = Number(e.element().classNames());
        var container = e.element().up('.features-content');
        e.element().up('.sidebar').select('.active')[0].removeClassName('active');
        container.select('.text-content').invoke('hide')[clickedNum].show();
      }
      else {
        var show_id = $A(e.element().up().classNames()).first();
        $$('#boat-features > h1.active')[0].removeClassName('active');
        $$('.features-content').invoke('hide');
        $(show_id).show();
      }
      e.element().up().addClassName('active');
    });
  }
}

function setupModal() {
  var backdrop = $('backdrop');
  if (backdrop) {
    $$('.show-modal').invoke('observe', 'click', show_modal); 
    $('backdrop').observe('click', function(e) {
      $('backdrop').hide();
      $('request-info-modal').hide();
    });
    $('hide-modal').observe('click', function(e) {
      e.stop();
      $('backdrop').hide();
      $('request-info-modal').hide();
    });
    
    //validate form
    var form = $('modal-shell').down('form');
    form.down('input[type="submit"]').observe('click', function(e) {
      e.stop();
      var errors = form.getInputs('text').slice(0,2).any(function(el) {
        return $F(el).strip().empty();
      });
      if (errors) {
        $('form-errors').highlight({endcolor: '#437574', restorecolor: '#437574'}).update('Please fill out the required fields.')
      }
      else form.submit();
    });
  }
  function show_modal(e) {
    e.stop();
    $('backdrop').show();
    $('request-info-modal').show();
    if (Prototype.Browser.IE && !window.XMLHttpRequest) window.scrollTo(0, 0);
  };
}

function setupPopup() {
  var largePopup = $('large-popup');
  if (!largePopup) return;
  
  lpDescendants = [largePopup, largePopup.descendants()].flatten();
  $('search-results').observe('mouseover', function(e) {
    var target = $(e.target);
    if (!target.match('img')) return;
    if (target.hasClassName('not-available')) return;
    if (!largePopup.visible()) {
      if (!Prototype.Browser.IE)
        largePopup.appear({duration: .4});
      //ie can't handle fading transparent pngs
      else largePopup.show();
    }
    //load image and link into popup
    largePopup.down().writeAttribute({'href': target.up().readAttribute('href')}).down('img').src = target.src.gsub('small', 'normal');
    
    largePopup.clonePosition(target, {setWidth: false, setHeight: false, setLeft: false, offsetTop: -50});
  }).observe('mouseout', function(e) {
    if (!$(e.target).match('img')) return;
    if (lpDescendants.any(function(n) {return e.relatedTarget == n})) return;
    largePopup.hide();
    largePopup.down().down('img').hide();
  });
  largePopup.observe('mouseout', function(e) {
    if (lpDescendants.any(function(n) {return e.relatedTarget == n}) || e.relatedTarget.match('img')) return;
    largePopup.hide();
    largePopup.down().down('img').hide();
    });
  
  //make sure the image in the popup is listening for the load event
  largePopup.down().down('img').observe('load', function(e) {
    $(e.target).appear({delay: .5,  queue: {scope: 'popupimage', limit: 1} });
  })
}

function setupStickyLinks() {
  var sticky_quick_links = $$('#sticky-quick-links a');
  if (sticky_quick_links.length == 0) return;
  sticky_quick_links.first().addClassName('active');
  var anchorTargetsOffset = sticky_quick_links.collect(function (el) {
    return {element: el, offset: $(el.readAttribute('href').slice(1)).cumulativeOffset().top}
  });
  
  document.observe('scroll:stopped', function(e) {
    $$('#sticky-quick-links .active').first().removeClassName('active');
    closestAnchor(anchorTargetsOffset, document.viewport.getScrollOffsets().top).addClassName('active');
    // console.log(closestAnchor(anchorTargetsOffset, document.viewport.getScrollOffsets().top));
  });
  
}

function closestAnchor(anchorOffsets, value) {
  var low = 0;
  var high = anchorOffsets.length - 1;
  var mid = 0;
  while (low < high) {
    mid = ((low + high)/2).floor();
    if (anchorOffsets[mid].offset < value)
      low = mid + 1; 
    else
      //can't be high = mid-1: here A[mid] >= value,
      //so high can't be < mid if A[mid] == value
      high = mid;
  }
  if (low == 0) return anchorOffsets[0].element;
  else return anchorOffsets[low-1].element;
}