$(function() {
  function lookup() {
    var postcode = $('input[name="postcode"]').val();
    // Don't bother making an API call unless we have at least 5 characters, not including spaces.
    // This should mean we only ever make a maximum of two API calls before we get a valid one.
    if (postcode.replace(' ', '').length >= 5) {
      var url = 'http://www.theyworkforyou.com/api/getMP?key=GgBTgoEaZKA5GEonR5ErroqF&always_return=true&callback=?&postcode=' + postcode;
      $('#postcode-spinner').show();
      $.getJSON(url, function(mp) {
        if (!mp.error) {
          $('[name="mp"]').val(mp.member_id);
          $('#mp_name').text(mp.first_name + ' ' + mp.last_name + ' (MP for ' + mp.constituency + ')').fadeIn();
          $('#postcode-spinner').hide();
          $('input[name="postcode"]').data('error', false);
        } else {
          
          $('input[name="postcode"]').addClass('error');
          $('input[name="postcode"]').data('error', true);
        }
      })
    }
  }

  $('input[name="postcode"]').blur(lookup);
  
  $('input[name="name"]').blur(function() {
    $('#your_name').text($(this).val()).fadeIn();
  });
  
  // If form has been returned a second time (eg. due to validation error, lookup immediately)
  if ($('input[name="postcode"]').val() != '' && $('input[name="postcode"]').val() != $('input[name="postcode"]').attr('placeholder')) {
    lookup();
  }
  
  
  
  // If no HTML5 placeholder support, implement by hand
  if (!Modernizr.input.placeholder){  
    $('input[type="text"]').each(function() {
      $(this).val($(this).attr('placeholder'));
    });
    $('input[type="text"]').focus(function() {
      // On focus, clear the initial value
      if ($(this).val() == $(this).attr('placeholder')) {
        $(this).val('');
      }
    }).blur(function() { 
      // On blur, restore initial value if input is empty
      if ($(this).val() == '') {
        $(this).val($(this).attr('placeholder'));
      }
    });
  }
  
  $('input[type="submit"]').css('position', 'absolute').css('left', '-9999px').width(0); // hide the no-js backup submit button
  $('#petition').submit(function() {
    var all_fields_complete = true;
    $('input[type="text"]').each(function() {
      if ($(this).val() == '' || $(this).val() == $(this).attr('placeholder')) {
        all_fields_complete = false;
        $(this).addClass('error').addClass('red');
        var type = $(this).attr('name');
        $(this).val('Please enter your ' + type);
        $(this).data('error', true);
        $(this).focus(function() {
          $(this).val('').removeClass('red');
          $(this).data('error', false);
        })
      } else if ($(this).data('error')) {
        all_fields_complete = false;
      } else {
        $(this).removeClass('error');
      }
      ;
    });
    return all_fields_complete
  });
    $('#submit').show().click(function () {
        $('#petition').submit();
    })
})

