/** =ajax/validation
************************************************************/
$(document).ready(function() {
	var $jsForm =  $('form.validate');
	if (!$('form.validate')) { return; }
	var submitOptions = {
	  clearForm: false,
	  beforeSubmit: function() {
	    $('<div class="loading">Sending<img src="/assets/styles/images/spinners/progress-bar.gif" alt="" /></div>').appendTo('.content-main .actions:first');
	    $('<div class="overlay"></div>').css({opacity: '.4'}).appendTo($jsForm);
	  },
	  success: function(responseText) {
      var response = $('<div>' + responseText + '</div>').find('.content-main:first .main:first').html();
      if (!$.trim(response)) {
        if (!$('.error-report').length) {
          $('<div class="error-report"></div>').appendTo('.actions');
        }
        response = '<ul>' + $('<div>' + responseText + '</div>').find('#content ul').html() + '</ul>';
        $('.error-report').html(response);
        $('.loading').remove();
      } else {
  	    $jsForm.fadeTo(400, 0.01, function() {
  				$jsForm.slideUp(600, function() {
  		      $('.loading').insertAfter(this).html(response).removeClass('loading');
  				});
      	});        
      }

	    $('div.overlay').fadeOut(100, function() {
	      $(this).remove();
	    });
	  }
	};
	$jsForm.tinyvalidate({
	  submitOverride: function() {
	    $jsForm.ajaxSubmit(submitOptions);
	  },
	  summary: {
			insertTo: '.content-main .actions:first',
			insertType: 'after',
	    wrapper: '<div class="error-summary"></div>',
	    preMessage: 'There was a problem processing your request.<br>Please correct the {num} highlighted {field|fields} and try again.',
	  	lineItems: null
		}
	});

});
$(document).ready(function() {
  
  /** =expandable textareas
  ************************************************************/
  if (typeof $.fn.expandable !== 'undefined'){
  	$('textarea').expandable({
  	  init: true,
  	  duration: 100,
  	  interval: 400,
  	  by: 1
  	});
  };
  
  /** =handle country outside USA
  ************************************************************/
  
  var $country = $('#country'),
      $countryParent = $country.parent(),
      $cityState = $('#citystate');
      
  $country.change(function() {

    $countryParent.next('p').remove();
    if ($country.val() != 'United States') {
      $countryParent.after('<p>Please enter your complete address in the Address field below.</p>');
      $cityState.slideUp('fast', function() {
        $cityState.find(':input').each(function() {
          $(this).data('val', this.value);
          this.value = 'NA';
        });
      });
    } else {
      $cityState
        .find(':input').each(function(index) {
          this.value = $(this).data('val') == 'NA' ? '' : $(this).data('val') || '';
        })
        .end()
      .slideDown('fast');
    }
  }).trigger('change');
});
