$(document).ready(function() {
  // Ajax form submission
  var $ajaxForm =  $('form.validate');
  var submitOptions = {
    clearForm: true,
    beforeSubmit: function() {
      $('<div class="loading">Processing<img src="/assets/styles/images/ajax-loader.gif" alt="" /></div>').appendTo('div.actions');
      $('<div class="overlay"></div>').css({opacity: '.4'}).appendTo($ajaxForm);
    },
    success: function(responseText) {
      $ajaxForm.slideUp(200, function() {
        var response = $('<div>' + responseText + '</div>').find('p:first').html();
        $('.loading').insertAfter(this).addClass('box success single-line').html(response).removeClass('loading');
      });
      $('div.overlay').fadeOut(100, function() {
        $(this).remove();
      });
    }
  };
  $ajaxForm.tinyvalidate({
    submitOverride: function() {
      $ajaxForm.ajaxSubmit(submitOptions);
    },
    summary: {
      wrapper: '<div class="error-summary error box"></div>',
      preMessage: '<p>There was a problem processing your request. <br>Please correct the {num} highlighted {field|fields} and try again.</p><ul>',
      postMessage: '</ul>'
    }
  });

  // Autogrowing textareas
    $('textarea').expandable({
      init: true,
      duration: 100,
      interval: 400,
      by: 1
    });

  // datepicker
  if (typeof $.fn.datepicker !== 'undefined') {

    $.unselectableDates = $.unselectableDates || [];
    var $visitDatePicker = $('#visit_form #date').before('<div style="clear:both;"></div>').prev();

    $visitDatePicker.datepicker({
      showOn: "both",
      altField: '#date',
      buttonImage: '/assets/styles/images/icons/datepicker.png',
      minDate: '+0',
      beforeShowDay: function(date) {
        var dow = date.getDay(),
            thisDate = '' + (date.getMonth()+1) + '-' + date.getDate()  + '-' + date.getFullYear(),
            selectable = ((dow + 6) % 7 >= 5) || $.unselectableDates[ thisDate ] ? false : true;

        return [selectable, '', ''];
      },
      onClose: function() {
        $(this).focus();
      }
    });
    $visitDatePicker.next().val('');

  }
});
