(function($) {
  function setSurveyedCookie() {
    var expireAfter = 30, // 30 days
        expirationDate = new Date();
    expirationDate.setDate(expirationDate.getDate() + expireAfter);
    document.cookie = "surveyed=true;expires=" + expirationDate.toGMTString() + ";path=/";
  }

  function hasBeenSurveyed() {
    var nameEQ = "surveyed=";
    var ca = document.cookie.split(';');
    for(var i=0; i < ca.length; i++) {
      var c = ca[i];

      while (c.charAt(0)==' ') {
        c = c.substring(1,c.length);
      }

      if (c.indexOf(nameEQ) == 0) {
        if (c.substring(nameEQ.length,c.length) == "true") {
          return true;
        }
      }
    }
    return false;
  }

  $(function() {
    if ($("form.fsForm").size() > 0) {
      // form page
      if (hasBeenSurveyed()) {
        // redirect to downloads page
        window.location = "/index.php/downloads/";
        return;
      }
    } else {
      // downloads page
      if (window.location.search.match(/surveyed=true/) || hasBeenSurveyed()) {
        // remember the surveyed user
        setSurveyedCookie();
      } else {
        // redirect back to the form
        window.location = "/index.php/download-the-guide/";
        return;
      }
    }
  });
})(jQuery);

