function closeFooter() {
  if (!((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPad/i)))) {
    $("footer").animate({height: 30}, 840, 'easeOutExpo',function() {
      $(this).removeClass("open")
    });
  }
} 

$(function () {
  
  /* slideshow */
  $(".slideshow").each(function () {
    var that = this;
    var cap = $("li.current img", that).attr("alt");
    $(".caption", that).html(cap);
    var count = $(".slides ul li", that).length;
    var i, ar = [];
    for (i = 1; i <= count; i++) {
      ar.push("." + i);
    }
    $(".slides", that).jCarouselLite({
      btnPrev: $(".prev-slide", that),
      btnNext: $(".next-slide", that),
      btnGo: ar,
      easing: "easeOutExpo",
      afterEnd: function (a, to, btnGo) {
        var cap = $("li.current img", that).attr("alt");
        $(".caption", that).html(cap);
        if (btnGo.length <= to) {
          to = 0;
        }
        $(".circle-nav a", that).removeClass("current");
        $(btnGo[to], that).addClass("current");
      }
    });
  });
  $(".slides").hover(function () {
    $(".arrow").fadeIn(300);
  }, function () {
    $(".arrow").fadeOut(300);
  });
  $(".circle-nav a").click(function (e) {
    e.preventDefault();
  }); 
  
  /* focus + blur treatment on input boxes */
  $.fn.focusAndBlur = function() {
    $.each(this, function(index, target) {
      enable($(target));
    });
    function enable(target) {
      var initVal = target.val();
      target.focus(
      function() {
        if (target.val() === initVal) {
          $(this).val("");
        }
      }).blur(function() {
        if (!$(this).val()) {
          $(this).val(initVal);
        }
      });
    };
  };
  $("input:text, input:password").focusAndBlur();

  /* footer drawer */
  $("footer nav").click(function () {
    if (!((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPad/i)))) {
      if ($(this).parent().hasClass("open")) {
        closeFooter();
      } else {
        $(this).parent().addClass("open");
        $("footer").animate({
          height: 384
        }, 840, 'easeOutExpo');
      }
    }
  });
  
  $(".section, #primary").click(function () {
    closeFooter();
  });

  function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
  };

/* footer login */
  $("#loginButton").click(function () {
	$('#loginFailed').hide();
	$('#loginFormWrapper').append('<div id="loader"></div>');
    $.post("xmlrpc-proxy.html", $("#loginForm").serialize(), function (data) {
      $(data).find('boolean:first').each(function () {
        if ($(this).text() == "1") {
          $("#loginForm").submit();
        } else {
		  $('#loginFailed').show();
		  $('#loader').remove();
        }
      });
    });
    return false;
  });

  $("#apply").submit(function () {
    //Validation
    var valid = true;
    var email = $('#apply input[name=email_address]').val();
	$('#apply input').removeClass('error');
	
    if ($('#apply input[name=first_name]').val().length == 0 || $('#apply input[name=first_name]').val().toLowerCase() == 'first name') {
      $('#apply input[name=first_name]').addClass('error');
    }
	if ($('#apply input[name=last_name]').val().length == 0 || $('#apply input[name=last_name]').val().toLowerCase() == 'last name') {
      $('#apply input[name=last_name]').addClass('error');
    }
	if ($('#apply input[name=company_name]').val().length == 0 || $('#apply input[name=company_name]').val().toLowerCase() == 'what you do') {
      $('#apply input[name=company_name]').addClass('error');
    }
	if (email.length == 0 || email.toLowerCase() == 'email' || !isValidEmailAddress(email)) {
      $('#apply input[name=email_address]').addClass('error');
    }
	
	valid = !$('#apply input').hasClass('error');
	
    if (valid) {
      var dataString = $("#apply").serialize().replace('Referred+by', '');
      $.ajax({
        type: "POST",
        url: "http://members.grindspaces.com/grind-code/index.php/admin/applicantmanagement/insertApplicantJsonP",
        data: dataString,
        dataType: "jsonp",
        success: function (returnData) {
          if (returnData == null) {
            alert("Failed to send. Please try again.")
          } else if (returnData.success == 0 && returnData.reason == 'EMAILNOTUNIQUE') {
            alert("The email address you have entered is already being used by another Grind member. Please try again.");
            $('#apply input[name=email_address]').addClass('error');
          } else if (returnData.success == 1) {
            $('#applicant-name').html($('#apply input[name=first_name]').val())
            $('#apply-form').fadeOut(1000);
            $('#apply-form-success').fadeIn(1000);
          } else {
            alert("Failed to send. Please try again.");
          }
        },
        error: function (jqXHR, textStatus, errorThrown) {
          alert("Failed to send. Please try again. " + textStatus)
        }
      });
    }
    return false;
  });
});
