$(document).ready(function()
{  
  var form = $("#registration");
  
  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(); 
    }
  }
  
  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()})
  }
  
});