$(function(){
  
  // Set up our case studies on the homepage
  if($("body").hasClass('index')) {
    $("#casestudy").casestudy({time: 800});
  }
  
  $("#casestudy_gallery ul").cycle();
  
  if(jQuery.browser.msie) {
    $("section.casestudylisting li:nth-child(3n+3)").css('margin-right','0');
    $("ul.team_members li:nth-child(5n+5)").css('margin-right','0');
  };
  
  // Form validation for our 'get in touch' page
  $("form#getintouchform").validate({
    rules: {
      'content[name]': 'required',
      'content[email]': {required: true, email: true},
      'content[phone]': {required: true},
      'content[budget]': {required: true}
    },
    success: function(label) {
      label.text("Success!").addClass("success");
    },
    invalidHandler: function(form) {
      form_error(form.currentTarget, "Please fill in the required fields.")
        },
    submitHandler: function(form) {
      if($(form).valid()) {
        $.ajax({
          url:      $(form).attr('action'),
          data:     $(form).serializeArray(),
          type:     "post",
          success: function(data) {
            if (data.errors == null) {
              $('#enquiry_form').fadeOut(function(){
                $('#enquiry_thanks').fadeIn();
              })
                /* Google Conversion Tracking */
                $('body').append($('<img></img>').attr('src','http://www.googleadservices.com/pagead/conversion/1041679550/?label=Ouh7CJSY_AEQvonb8AM&amp;guid=ON&amp;script=0'))
                  } else {
                    form_error(form, "Sorry, something went wrong. We're on it.")
                      }
          },
          error: function(data) { 
            form_error(form, "Sorry, something went wrong. We're on it.")
              }
        })
          }
      return false;
    }
  });
  
});

function form_error(form, message) {
  $(form).find('.errormessage').show().html(message)
    }
