jQuery(function($) {

$('#quickFind select').change(function() {
  if($(this).val() != '')
    document.location = $(this).val();
});

$('a.external').live('click', function(event) {
  event.preventDefault();
  window.open($(this).attr('href'));
});

$('a[href^=#]').click(function(event) {
  target = $(this).attr('href');
  if(target.length > 1) {
    targetObj = $('a[name=\'' + target.slice(1) + "\']").closest(":visible");
    if(targetObj.length > 0) {
      event.preventDefault();
      $(window).scrollTo(targetObj, 300);
    }
  }
});

$('#slideshow').cycle({
  fx: 'fade',
  speed: 1200,
  timeout: 5500,
  pause: 1,
  pager: '#slideshow .pagination',
  pagerEvent: 'mouseover',
  slideExpr: 'a'
});

$('#slideshow .pagination a').click(function(event) {
  event.preventDefault();
});

$('form a.formSubmit').click(function(event) {
  event.preventDefault();
  if($(this).is(".disabled")) return;
  $(this).closest('form').submit();
});

$('input[title]').blur(function() {
  if($(this).val() == '') {
    $(this).addClass('hinting').val($(this).attr('title'));
    $(this).one('focus', function() {
      $(this).removeClass('hinting').val('');
    });
  }
}).trigger('blur');


$('#newsletter, #announcements').submit(function(event) {
  form = $(this);
  event.preventDefault();

  form.find('input, select').each(function() {
    if($(this).val() == '' || $(this).hasClass('hinting')) {
      $(this).addClass('invalid');
    } else {
      $(this).removeClass('invalid');
    }
  });

  invalids = form.find('.invalid');
  if(invalids.length > 0) {
    invalids.effect('shake', {distance: 10, duration: 100, times: 2});
    invalids.eq(0).select().focus();
    return;
  }

  form.find('input, select').css('background-color', '#eee').attr('disabled', 'disabled');
  form.find('a.formSubmit').hide();
  form.append('<p class="status">Subscribing...</p>');

  $.ajax({
    type: "POST",
    url: form.attr('action'),
    data: form.find(':input'),
    dataType: 'json',
    success: function() {
      form.find(".status").text("You have subscribed");
    },
    error: function() {
      form.find(".status").text("Sorry - subscription failed due to a network or server error");
    }
  });
});

$('#visaWizardBox').bBox();
$('#wizardProgress, #wizardSaved').hide();
$('#visaWizard, ul.jobs a.qualify, a.launchVisaWizard').click(function(event) {
  event.preventDefault();
  if($('#wizardContent').text() == '') {
    $('#wizardContent').load("/visa_wizard/index.php", "", function() {

      if($('#visaWizardTestMode').length > 0) {
        $('body').prepend("<div id=\"visaWizardTestArea\" style=\"padding: 5px 15px; background: lightgreen; position: relative; z-index: 9999; text-align: center;\">Visa Wizard Test Mode</div>");
      }
      
      $('#wizard .valRequired').change(wizardValidate);
      $('#wizard input[type=text].valRequired').keyup(wizardValidate);

      $('#wizard .valRequiredEmail').change(wizardValidateEmail);
      $('#wizard input[type=text].valRequiredEmail').keyup(wizardValidateEmail);

      $('#wizard select[name=australian_education_id]').change(function() {
        if($(this).find('option[selected][rel=followup]').length > 0) {
          $('#wizard .australian_education_dependent').removeAttr('disabled');
        } else {
          $('#wizard .australian_education_dependent').attr('disabled', 'disabled').removeAttr('checked');
        }
      });
      
      $('#wizard select[name=occupation_id]').change(function() {
        if($(this).find('option.worth60[selected]').length > 0) {
          $('#wizard input[name=occupation_worth_sixty_points]').attr('checked', 'checked');
          $('#wizard input[name=work_experience]').removeAttr('disabled');
        } else {
          $('#wizard input[name=occupation_worth_sixty_points]').removeAttr('checked');
          $('#wizard input[name=work_experience]').attr('disabled', 'disabled').removeAttr('checked');
        }
        if($(this).find('option.worth60.indemand[selected]').length > 0) {
          $('#wizard input[name=on_modl]').attr('checked', 'checked');
          $('#wizard input[name=occupation_in_demand]').removeAttr('disabled');
        } else {
          $('#wizard input[name=on_modl]').removeAttr('checked');
          $('#wizard input[name=occupation_in_demand]').attr('disabled', 'disabled').removeAttr('checked');
        }
        selected = $(this).find('option[selected]');
        if(selected.is(".hasdesc")) {
          $('#wizard .occupation_description').load("/occupation/description/" + selected.attr('value') + "/");
        } else {
          $('#wizard .occupation_description').text("");
        }
      });
      
      $('#describe_occupation').click(function(event) {
        event.preventDefault();
        occupation = $('#vwf_occupation_id option.hasdesc[selected]');
        if(occupation.length > 0) {
          window.open('/visa_wizard/index.php/occupations/' + occupation.attr('value'), 'occupation_description', 'width=400,height=450,resizable=yes,toolbar=no,scrollbars=yes,location=no,directories=no,status=no,menubar=no,copyhistory=no');
        }
      });
      
      $('#wizard input[name=partner]').change(function() {
        if($(this).is('[value="not resident"]')) {
          $('#wizard input[name^=non_resident_partner_]').removeAttr('disabled');
        } else {
          $('#wizard input[name^=non_resident_partner_]').removeAttr('checked').attr('disabled', 'disabled');
        }
      }).click(function() {
        $(this).trigger('change');
      });
      
      $('#wizard input[name=non_resident_partner_education_ok]').change(function() {
        if($(this).is(':checked')) {
          $('#wizard input[name=non_resident_partner_experience_ok]').removeAttr('checked');
        }
      }).click(function() {
        $(this).trigger('change');
      });
      $('#wizard input[name=non_resident_partner_experience_ok]').change(function() {
        if($(this).is(':checked')) {
          $('#wizard input[name=non_resident_partner_education_ok]').removeAttr('checked');
        }
      }).click(function() { $(this).trigger('change'); });
      
      $('#wizard input[name=family_sponsorship]').change(function() {
        if($(this).is(':checked')) {
          $('#wizard input[name=family_sponsorship_da]').removeAttr('disabled');
        } else {
          $('#wizard input[name=family_sponsorship_da]').removeAttr('checked').attr('disabled', 'disabled');
        }
      }).click(function() { $(this).trigger('change'); });
      
      $('#wizard input[name=employer_sponsorship]').change(function() {
        if($(this).filter('[value=permanent]').is(':checked')) {
          $('#wizard input[name=permanent_employer_situation], #wizard input[name=permanent_employer_regional_area]').removeAttr('disabled');
        } else {
          $('#wizard input[name=permanent_employer_situation], #wizard input[name=permanent_employer_regional_area]').removeAttr('checked').attr('disabled', 'disabled');
        }
      }).click(function() { $(this).trigger('change'); });
      
      $('#wizard input[name=student]').change(function() {
        if($(this).is(':checked')) {
          $('#wizard input[name=student_situation]').removeAttr('disabled');
        } else {
          $('#wizard input[name=student_situation]').removeAttr('checked').attr('disabled', 'disabled');
        }
      }).click(function() { $(this).trigger('change'); });
      
      $('#wizard input[name=agree_to_terms]').change(function() {
        if($(this).is(':checked')) {
          $(this).parents('fieldset').find('a.saveContinue').removeClass('disabled');
        } else {
          $(this).parents('fieldset').find('a.saveContinue').addClass('disabled');
        }
      }).click(function() {
        $(this).trigger('change');
      });
      
      $('select:visible').filter(":not(#wizard select)").addClass('hiddenForIE').hide();
      $('#visaWizardBox').bBoxShow({modal: true}).fadeIn(300, function() {
        $(this).find(':visible:input:first').select();
      });
      
      $('#resultsVisaTypes a').click(function(event) {
        event.preventDefault();
        window.open($(this).attr('href'));
      });

      $('#resultsDisclaimer').html($('#visaWizardBox .disclaimerSource').html());
      
    });
  } else {
    $('select:visible').filter(":not(#wizard select)").addClass('hiddenForIE').hide();
    $('#visaWizardBox').bBoxShow({modal: true}).fadeIn(300, function() {
      $(this).find(':visible:input:first').select();
    });
  }
});

$('#launchWizard').live('click', function(event) {
  event.preventDefault();
  if($(this).is('.disabled')) return;
  wizardFlipPage();
});

$('#wizard a.back').live('click', function(event) {
  event.preventDefault();
  wizardFlipPage('back');
});

$('#wizard a.saveContinue').live('click', function(event) {
  event.preventDefault();
  if($(this).is('.disabled')) return;
  wizardFlipPage();
});

$('#wizard a.resume').click(function(event) {
  event.preventDefault();
  $.ajax({
    url: '/visa_wizard/index.php/resume',
    type: 'get',
    data: $('#wizardResume input[name=resume_code]'),
    async: false, /* Defeats the purpose? Yeah. Shutup. */
    cache: false,
    dataType: 'json',
    success: function(data, status) {
      resumeCode = $('#wizardResume input[name=resume_code]').val();
      $('#wizardContent form input[name=resume_code]').remove();
      $('#wizardContent form').append('<input type="hidden" name="resume_code" value="' + resumeCode + '" />');
      $('#wizardCurrentResumeCode').text(resumeCode);
      $.each(data, function(fieldName, fieldValue) {
        if(fieldName == 'page') {
          // TODO: Jump to the right page, and hide/show wizard panels as needed
          // $('#wizardContent form fieldset').hide().eq(parseInt(fieldValue) - 1).show();
        } else {
          field = $('#wizardContent form :input[name=' + fieldName + ']');
          if(field.length > 0) {
            if(field.is(':checkbox')) {
              if(fieldValue == 'on') {
                field.attr('checked', 'checked');
              } else {
                field.removeAttr('checked');
              }
              field.trigger('change');
            } else if(field.is(':radio')) {
              selected_button = field.filter('[value="' + fieldValue + '"]');
              if(selected_button.length > 0) {
                selected_button.attr('checked', 'checked');
                selected_button.trigger('change');
              } else {
                field.removeAttr('checked');
                field.eq(0).trigger('change');
              }
            } else {
              field.val(fieldValue);
              field.trigger('change');
            }        
          }
        }
      });
    }
  });
});

$('#wizard a#saveProgress').click(function(event) {
  event.preventDefault();
  
  page = $('#wizard fieldset:visible:first');
  pageNum = $(page).prevAll().length + 1;
  $('#wizard input[name=page]').text(pageNum);
  
  wizardSave();
});

$('#closeX, a.closeX').click(function(event) {
  event.preventDefault();
  $('.hiddenForIE').removeClass('hiddenForIE').show();
  $.bBoxHide();
});

$('#refine select').change(function() {
  $('#refine input[name=p]').val(''); /* Go back to page 1 */
  $('#refine').submit();
});

$('#refine a[rel]').click(function(event) {
  event.preventDefault();
  $('#refine input[name=p]').val(''); /* Go back to page 1 */
  if($(this).hasClass('selected')) {
    $('#refine input[name=type]').val('');
  } else {
    $('#refine input[name=type]').val($(this).attr('rel'));
  }
  $('#refine').submit();
});

$('ul.paginate a[rel]').click(function(event) {
  event.preventDefault();
  $('#refine input[name=p]').val($(this).attr('rel'));
  $('#refine').submit();
});


$('#share a.toggleshare').click(function(event){event.preventDefault();});
$('#share a.toggleshare').mouseenter(function() {
  $('#shareoptions').show().stop(true, false).animate({width: 320});
});
$('#share').mouseleave(function() {
  $('#shareoptions').fadeTo(3000, 1, function() {
    $(this).animate({width: 0}, function() {
      $(this).hide();
    });
  });
});

$('#candidates:first').each(function() {
  $.getJSON("/candidates/industries.json", function(industries) {
    $.each(industries, function(id, industry) {
      $('#candidates select.industry')
        .append('<option value="' + id + '">' + industry + '</option>');
    });
  });

  $('#candidates select.industry').change(function() {
    $('#candidates select.candidate')
      .html('<option value="">Select Candidate...</option>');
    $.getJSON("/candidates/industries/" + $(this).val() + ".json", function(candidates) {
      $.each(candidates, function(i, candidate) {
        $('#candidates select.candidate')
          .append('<option>' + candidate + '</option>');
      });
    });
  });

  $('#candidates').submit(function(event) {
    event.preventDefault();
    
    $('#candidates select').each(function() {
      if($(this).val() == '') {
        $(this).addClass('invalid');
      } else {
        $(this).removeClass('invalid');
      }
    });
  
    invalids = $('#candidates .invalid');
    if(invalids.length > 0) {
      invalids.effect('shake', {distance: 10, duration: 100, times: 2});
      invalids.eq(0).select().focus();
      return;
    }
    
    document.location = $(this).attr('action') + "?" + $(this).serialize();
  });
});

$('#announcements:first').each(function() {
  $.getJSON("/jobs/industries.json", function(industries) {
    $.each(industries, function(id, industry) {
      $("#announcements select.job_industry")
        .append('<option value="' + id + '">' + industry + '</option>');
    });
  });
});

$('#visaAssessmentBox').bBox();
$('a.assessmentForm').click(function(event) {
  event.preventDefault();
  $('select:visible').addClass('hiddenForIE').hide();
  $('#visaAssessmentBox').bBoxShow({modal: true}).fadeIn(300, function() {
    $(this).animate({height: 650}, 400).find(':visible:input:first').select();
  });
});

$.fn.uberFind = function(uberSelector) {
  var matches = new String(uberSelector).match(/^P\((.*?)\)(.*)$/);
  if(matches) {
    return $(this).closest(matches[1]).find(matches[2]);
  }
  return $(uberSelector);
}

$.fn.setupExpanders = function() {
  return this.each(function() {
    $(this).find('input.hideshow:checkbox, input.hideshow:radio')
      .click(function() { $(this).trigger('change'); })
      .change(function(event) {
        var target = $(this).uberFind($(this).attr('rel'));
        if($(this).is(':checked') && target.is(':not(:visible)')) {
          target.show().find(':input:first').select();
          // target.closest("body, .scroller").scrollTo(target);
        } else if($(this).is(':not(:checked)') && target.is(':visible')) {
          target.hide();
        }
      });
      
    $(this).find('input.hideclear:radio')
      .click(function() { $(this).trigger('change'); })
      .change(function(event) {
        var target = $(this).uberFind($(this).attr('rel'));
        if($(this).is(':checked') && target.is(':visible')) {
          target.hide();
          target.find(':input').val('');
        }
      });
    
    return this;
  });
}
$('body').setupExpanders();

$.fn.setupMasks = function() {
  return this.each(function() {
    $(this).find('.date:text').mask('99/99/9999');
    $(this).find('.clientFileNumber:text').mask('aaaa9999');
    return this;
  });
};
$('body').setupMasks();

$('ul.repeatableSection').each(function() {
  template = $(this).find('li:first');
  template.append('<a href="#" class="add">Add</a><a href="#" class="delete">Delete</a>')
  $(this).data('repeatableTemplate', template.html());
  $(this).bind('reindex', function() {
    items = $(this).find('li');
    items.each(function(index) {
      $(this).find(':input[name]').each(function() {
        name = $(this).attr('name');
        newname = name.replace(/\[[0-9]*\]/, '[' + index + ']');
        $(this).attr('name', newname);
      })
    });
    if(items.length <= 1) {
      items.find('a.delete').addClass('disabled');
    } else {
      items.find('a.delete').removeClass('disabled');
    }
  }).trigger('reindex');
});

$('ul.repeatableSection li a.add').live('click', function(event) {
  if($(this).is('.disabled')) return false;
  repeatableSection = $(this).closest('ul.repeatableSection');
  item = $(this).closest('li');
  template = repeatableSection.data('repeatableTemplate');
  item.after('<li>' + template + '</li>');
  item.next().setupMasks().setupExpanders();
  repeatableSection.trigger('reindex');
  return false;
});

$('ul.repeatableSection li a.delete').live('click', function(event) {
  if($(this).is('.disabled')) return false;
  repeatableSection = $(this).closest('ul.repeatableSection');
  $(this).closest('li').remove();
  repeatableSection.trigger('reindex');
  return false;
});

$('a.submitAssessment').click(function(event) {
  event.preventDefault();
  if($(this).is('.disabled')) return;
  $('.assessmentSuccessMessage, .assessmentErrorMessage, .assessmentInvalidMessage').hide();
  $('#assessmentContent input.invalid').removeClass('invalid');
  $(this).addClass('disabled');
  disabled_fields = $('#assessmentContent').find(":input").attr('disabled', 'disabled');
  $('.assessmentSubmittingIndicator').show();
  $.ajax({
    url: $(this).closest('form').attr('action'),
    type: $(this).closest('form').attr('method'),
    cache: false,
    data: $(this).closest('form').find(':input:not(:checkbox, :radio, .ignore), :input:checkbox:checked:not(.ignore), :input:radio:checked:not(.ignore)'),
    dataType: 'json',
    success: function(data, status) {
      $('.assessmentSubmittingIndicator').hide();
      $('.assessmentSuccessMessage').show();
    },
    error: function(response, status) {
      $('.assessmentSubmittingIndicator').hide();
      $('a.submitAssessment').removeClass('disabled');
      disabled_fields.removeAttr('disabled');
      if(response.status == 422) {
        $('.assessmentInvalidMessage').show();
        data = eval("(" + response.responseText + ")");
        $.each(data['errors'], function(fieldname, error) {
          $('#assessmentContent input[name=' + fieldname + ']').addClass('invalid');
        });
      } else {
        $('.assessmentErrorMessage').show();
      }
    }
  });
});

$('table.occupations a.growshrinkhandle').click(function(event) {
  event.preventDefault();
  if($(this).is('.grown')) {
    $(this).closest('tr').next('tr').find('.description').hide('blind');
    $(this).removeClass('grown');
  } else {
    $(this).closest('tr').next('tr').find('.description').show('blind');
    $(this).addClass('grown');
  }
});

$('table.occupations').eq(0).each(function() {
  matches = new String(document.location).match(/#([^#\?]*)($|\?)/);
  if(matches) {
    target = matches[1];
    targetel = $(this).find('tr#occupation' + target).eq(0);
    if(targetel) {
      $(window).scrollTo(targetel);
      targetel.find('a.growshrinkhandle').click();
    }
  }
});

$('#shareEmailBox').bBox();

$('#shareoptions a.email').click(function(event) {
  event.preventDefault();
  $('#shareEmailBox').bBoxShow({modal: true});
  $('#shareEmail input[name=url]').val(document.location);
  $('#shareEmail input[name=title]').val($('head title').text());
  $('#shareEmail input[type=text]').removeAttr('disabled');
  $('#shareEmail .status').text('');
  $('#shareEmail a.formSubmit').removeClass('disabled');
  $('#shareEmail input:first').focus();
});

$('#shareEmailBox form').submit(function(event) {
  event.preventDefault();
  var inputs = $(this).find("input[type=text]");
  var submit = $(this).find("a.formSubmit");
  var status = $('#shareEmail .status');
  var name_input = inputs.filter('input[name=to_name]');
  var email_input = inputs.filter('input[name=to_email]');
  var from_name_input = inputs.filter('input[name=from_name]');
  var from_email_input = inputs.filter('input[name=from_email]');

  inputs.removeClass('invalid');

  invalid = false;
  if(name_input.val() == "") {
    name_input.addClass('invalid');
    invalid = true;
  }
  if(email_input.val().match(/^[^@\s]+@[^@\.\s]+\.[^@\s]+$/)) {
  } else {
    email_input.addClass('invalid');
    invalid = true;
  }
  if(from_name_input.val() == "") {
    from_name_input.addClass('invalid');
    invalid = true;
  }
  if(from_email_input.val().match(/^[^@\s]+@[^@\.\s]+\.[^@\s]+$/)) {
  } else {
    from_email_input.addClass('invalid');
    invalid = true;
  }

  if(invalid) {
    status.text('All fields are required');
    $(this).find('input.invalid:first').focus();
    return;
  }

  inputs.attr('disabled', 'disabled');
  submit.addClass('disabled');
  status.removeClass('fail').text('Sending...');

  $.ajax({
    url: "/emailpage.php",
    type: 'post',
    data: $(this).find('input'),
    success: function() {
      status.text('Sent');
      // Delay before closing
      $('#shareEmailBox').fadeTo(1500, 1.0, function() {
        $.bBoxHide();
        inputs.val('');
      });
    },
    error: function() {
      status.addClass('fail').text('Sending failed');
      submit.removeClass('disabled');
      inputs.removeAttr('disabled');
    }
  });
});

$('form#pay').submit(function(event) {
  var ewt = $(this).find('input[name=ewayTotalAmount]');
  var amt = $(this).find('input[name=amount]');
  var amtValValid = amt.val().match(/^[1-9][0-9]*(?:\.[0-9]{0,2})?$/);
  var amtVal = parseFloat(amt.val());
  var amtValCents = parseInt(100.0 * amtVal);
  if(amtValValid && amtValCents >= 200) {
    // Valid Number
    ewt.val(amtValCents);
  } else {
    amt.addClass('invalid');
    return false;
  }
});


// classify annoying form builder text inputs
$('input[type=text]').addClass('textinput');

var resume_code = $('#wizardResume input:not(.hinting)[name=resume_code]').val();
if(resume_code != undefined && resume_code != "Resume Code") {
  $('#visaWizard').trigger('click');
  $('#wizardResume a.resume').trigger('click');
}

if($('#startVisaWizard').length > 0) {
  $('#visaWizard').trigger('click');
}

}); /* End DOM loaded */

function a() {
  $('ul:hidden').show();
}

function wizardFlipPage(direction) {
  var animA = {left: -3000};
  var shift = {left: 3000};
  var animB = {left: 0};

  fromPage = $('#wizard fieldset:visible:first');
  fromPageNum = $(fromPage).prevAll().length + 1;
  
  if(parseInt(direction) > 0) {
    if(fromPageNum < parseInt(direction)) {
      animA = {left: 3000};
      shift = {left: -3000};
    }
    toPage = $('#wizard fieldset:visible:eq(' + (fromPageNum - 1) + ')');
  } else {
    if(direction == 'back') {
      animA = {left: 3000};
      shift = {left: -3000};
    }
    toPage = (direction == 'back' ? $(fromPage).prev('fieldset') : $(fromPage).next('fieldset') );
  }

  if(toPage.length == 0 || toPage == fromPage) return;

  pageNum = $(toPage).prevAll().length + 1;
  totalPages = $(toPage).siblings('fieldset').andSelf().length - 1;
  percentComplete = totalPages > 0 ? parseInt((pageNum-1) * 100.0 / totalPages) : 0;

  $('#visaWizardBox').animate(animA, 700, function() {
    
    $('#wizard input[name=page]').val(pageNum);
    
    wizardSave();

    if($(toPage).is(":first-child")) {
      $('#wizardInfo, #wizardResume').show();
      $('#wizardProgress, #wizardSaved').hide();
    } else if($(toPage).is(".results")) {
      $('#wizardInfo, #wizardResume, #wizardSaved').hide();
      $('#wizardProgress').show();
    } else {
      $('#wizardInfo, #wizardResume').hide();
      $('#wizardProgress, #wizardSaved').show();
    }

    fromPage.hide();
    $('#wizard .pageNumber').text(pageNum);
    $('#wizardProgress .progressPercent').text(percentComplete);
    toPage.show();
    
    $(this).css(shift).animate(animB, 700, function() {
      $(this).find(':visible:input:first').select();
      $('#wizardProgress .bar').animate({width: '' + percentComplete + '%'});
    });
  });
}

function wizardSave() {
  $.ajax({
    url: '/visa_wizard/index.php/save',
    type: 'post',
    data: $('#wizardContent form :input:not(:checkbox, :radio, .ignore), #wizardContent form :input:checkbox:checked:not(.ignore), #wizardContent form :input:radio:checked:not(.ignore)'),
    async: false, /* Defeats the purpose? Yes. */
    cache: false,
    dataType: 'json',
    success: function(data, status) {

      if($('#visaWizardTestMode').length > 0) {
        testtext = "";
        $.each(data['points'], function(vt, points) {
          if(points == "0")
            testtext += "[" + vt + ": met] ";
          else
            testtext += "[" + vt + ": " + points + "] ";
        });
        $('#visaWizardTestArea').text(testtext);
      }

      if($('#wizardContent form input[name=resume_code]').length == 0) {
        $('#wizardContent form').append('<input type="hidden" name="resume_code" value="' + data['resume_code'] + '" />');
        $('#wizardCurrentResumeCode').text(data['resume_code']);
      }
      
      visa_types = $('#resultsVisaTypes li').hide();
      $.each(data['eligible_visas'], function() {
        visa_types.filter('.' + this).show().find('.points').text(data['eligible_points'][this]);
      });
      if(data['eligible_visas'].length == 0) {
        $('#noMatchingVisaTypes').show();
        $('#someMatchingVisaTypes').hide();
      } else {
        $('#someMatchingVisaTypes').show();
        $('#noMatchingVisaTypes').hide();
      }
      
      $('body').append(data['tracking_code']);

    }
  });
}

function wizardValidate(event) {
  wizardFieldResetValidation(this);
  if($(this).val().length > 0) {
    wizardFieldPassValidation(this);
  } else {
    wizardFieldFailValidation(this, "cannot be blank");
  }
}

function wizardValidateEmail(event) {
  wizardFieldResetValidation(this);
  if($(this).val().match(/^[^@\s]+@[^@\.\s]+\.[^@\s]+$/)) {
    wizardFieldPassValidation(this);
  } else {
    wizardFieldFailValidation(this, "must be a valid e-mail address");
  }
}

function wizardFieldResetValidation(field) {
  $(field).nextAll("span").remove();
}

function wizardFieldFailValidation(field, message) {
  span = $(field).next('span:first');
  if(span.length == 0) {
    $(field).after('<span class="bad">' + message + '</span>');
    $(field).removeClass('valid');
  }
  
  $('#launchWizard').addClass('disabled');
}

function wizardFieldPassValidation(field) {
  span = $(field).next('span:first');
  if(span.length == 0) {
    $(field).addClass('valid');
    $(field).after('<span class="good">.</span>');
  }
  
  if($(field).closest('fieldset').find('.valRequired:input:not(.valid), .valRequiredEmail:input:not(.valid)').length == 0) {
    $('#launchWizard').removeClass('disabled');
  } else {
    $('#launchWizard').addClass('disabled');
  }
}

function locateElement(from, uberSelector) {

}
