jQuery.noConflict();
jQuery(function() {
  if (cookied_dates = jQuery.evalJSON(jQuery.cookie("dates"))){
    jQuery.each(cookied_dates, function(date) {
      jQuery.each(this, function(day_part, value) {
        if(value == 'on'){
          var label = jQuery("label[for=reservations_" + date + "_" + day_part +"]");
          label.addClass('active');
          var checkbox = label.children("input[type=checkbox]").first();
          checkbox.attr('checked', true);
        }
      }); 
    });
  }
  else {
    var cookied_dates = {};
  }
  
  jQuery(".calendar label").click(function() {
    var $this = jQuery(this);
    var checkbox = $this.children("input[type=checkbox]").first();
    if (checkbox.is(':checked')){
      $this.addClass('active');
      date = $this.attr('for').split('_').slice(1, -1).join('_');
      day_part = $this.attr('for').split('_').reverse()[0];
      if(cookied_dates[date]){
        cookied_dates[date][day_part] = "on";
      }
      else{
        cookied_dates[date] = {};
        cookied_dates[date][day_part] = "on";
      }
    }
    else{
      $this.removeClass('active');
      date = $this.attr('for').split('_').slice(1, -1).join('_');
      day_part = $this.attr('for').split('_').reverse()[0];
      if(cookied_dates[date]){
        cookied_dates[date][day_part] = "off";
      }
    }
    jQuery.cookie("dates", jQuery.toJSON(cookied_dates), { path: '/' });
  });

  if (jQuery("#reservation_calendar").length > 0){
    // before submitting away from calendar, update hidden inputs of the form with those from the session cookie
    jQuery("#verzenden").click(function(){
      jQuery("#reservation_calendar input[type=checkbox]").remove();
      var cookied_dates = jQuery.cookie("dates");
      cookied_dates = jQuery.evalJSON(cookied_dates);
      jQuery.each(cookied_dates, function(date) {
        jQuery.each(this, function(day_part, value) {
          if(value == "on"){
            var html = "<input type='hidden' name='reservations[" + date + "][" + day_part +"]' value='on' />";
            jQuery("#reservation_calendar form").append(jQuery(html));
          }
        });
      });
    })
  }
  
  jQuery("#reservation_form").validate({
    errorPlacement: function(error, element) {
      if ( element.is(":radio") )
        error.appendTo( element.parent() );
      else if ( element.is(":checkbox") )
        error.appendTo ( element.next() );
      else
        error.appendTo( element.parent() );
    }
  });
  
});
