$(document).ready(function(){
  //Add filetype icon class to a for second-class browsers
  var fileTypes = {
    zip: 'zip',
    pdf: 'pdf'
  };
  $('a').filter(function(){return this.href.match(document.domain) && this.href.lastIndexOf('.') > 0;}).each(function(){
    var hrefArray = this.href.split('.');
    var fileType = fileTypes[hrefArray[hrefArray.length - 1]];
    if (fileType) {
      $(this).addClass('icon-' + fileType);
    }
  });
  
  //Toggle abuse form for forum entries
  $('.feedback_item a.abuse-toggler').click(function(event){
    event.preventDefault();
    $(this).parents('.feedback_item').find('.comment-abuse').slideToggle();
  });

 
  //Reservartions form handling
  
  
  //Replace textefields for number with dropdowns
  var html = '<select>';
  for(var i = 0; i <= 5; i++) { html += '<option>'+i+'</option>'; }
  html += '</select>';
  $('.select-integer input[type=text]').each(function(){
    var $this = $(this);
    $(html)
      .attr('name', $this.attr('name'))
      .attr('id', $this.attr('id'))
      .val($this.val())
      .insertAfter(this);
   $this.remove();
  });
  
  //Validate the form before submission
  $('form:has(.reservations)').submit(function(e){
    var $this = $(this);
    //clear existing error message (if any)
    $this.prev('.error_message').html('<ul/>');
    /*
     * Helper function to add error message
     * @param element {selector} An element after which to insert the error message
     * @parem message {string} The error message
     */
    
    function addErrorMessage(element, message) {
      //get the div containing the errors...
      var errorDiv = $this.prev('.error_message').eq(0);
      //...or create it if it doesn't exsit
      if(!errorDiv.size()) {
        errorDiv = $('<div class="error_message"><ul/></div>').insertBefore($this);
      }
      //append the error message
      $('<li/>').appendTo($('ul', errorDiv)).text(message);
      //Add an error message next to the specified element
      $(element).siblings('div.error_message').remove().end().after('<div class="error_message">' + message  + '</div>');
    }
    
    //Validate required fields
    $('.required input, .required select', this).each(function(){
      if(!$(this).val()) {
        addErrorMessage(this, 'Veuillez entrer une valeur pour "' + $(this).siblings('label').text().replace(':','').replace('*','').trim() + '"');
      }
    });
    //Validate seats number
    var numberOfSeats = 0;
    var firstSeatsField = $('fieldset .select-integer select', this).each(function(){
      numberOfSeats += $(this).val();
    }).eq(0);
    if(numberOfSeats === 0) {
      addErrorMessage(firstSeatsField.siblings('label'), 'Veuillez entrer une valeur pour "places"');
    }
    //Returns false if there is any error message
    return $this.prev('.error_message').find('li').size() === 0;    
  }).find('.mailing input[type=checkbox][value=2]')
    .click(function(){
      //add behavior to to the "courrier" checkbox to mark address elements as required when checked
      var checkbox = $(this);
      var checked = checkbox.attr('checked');
      if(checked) {
        checkbox.parents('.mailing').siblings('.address-element').addClass('required').find('label').prepend('<sup class="req">*</sup>');
      } else {
        checkbox.parents('.mailing').siblings('.address-element').removeClass('required').find('label sup.req').remove();
      }
      
    }).end() //.mailing input[type=checkbox][value=2]
  .find('fieldset .reduction select').change(function(){
    //add behavior to mark the reduction type field required when a reduced price seats are requested
    var $this = $(this);
    $this.parent().next().toggleClass('required', $this.val());
  }).end() //fieldset .reduction select
  .find('.select-spectacle select')
    .change(function(){
      //Filter dates on spectacle selection
      $('option', this).each(function(){
        var $this = $(this);
        if($this.attr('selected')) {
          $this.data('dates').appendTo($('.select-date select'));
        } else {
          $this.data('dates').remove();
        }
      });
    }).find('option').each(function(){
      //For each spectacle option, collect the corresponding date options
      var $this = $(this);
      var value = $this.val();
      var dates = $('.select-date select option:contains(['+value+'])').each(function(){
        var $this = $(this);
        $this.text($this.text().replace('['+value+']', ''));
      });
      if(dates.size() > 0) {
        //Remove dates for this spectacle if it is not selected
        if(!$this.attr('selected')) {
          dates.remove();
        }
        //Store this spectacle date for use in the change event handler declared previously
        $this.data('dates', dates);
      } else {
        //No dates for this event, remove it from the list
        $this.remove();
      }
    }).end() //option
  .end()//.select-spectacle select 
  .find('.reduction-type select')
    .after('<label style="display:none">type de reduction</label>')
  .end();
});


