$(function(){

  $('.slideshow').each(function(){
    var id = parseInt(this.id.match(/\d+/)[0]);
    var gallery = new GalleryController({
      el: this,
      id: id,
      data: window['data_objects_galleries_'+id],
      width: $(this).width(),
      height: $(this).height(),
      slideShow: true
    });
    $(this).append(gallery.view.render())
  });

  $("a[rel^='prettyPhoto']").prettyPhoto({animationSpeed:'normal'});

  function onContactFormLoaded(html){
    var contact = $(html);

    contact.find('label[for=id_message]').hide();
    var textarea = contact.find('textarea');
    if(textarea.length){
      if(textarea.text() == ''){
        textarea.text('Your message...');
        textarea.focus(function(){
          textarea.text('');
        })
      }
    } else {
      // must have submitted the form successfully
      setTimeout(function(){
        contact.slideUp('slow', function(){
          contact.remove();
        })
      }, 2000)
    }

    var existingForm = $('#contact-form');

    if(existingForm.length){
      existingForm.replaceWith(contact)
    } else {
      contact.hide()
      $('#header-contact').append(contact);
      contact.slideDown('slow');
    }
    contact.find('form').submit(function(){
      $.post(
        '/contact/',
        $(this).serialize(),
        onContactFormLoaded,
        'html'
      )
      return false;
    })
  }

  $('#contact-form-button').click(function(){
    if($('#contact-form').length){
      $('#contact-form').slideToggle('slow');
    } else {
      $.get(
        '/contact/',
        {},
        onContactFormLoaded,
        'html'
      );
    }
    return false
  })
  
  $('#quote .quote').each(function(){
    $(this).css('top', $(this).position().top);
  });
  
  $('#quote .quote').css('position', 'absolute');
  
  
  var i = 0;
  var pane = $('#quote .pane');
  var quoteScrollIntervalID;
  
  function quoteScrollInc(){
    pane.css('top', -i);
    if(i % 10 == 0){
      var first = $('#quote .quote:first-child');
      if(first.position().top + first.height() < i){
        var last = $('#quote .quote:last-child');
        first
          .css('top', last.position().top + last.outerHeight())
          .appendTo(pane);
      }
    }
    i ++;
  }
  
  function startScroll(){
    if(!quoteScrollIntervalID)
      quoteScrollIntervalID  = setInterval(quoteScrollInc, 60);
  }
  
  function stopScroll(){
    clearInterval(quoteScrollIntervalID);
    quoteScrollIntervalID = null;
  }
  
  $(pane).mouseenter(stopScroll).mouseleave(startScroll);
  
  startScroll();
  
  
  
})

