/* google analytics*/
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-11757081-1']);
  _gaq.push(['_setDomainName', '.asana.com']);
	//_gaq.push(["_setDomainName", "none"]);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
   
  })();
   
/* kissmetrics */
var _kmq = _kmq || [];
function _kms(u) { setTimeout(function() {
    var s = document.createElement('script');
    var f = document.getElementsByTagName('script')[0];
    s.type = 'text/javascript';
    s.async = true;
    s.src = u;
    f.parentNode.insertBefore(s, f);
  }, 1);
} _kms('//i.kissmetrics.com/i.js');
_kms('//doug1izaerwt3.cloudfront.net/efc20171ef3ae1d1c58259da710bad67e51b7f9a.1.js');

/* jquery extension to do better email validation */
// Extend email validation method so that it ignores whitespace
jQuery.validator.addMethod("emailButAllowTrailingWhitespace", function(value, element) {
    return (this.optional(element) || /^[^@]+@[^@]+\.[a-zA-Z]{2,}$/.test(jQuery.trim(value))) 
    // jQuery.validator.methods.email.call(this, jQuery.trim(value), element));
},"");

    
/* ui code */
$(function() {
  var signupSuccess = {
    href : "#success",
    title : "Thank You!",
    inline : true,
    width : 690,
    height : 450,
    transition : "none",
    onClosed : function() {
      $("input[name*=email]").val('');
      $("input[name*=email]").parent().find(".field-big-default").show();
      $("#home-signup-name").focus();
    }
  };

  var signupFail = {
    href : "#fail",
    title : "Thanks!",
    inline : true,
    width : 690,
    height : 450,
    transition : "none"
  };

  $.extend({
    signupQuery : {
      href : "#signup",
      title : "Sign Up for Free!",
      inline : true,
      width : 690,
      height : 450,
      transition : "none",
      onComplete : function() {
        $("#popup-signup-name").focus();
      }
    },
    resizeBg : function() {
      var windowH = $(window).height();
      var pageH = $("#page-wrap").height();
      var bgH = $(".bg").height();

      if(windowH > (pageH + 150)) {
        $("#bg-wrap").css("height", parseInt(windowH) + "px");
        $("#footer").css("height", parseInt(windowH - pageH - 1) + "px");
      }
      else {
        $("#bg-wrap").css("height", parseInt(pageH + 150) + "px");
      }
    },
    signupSubmit : function(submitData) {
      // Trim whitespace before submitting.
      submitData.name = jQuery.trim(submitData.name);
      submitData.email = jQuery.trim(submitData.email);
	  _kmq.push(['identify', submitData.email]);
	  _kmq.push(['record', "Signed Up"]);
	  _gaq.push(['_trackEvent', 'SignUp', 'Create', 'LightBox']);
      $.ajax({
        url : 'proxy.php',
        type : 'POST',
        dataType : 'json',
        data : submitData,
        timeout : 5000,
        success : function(data) {

          if(data.status.http_code == 200) {
            $.colorbox(signupSuccess);
          }
          else {
            $.colorbox(signupFail);
          }

          $.post('/log', {
            name : submitData.name,
            email : submitData.email,
            response : data.status.http_code
          });

        },
        error : function(jqXHR, textStatus, errorThrown) {

          console.log("status: " + textStatus);
          console.log("error: " + errorThrown);
          var status = (jqXHR.status != 0) ? jqXHR.status : "timeout";
          $.colorbox(signupFail);

          $.post('/log', {
            name : submitData.name,
            email : submitData.email,
            response : status
          });

        }
      });
    }
  });
  /* autocomplete disable */
  if($.browser.webkit) {
    $('input').attr('autocomplete', 'off');
  }

  $(".template-signup").colorbox($.signupQuery);

  /*$(window).load($.resizeBg);
  $(window).resize($.resizeBg);*/

  if($(".field-big").val() != "") {
    $(this).next().hide();
  }
  $(".field-big").keyup(function() {
    val = $(this).val();
    if(val == "") {
      $(this).parent().find(".field-big-default").show();
    }
    else {
      $(this).parent().find(".field-big-default").hide();
    }
  });

  $(".field-big-default").click(function() {
    $(this).prev().focus();
  });

  $("#home-login-form").validate();
  $("#popup-form").validate();

  $.extend($.validator.messages, {
    required : "",
    email : ""
  });

  $(window).load(function() {
    $(".field-big").val('');
  });

  $.extend({
    validateHome : function() {
      $(".error-container").hide();
      var name = $("#home-signup-name");
      var email = $("#home-signup-email");
      if(!$("#home-login-form").validate().form()) {
        if(name.hasClass('error')) {
          $("#home-login-error-name").show();
          name.focus();
        }
        else {
          $("#home-login-error-email").show();
          email.focus();
        }
      }
      else {
        $(".error-container").hide();
        $("#sent-address").html(email.val());
        var submitData;
        if(name.val() == "forcefail") {
          console.log("Force fail!");
          submitData = { }
        }
        else {
          submitData = {
            name : name.val(),
            email : email.val()
          }
        }
        $.signupSubmit(submitData);
      }
    },
    validatePopup : function() {
      $(".error-container").hide();
      var name = $("#popup-signup-name");
      var email = $("#popup-signup-email");
      if(!$("#popup-form").validate().form()) {
        if(name.hasClass('error')) {
          $("#popup-error-name").show();
          name.focus();
        }
        else {
          $("#popup-error-email").show();
          email.focus();
        }
      }
      else {
        $(".error-container").hide();
        $("#sent-address").html(email.val());
        var submitData;
        $.signupSubmit({
          name : name.val(),
          email : email.val()
        });
      }
    },
    signupWithGoogle: function() {
      BrowserGoogleAuth.start(function(auth_response) {
        if (auth_response === null) {
          // The user must have denied access from google, so do nothing.
          return;
        }
        var form = document.createElement("form");
        form.setAttribute("method", "POST");
        form.setAttribute("action", "https://app.asana.com/-/signup");
        var addField = function(name, value) {
          var hiddenField = document.createElement("input");
          hiddenField.setAttribute("type", "hidden");
          hiddenField.setAttribute("name", name);
          hiddenField.setAttribute("value", value);
          form.appendChild(hiddenField);
        }
        addField("src", "simple-signup");
        addField("i", "google");
        addField("auth", auth_response.access_token);

        document.body.appendChild(form);
        form.submit();
      });
      return false;
    }
  });

  $("#home-google-auth").click($.signupWithGoogle);
  $("#popup-signup-google-auth").click($.signupWithGoogle);

  $("#home-login-form").keydown(function(e) {
    if(e.keyCode == 13) {
      $.validateHome();
    }
  });
  $("#home-submit").click($.validateHome);

  $("#popup-form").keydown(function(e) {
    if(e.keyCode == 13) {
      $.validatePopup();
    }
  });
  $("#popup-submit").click($.validatePopup);

});

