$(function ()
  {
    jQuery.validator.addMethod("isValidProgram", function (value, element) {
      return value != 0;
    });

    jQuery.validator.setDefaults({debug: true});
    if ($("#combo_form").is("form"))
    {
       combo_form();
    }
  }
);


function combo_form()
{
  // set NON FORM values - we do not ask the user to provide answers for this
  lead_values["phpsessionid"] = ((phpsessionid) ? phpsessionid : '');
  lead_values["ip_address"]   = ((ip_address)   ? ip_address   : '');
  lead_values["date_created"] = ((date_created) ? date_created : '');

  full_program_list = $("select[name='program_id']").clone();

  teach_row   = $("select[name='teach_cert']").parent().parent();
  license_row = $("select[name='rn_license']").parent().parent();

  if (typeof(is_dominican) == 'undefined' && typeof(is_scranton) == 'undefined') {
	  $(teach_row).hide();
  }
  $(license_row).hide();
 
  
  phone_fixer();
  zipcode_fixer();
  filter_programs();
  //dropdown_fixer();

  var validate_rules = {
      first_name: {
        required: true,
        minlength: 2
      },
      last_name: {
        required: true,
        minlength: 2
      },
      street_addr: {
        required: true,
        minlength: 2
      },
      city: {
        required: true,
        minlength: 2
      },
      state: {
        required: true
      },
      day_phone: {
        required: true,
        phoneUS: true,
        nonRepeating: true
      },
      evening_phone: {
        required: true,
        phoneUS: true,
        nonRepeating: true
      },
      start_date: {
        required: true,
        min: 0,
        max: 6
      },
      category_id: {
        required: true,
        min: 1,
        max: 14
      },
      degree_level_id: {
        required: true,
        min: 1,
        max: 15
      },
      program_id: {
        isValidProgram: true
      },
      prev_education: {
        required: true,
        min: 1,
        max: 9
      },
      grad_year: {
        required: true,
        min: 1,
        max: 2010
      },
      age: {
        required: true,
        min: 18,
        max: 36
      },
      live_us: {
        required: true
      },
      citizen: {
        required: true
      },
      military: {
        required: true,
        min: 1,
        max: 26
      },
      rn_license: {
        required: false
      },
      teach_cert: {
        required: false
      },
      email: {
        required: true,
        email: true
      },
      zipcode: {
        required: true,
        digits: true,
        minlength: 5,
        maxlength: 5
      }
  },
  
  validate_messages = {
    first_name:      "Please enter your first name",
    last_name:       "Please enter your last name",
    street_addr:     "Please enter your address",
    start_date:      "Please enter your start date",
    day_phone:       "Please enter a valid phone number",
    evening_phone:   "Please enter a valid phone number",
    category_id:     "Please pick a category",
    degree_level_id: "Please choose a degree level",
    program_id:      "Please select a program",
    prev_education:  "Please select your prior education",
    grad_year:       "Please select your graduation year",
    age:             "Please select your age",
    live_us:         "Please enter if you live in the U.S.",
    citizen:         "Please enter if you are a U.S. Citizen",
    military:        "Please enter your military affiliation",
    rn_license:      "Please enter your license information",
    teach_cert:      "Please enter your certificate information",
    email:           "Please enter your email",
    city:           "Please enter your city",
    state:           "Please enter your state",
    zipcode:         "Please enter your zipcode"
  };
  
  if (typeof(is_kaplan) != 'undefined' && is_kaplan) {
    validate_rules.mobile_phone = {
      required: true,
      phoneUS: true,
      nonRepeating: true
    };
    
    validate_messages.mobile_phone = "Please enter a valid phone number";
  }

  $("#combo_form").validate({
    rules: validate_rules,
    messages: validate_messages
  });

  $("#combo_submit").click(function(){
      jQuery.each(jQuery.browser, function(i, val) {

        if(i=="msie" &&
            (jQuery.browser.version.substr(0,3)=="6.0"
            || jQuery.browser.version.substr(0,3)=="7.0"
            || jQuery.browser.version.substr(0,3)=="8.0")){
          ;//alert("You are using IE. Stop It");//do ie stuff
        }

      });

      //Validator doesn't check disabled elements, so enable for the validate
      var store_prog_flag = $("select[name='program_id']").attr("disabled");
      $("select[name='program_id']").removeAttr("disabled");

      if ($("#combo_form").valid()){
        ;//alert("valid");
        $("#combo_form").submit();
      }else{
        ;//alert("not valid");
      }

      $("select[name='program_id']").attr("disabled",store_prog_flag);
      return false;
    });
  $("#category_select").change(function(){filter_programs();});
  $("#degree_select").change(function(){filter_programs();});

}

function filter_programs()
{
  new_category_id     = $("#category_select").val();
  new_degree_level_id = $("select[name='degree_level_id']").val();

  if (new_category_id == 0 || new_degree_level_id == 0)
  {
    $("select[name='program_id']").attr("disabled","disabled");
    $("select[name='program_id']").parent().parent().css("color","gray");
    $("select[name='program_id']").empty();
    return false;
  }

  //Empty the program options and replace with matching originals
  $("select[name='program_id']").empty();

  var programs_seen = {},
    inserted_count = 0,
    spl = '';

  full_program_list.children().each(function () {

    spl = $(this).attr("class").split("_");
    my_category_id     = spl[0];
    my_degree_level_id = spl[1];
    my_program_id      = $(this).val().split('_')[2];

    if ((my_category_id == new_category_id || new_category_id == 12) &&
      (my_degree_level_id == new_degree_level_id || new_degree_level_id == 15)) {

      // hack to force the object to accept a number as a hash
      if (programs_seen['str'+my_program_id]) {
        return true;
      }

      programs_seen['str'+my_program_id] = true;

      $("select[name='program_id']").append($(this).clone());
      inserted_count++;
    }
    return true;
  });
  
  if (inserted_count === 0)
  {
    $("select[name='program_id']").append("<option value='0'>There are no programs for this Area and Degree Type</option>");
    $("select[name='program_id']").attr("disabled","disabled");
  }else
  {
    $("select[name='program_id']").removeAttr("disabled");
    $("select[name='program_id']").parent().parent().css("color","black");
    $("#combo_form").validate().element("select[name='program_id']");
  }

  $(teach_row).hide();
  $(license_row).hide();

  // Kaplan's categories have been overwritten to appease them
  if (typeof(is_kaplan) != 'undefined' && is_kaplan) {
	  if (new_category_id == 9)
	  {
		  $(license_row).show();
	  }else if (new_category_id == 11 || new_category_id == 6)
	  {
		  $(teach_row).show();
	  }
  }else
  {
	  console.log
	  if (new_category_id == 7)
	  {
		$(license_row).show();
	  }else if (new_category_id == 3 || (typeof(is_dominican) != 'undefined' && is_dominican) || (typeof(is_scranton) != 'undefined' && is_scranton))
	  { // We need to always show the teaching question for Dominican U or Scranton
		$(teach_row).show();
	  }
	}

  $(".hidden_form").hide();
  $(".hidden_form_category_"+new_category_id).show();
  $(".hidden_form_degree_"+new_degree_level_id).show();
  $(".hidden_form_category_"+new_category_id+'_degree_'+new_degree_level_id).show();
  return true;
}

function zipcode_fixer()
{
	$("#zipcode").keyup(function(event){
		var ev = $(this).val();
		ev = ev.replace(/\D/g,''); // strip out other stuff

		if (ev.length > 5){
		ev = ev.substr(0,5);
		}
		$(this).val(ev); // return it formatted
	});
}
