function setLanguageCookie(value) {
  var cookie = "lang=" + encodeURIComponent(value);
  cookie += ";max-age=" + (365*60*60*24);
  cookie += ";path=/";
  document.cookie = cookie;
};

function classChange(styleChange,item) {
  item.className = styleChange;
}

(function($) {
  $(document).ready(function(){

    var emailprompt = 'email';
    $('#collectorformemail').val(emailprompt);
    // clear email on focus
    $('#collectorformemail').focus(function(){
      if ( $(this).val()==emailprompt ){
        $(this).val('');
      }
    });
    // if email is empty on bllur restore previous text
    $('#collectorformemail').blur(function(){
      if($(this).val()==''){
        $(this).val(emailprompt);
      }
    });

    $('#collectorform').submit(function(event){
      event.preventDefault();
      var $this = $(this);
      // a bit of validation
      var emailTest = new RegExp('^\\w[-.\\w]+\\@[-a-zA-Z0-9]+(\\.[-a-zA-Z0-9]+)*\\.[a-zA-Z]{2,}$');
      if ( !emailTest.test($('#collectorformemail').val()) ) {
        alert('Invalid email address');
        return false;
      };
      $('#collectormessage').text("[submitting...]").show();
      var dataToSend = $this.serialize();
      $.ajax({
        url: '/collector', 
        data: dataToSend,
        type: 'GET',
        dataType: 'text',
        error: function(xhr,textStatus,errorThrown) {
          alert('unexpected error: ' + xhr.status);
        },
        success: function (got,textStatus,xhr) {
          // the result looks like a query string
          var gotParts = {};
          jQuery.each(got.split(/[&]/), function(){
            var key = this.split('=')[0];
            var val = this.split('=')[1];
            if (!key) return;            
            gotParts[key]=val;
          });
          // this is very hacky but generally if we get a 200 it is either success or a duplicate (I think)
          if ( gotParts['duplicate'] ) {
            alert('you are already on the mailing list');
          }
          else {
            alert('You will receive a confirmation email. Click on the relevant link in that email to complete the mailing-list signup.');
          };
        },
        complete: function () {
          $('#collectormessage').fadeOut(500);
        },
      });
    });

  });
})(jQuery);

