$(document).ready(function(){
  $('#areacode').change(function(){
    $('#mobilenumber').focus().select();
  });

  function expandFieldset(fieldset) {
    // Don't animate multiple times
    if(!fieldset.animating) {
      fieldset.animating = true;
      toggleFieldset(fieldset);
    }
  }

  // Expand the contact details fieldset as soon
  // as we've filled in all the service details
  function expandContactDetailsFieldset() {
    if($('#mnp-contactdetails').hasClass('collapsed')
       && $('#areacode')[0].selectedIndex>0
       && $('#mobilenumber').val().length
       && $('#provider')[0].selectedIndex>0
       && $('#service')[0].selectedIndex>0) {
      expandFieldset($('#mnp-contactdetails')[0]);
    }
  }
  $('#areacode,#mobilenumber,#provider,#service')
    .change(expandContactDetailsFieldset);
  $('#mobilenumber')
    .keydown(expandContactDetailsFieldset);

  // Expand the security & privacy info fieldset as
  // soon as we've filled in all the contact details
  function expandSecurityAndPrivacyFieldset() {
    if($('#mnp-securityinfo').hasClass('collapsed')
       && $('#title')[0].selectedIndex>0
       && $('#firstname').val().length
       && $('#surname').val().length
       && $('#address1').val().length
       && $('#address2').val().length
       && $('#parish').val().length
       && $('#postcode').val().length
       && $('#daytimephone').val().length
       && $('#email').val().length) {
      expandFieldset($('#mnp-securityinfo')[0]);
    }
  }
  $('#title,#firstname,#surname,#address1,#address2,#parish,#postcode,#daytimephone,#email')
    .change(expandSecurityAndPrivacyFieldset);
  $('#firstname,#surname,#address1,#address2,#parish,#postcode,#daytimephone,#email')
    .keydown(expandSecurityAndPrivacyFieldset);

  // Expand the declaration fieldset as soon as
  // we've filled in all the contact details
  function expandDeclarationFieldset() {
    if($('#mnp-declaration').hasClass('collapsed')
       && $('#password').val().length
       && $('#confirmpassword').val().length
       && $('#pin').val().length
       && $('#confirmpin').val().length
       && $('#question')[0].selectedIndex>0
       && $('#answer').val().length) {
      expandFieldset($('#mnp-declaration')[0]);
    }
  }
  $('#password,#confirmpassword,#pin,#confirmpin,#question,#answer')
    .change(expandDeclarationFieldset);
  $('#password,#confirmpassword,#pin,#confirmpin,#answer')
    .keydown(expandDeclarationFieldset);

  // Validate the input on form submission
  $(document.theForm).submit(function(){
    var errors = doValidation({
      areacode: $('#areacode').val(),
      mobilenumber: $('#mobilenumber').val(),
      provider: $('#provider').val(),
      service: $('#service').val(),
      title: $('#title').val(),
      firstname: $('#firstname').val(),
      surname: $('#surname').val(),
      address1: $('#address1').val(),
      parish: $('#parish').val(),
      postcode: $('#postcode').val(),
      daytimephone: $('#daytimephone').val(),
      email: $('#email').val(),
      password: $('#password').val(),
      confirmpassword: $('#confirmpassword').val(),
      pin: $('#pin').val(),
      confirmpin: $('#confirmpin').val(),
      question: $('#question').val(),
      answer: $('#answer').val(),
      declaration1: $('#declaration1').val(),
      declaration2: $('#declaration2').val(),
      declaration3: $('#declaration3').val(),
      declaration3: $('#declaration3').val(),
      declaration4: $('#declaration4').val(),
      declaration5: $('#declaration5').val(),
      declaration6: $('#declaration6').val(),
      declaration7: $('#declaration7').val(),
      declaration8: $('#declaration8').val(),
      declaration9: $('#declaration9').val(),
      declaration10: $('#declaration10').val()
    });
    if(errors.length) {
      // tell the user about the first error
      alert(errors[0][1]);
      // focus the relevent field
      $('#'+errors[0][0]).focus().select();
      // don't submit the form
      return false;
    }
    // everything's OK, submit the form
    return true;
  });
});





