$(document).ready(function()
{  
  var form = $("#registration");
  
  $("#registration input, #registration select").live("blur",updateForm);
  
  function updateForm(event){
    $.ajax({
      type:"post",
      url: "/open-an-account/" + $("#ref").val(),
      data: form.serialize()      
    });
  }
  
  
  $("#save-button").live("click",function()
  {
    var password = $("#account\\_Individuals\\[0\\]\\_Email").val() == "" ? "<label>Your main e-mail</label><input onclick='$(this).select()' type='text' name='save' value='type your email here'></input>" : "<p>One email containing all the necessary information will be sent to:</p><input type='text' name='save' value='"+ $("#account\\_Individuals\\[0\\]\\_Email").val() +"' />";
    var sfl = "<form id='sfl'><p>With this feature you can save all of your current progress on the form and come back to finish the registration process later. We'll simply send you an email with a link so you can access the form at a more convenient time.</p>" + password + "</form>";
    
    $(sfl).dialog({
      autoOpen : true,
      resizable : false,
      title: "Save Form for Later",
      modal : true,
      buttons : {
        "Send Email" : function(){
          var that = this;
          $.ajax({
            type:"post",
            url: "/open-an-account/" + $("#ref").val(),
            data: $(this).serialize(),
            beforeSend : function(xhr){
              $(that).append("<center id='sfl-progress' style='margin-top:10px'><img src='/content/images/ajax-progress.gif' alt='loading...'/></center>");
              $("#sfl-warning").remove();
            },
            success : function(data){
              $("#sfl-progress").remove();
              $(that).append("<p id='sfl-warning' style='color:green'>Email sent sucessfully!</p>")
              setTimeout(function(){
                $(that).dialog("close");
              },2000);
            },
            error : function(){
              $("#sfl-progress").remove();
              $(that).append("<p id='sfl-warning' style='color:red'>Please enter a valid e-mail address</p>")
            }
          })
        },
        "Cancel" : function(){$(this).dialog("close")}
      }
    }).submit(function(e){e.preventDefault();})
    
    $()
  })
  
  if(form.html() != null)
  {
          
    form.crossfade(
      {
        items: 'fieldset',
        nav: '#nav',
        controls: {prev:'Back',next:'Proceed'},
        start:0,
        duration:0,
        fixed:false
      });
    
    // NAVIGATION CLONE - ATTEMPT TO COMMENT IT OUT
    form.find(".controls:gt(0)").each(function()
    {
      var clone = $(this).clone(true);
      clone.addClass("top");
      $(this).parent().prepend(clone);
    });
    //
    
    
    form.find('fieldset:first .controls .next').removeClass('next').addClass('begin');
    
    // FORM VALIDATION
    var validation  = form.validate({invalidHandler:invalidForm});
    
    //$(".phone").rules("add", {minlength:11, digits: true});
    $(".postcode").rules("add", {minlength:5});
      
    
    //LIVE QUERY    
    $('.individual').livequery(function() {
      
      //$(".country-selector option[value='487']").attr("selected", "selected");
      
      
      var individuals = $(this);
      
      individuals.find(".documentInformation").hide();
      
      //individuals.find(".phone").rules("add", {minlength:11, digits: true});
      individuals.find(".postcode").rules("add", {minlength:5});
      
      individuals.find('.issue').datepicker({
        showOn: 'button',
        buttonImage: '/content/images/calendar.gif',
        buttonImageOnly: true,
        dateFormat: 'dd/mm/yy',
        minDate: '-10y',
        maxDate: '+10y',
        yearRange: '-10:+10',
        changeMonth: true,
        changeYear: true
      });
      
      individuals.find('.birthday').datepicker({
        showOn: 'button',
        buttonImage: '/content/images/calendar.gif',
        buttonImageOnly: true,
        dateFormat: 'dd/mm/yy',
        minDate: '-110y',
        maxDate: '-18y',
        defaultDate: '-40y',
        yearRange:'1900:2200',
        changeMonth: true,
        changeYear: true
      });   
      
      //individuals.find(".documentInformation .required").each(function(){$(this).rules("add",{required:false})});
      $(".documentType").each(function(){setDocumentInfo($(this))});
      $(this).find(".documentType").change(function(){setDocumentInfo($(this))});
      
    });

    
    $('.newIndividual').click(function(event){
      event.preventDefault();
      var clone = form.find('.individual:first').clone(true);
      clone.find('label.error').remove();
      clone.find("img.ui-datepicker-trigger").remove();
      clone.find('.documentType').next('label').text('Document Number:');
      clone.find('input, select').removeClass('error valid')
      
      firstInput = form.find('.individual:last input:first');
      firstInput = firstInput.attr('id').substring(firstInput.attr('id').lastIndexOf('_')+1,firstInput.attr('id').length);
      
      clone.find('input,select').each(function()
      {
        var node = form.find('.individual').length;// + Number(firstInput);
        
        var id = $(this).attr('id');
        var newId = id.substring(0,id.lastIndexOf('[')+1);
        $(this).attr('id',newId + node + id.substring(id.lastIndexOf("]"), id.length));
        
        $(this).removeClass('hasDatepicker');
        $(this).prev('label').attr('for',newId + node);
        
        var name = $(this).attr('name');
        var newName = name.substring(name.lastIndexOf(']'),name.length);
        var prefix = name.substring(0,name.lastIndexOf('['))
        $(this).attr('name', prefix + '[' + node + newName);
      })
      clone.find('input').val('');
      var remove = clone.find('.remove');
      if(remove.html() == null)
      {
        clone.find('legend').after("<div class='remove'>(x) remove</div>");
        clone.find('.remove').bind('click',removeIndividual)
      }
      form.find('.individual:first').before(clone);
      
    })
    
  }
  
  function setDocumentInfo(documentType)
  { 
    var individual = documentType.closest(".individual");
    
    switch(documentType.val())
    { 
      case "drivingLicense":
        //individual.find(".documentInformation .required").each(function(){$(this).rules("add",{required:true})});
        individual.find(".documentInformation").show();
        individual.find(".documentNumber").html("License Number:<a class='fieldInfo' href='/content/images/forms_driving_license.jpg'>Where is my Driving License Number?</a>");
        break;
      case "passport":
        //individual.find(".documentInformation .required").each(function(){$(this).rules("add",{required:true})});
        individual.find(".documentInformation").show();
        individual.find(".documentNumber").html("Passport Number:<a class='fieldInfo' href='/content/images/forms_passport.jpg'>Where is my Passport Number?</a>");
        break;
      default:
        //individual.find(".documentInformation .required").each(function(){$(this).rules("add",{required:false})});
        individual.find(".documentInformation").hide();
    }
    $("a.fieldInfo").fancybox();
  }
  
  function removeIndividual()
  {
    var individual = $(this).parent('.individual');
    if(confirm("Are you sure you want do delete this Individual? The information you provided for this item will be lost"))
    {
      individual.remove();
      updateForm();
    }
  }
  
  function invalidForm()
  {
    if($('.errors').html()==null) $('.submit').closest('fieldset').append("<div class='errors'></div>")
    $('.errors').show('pulsate',{times:3},function(){setTimeout(function(){$('.errors').fadeOut()},5000)}).html("Unfortunately there were ("+ validation.invalidElements().length + ") errors on this form, please correct these errors by clicking on the red tabs (above)")
    
    $('#nav li').removeClass('red');
    $(jQuery.unique(validation.invalidElements().closest('fieldset'))).each(function()
    {
      var index = form.children('fieldset').index($(this));
      var altIndex = form.children('fieldset').index($(this).parent('fieldset'));
      index == -1 ? $('#nav li').eq(altIndex).addClass('red') : $('#nav li').eq(index).addClass('red');
    })
    
    $('#nav').click(function(){$('.errors').hide()})
  }
  
});