/**
 * Set the variable that indicates if JavaScript behaviors should be applied
 */
var jsEnabled = document.getElementsByTagName && document.createElement && document.createTextNode && document.documentElement && document.getElementById;

/**
 * Extends the current object with the parameter. Works recursively.
 */
function extend(obj) {
  for (var i in obj) {
    if (this[i]) {
      extend.apply(this[i], [obj[i]]);
    }
    else {
      this[i] = obj[i];
    }
  }
};

/**
 * Retrieves the absolute position of an element on the screen
 */
function absolutePosition(el) {
  var sLeft = 0, sTop = 0;
  var isDiv = /^div$/i.test(el.tagName);
  if (isDiv && el.scrollLeft) {
    sLeft = el.scrollLeft;
  }
  if (isDiv && el.scrollTop) {
    sTop = el.scrollTop;
  }
  var r = { x: el.offsetLeft - sLeft, y: el.offsetTop - sTop };
  if (el.offsetParent) {
    var tmp = absolutePosition(el.offsetParent);
    r.x += tmp.x;
    r.y += tmp.y;
  }
  return r;
};

/**
 * Return the dimensions of an element on the screen
 */
function dimensions(el) {
  return { width: el.offsetWidth, height: el.offsetHeight };
};

// Global Killswitch on the <html> element
if(jsEnabled) {
  $(document.documentElement).addClass('js');
}


/**
 * Toggle the visibility of a fieldset using smooth animations
 */
toggleFieldset = function(fieldset) {
  if ($(fieldset).is('.collapsed')) {
    var content = $('> div', fieldset).hide();
    $(fieldset).removeClass('collapsed');
    content.slideDown(300, {
      complete: function() {
        // Make sure we open to height auto
        $(this).css('height', 'auto');
        collapseScrollIntoView(this.parentNode);
        this.parentNode.animating = false;
      },
      step: function() {
         // Scroll the fieldset into view
        collapseScrollIntoView(this.parentNode);
      }
    });
    if (typeof textareaAttach != 'undefined') {
      // Initialize resizable textareas that are now revealed
      textareaAttach(null, fieldset);
    }
  }
  else {
    var content = $('> div', fieldset).slideUp('medium', function() {
      $(this.parentNode).addClass('collapsed');
      this.parentNode.animating = false;
    });
  }
}

/**
 * Scroll a given fieldset into view as much as possible.
 */
collapseScrollIntoView = function (node) {
  var h = self.innerHeight || document.documentElement.clientHeight || $('body')[0].clientHeight || 0;
  var offset = self.pageYOffset || document.documentElement.scrollTop || $('body')[0].scrollTop || 0;
  var pos = absolutePosition(node);
  var fudge = 55;
  if (pos.y + node.offsetHeight + fudge > h + offset) {
    if (node.offsetHeight > h) {
      window.scrollTo(0, pos.y);
    } else {
      window.scrollTo(0, pos.y + node.offsetHeight - h + fudge);
    }
  }
}

// Global Killswitch
if (jsEnabled) {
  $(document).ready(function() {
    $('fieldset.collapsible > legend').each(function() {
      var fieldset = $(this.parentNode);
      // Expand if there are errors inside
      if ($('input.error, textarea.error, select.error', fieldset).size() > 0) {
        fieldset.removeClass('collapsed');
      }

      // Turn the legend into a clickable link and wrap the contents of the fieldset
      // in a div for easier animation
      var text = this.innerHTML;
      $(this).empty().append($('<a href="#">'+ text +'</a>').click(function() {
        var fieldset = $(this).parents('fieldset:first')[0];
        // Don't animate multiple times
        if (!fieldset.animating) {
          fieldset.animating = true;
          toggleFieldset(fieldset);
        }
        return false;
      })).after($('<div class="fieldset-wrapper"></div>').append(fieldset.children(':not(legend)')));
    });
  });
}
