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

    jQuery.validator.setDefaults({debug: true,onlick: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();
  full_edu_list = $("select[name='prev_education']").clone();

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

	$("#skip_button").click(function(){
		url = window.location;
		window.location = url;
		$(this).hide();
		
	});
	
	$("#more").click(function(){
		$("#truncated_desc").hide();
		$("#full_desc").show();	
	});

  if (typeof(is_dominican) == 'undefined' && typeof(is_scranton) == 'undefined') {
	// commented out for customform  $(teach_row).hide();
  }
  $(license_row).hide();
  if (typeof(is_gcu) != 'undefined')
  {
      mgmt_row = $("select[name='mgmt']").parent().parent();
      $(mgmt_row).hide();
  }

	if (typeof(is_capella) != 'undefined' && is_capella) {
		// display/hide capella's transfer credits question based on highest level of education value
		$("#prev_education").click(function(){
			if ($("#prev_education").val() > 0 && $("#prev_education").val() < 5) 
			{
				$(".hidden_form_transfer_credits").show();
			}
			else
			{
				$(".hidden_form_transfer_credits").hide();
			}
		});
	}	
	
	
	if (typeof(is_kaplan) != 'undefined' && is_kaplan) {

		// display/hide AAS in Medical Assisting extra questions when it's picked
		$("#program").change(function(){
			if ($("#program").val().substr(0,4) == '5678')
			{
				$(".hidden_form_medical_assisting").show();
			}
			else
			{
				$(".hidden_form_medical_assisting").hide();
			}
		});		
		
	}

	if ((typeof(is_devry) != 'undefined' && is_devry) || (typeof(is_keller) != 'undefined' && is_keller)) {
		nj_zips = [ "201","551","609","732","848","856","862","908","973" ];
		show_consent_flag = 0;

		// display/hide NJ contact question based on area code
      // blur handler used instead of change because our auto-formatting 
      // code for the input (phone_fixer) interferes with change event firing
      // on Safari, IE
		$("#day_phone").blur(function(){
			// has to be a full phone number
			if ($("#day_phone").val().length > 13)
			{
				area_code = $("#day_phone").val().substr(1,3);
				if (jQuery.inArray(area_code,nj_zips) > -1)
				{
					show_consent_flag = 1;
				} else {
					$(".hidden_form_consent_flag").hide();
					show_consent_flag = 0;
            }
			}
			// if neither made it show, then make sure it's hidden
			if (show_consent_flag != 1)
			{
				$("#consent_td").empty();
				$(".hidden_form_consent_flag").hide();
			}
			else
			{
				$("#consent_td").html('<span>For New Jersey residents, DeVry must have your express consent before we contact your mobile phone. Checking “yes” and submitting this form constitutes your express consent to be called by DeVry University at the number listed regarding furthering your education.</span><br /> <select name="consent_flag"><option value="">Please select one:&nbsp;</option><option value="1">Yes</option><option value="0">Skip</option> </select>');
				$(".hidden_form_consent_flag").show();

			}
		});
		
		$("#evening_phone").blur(function(){
			// has to be a full phone number
			if ($("#evening_phone").val().length > 13)
			{
				area_code = $("#evening_phone").val().substr(1,3);

				if (area_code == "201" || area_code == "551" || area_code == "609" || area_code == "732" || area_code == "848" || area_code == "856" || area_code == "862" || area_code == "908" || area_code == "973")
				{
					show_consent_flag = 1;
				} else {
					$(".hidden_form_consent_flag").hide();
					show_consent_flag = 0;
				}
			}
			// if neither made it show, then make sure it's hidden
			if (show_consent_flag != 1)
			{
				$("#consent_td").empty();
				$(".hidden_form_consent_flag").hide();
			}
			else
			{
				$("#consent_td").html('<span>For New Jersey residents, DeVry must have your express consent before we contact your mobile phone. Checking “yes” and submitting this form constitutes your express consent to be called by DeVry University at the number listed regarding furthering your education.</span><br /> <select name="consent_flag"><option value="">Please select one:&nbsp;</option><option value="1">Yes</option><option value="0">Skip</option> </select>');
				$(".hidden_form_consent_flag").show();

			}			
		});
				
	}	

  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: 17
      },
      degree_level_id: {
        required: true,
        min: 1,
        max: 15
      },
      program_id: {
        isValidProgram: true
      },
      prev_education: {
        required: true,
        min: 1,
        max: 11
      },
      grad_year: {
        required: true,
        min: 1,
        max: 2020
      },
      age: {
        required: true,
        min: 17,
        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"
  };

// function that allows access to the school id
	function getQueryParams(qs){
	    qs = qs.split("+").join(" ");
	    var params = {};
//		This loop is infinite in a few browsers		
//	    var tokens;
//	    while (tokens = /[?&]?([^=]+)=([^&]*)/g.exec(qs)) {
//	        params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
//	    }
	    
	    // http://stevenbenner.com/2010/03/javascript-regex-trick-parse-a-query-string-into-an-object/
	    qs.replace(
			new RegExp("([^?=&]+)(=([^&]*))?", "g"), 
			function($0, $1, $2, $3){
	        	params[$1] = $3;
	    	}
		);
	    return params;
	}
	if (typeof(cf_school_id) != 'undefined')
	{
		var schoolString="school="+ cf_school_id;
	}
	else
	{
		var $_GET = getQueryParams(document.location.search);
		var schoolString = "school="+$_GET['school'];
	}

  
//  Dynamically generate the messages and rules
  var mnr= $.ajax({type: "GET", data: schoolString, url: "/ajax/get_messages_and_rules.php", async: false}).responseText;
  eval(mnr);
//

    if (typeof(is_ashford) != 'undefined' && is_ashford) {
        validate_rules.agree = {
            required: true,
            min: 1,
            max: 1
        };
        validate_messages.agree = "We need your permission to contact you";
  }


	if (typeof(is_phoenix) != 'undefined' && is_phoenix) {
	  validate_rules.prev_education = {
	      required: true,
	      min: 1,
	      max: 10
	  };
	}
	
	if (typeof(is_ftuo) != 'undefined' && is_ftuo) {
        validate_rules.enroll_start = {
            required: true,
            min: 0,
            max: 6
        };
        validate_rules.agree = {
            required: true,
            min: 1,
            max: 1
        };
        validate_rules.prev_education = {
            required: true,
            min: 1,
            max: 13
        };
        validate_rules.hours_per_week = {
            required: true,
            min: 1,
            max: 20
        };
        validate_rules.outstanding_balance = {
            required: true,
            min: 0,
            max: 1
        };
        validate_messages.enroll_start = "Please select when you plan to enroll";
        validate_messages.agree = "Please acknowledge that you may be contacted";
        validate_messages.prev_education = "Please select your highest level of education";
        validate_messages.hours_per_week = "Please select how many hours you plan to dedicate";
        validate_messages.outstanding_balance = "Please answer about outstanding balances";
  }

  if (typeof(is_jacksonville) != 'undefined' && is_jacksonville)
  {
      validate_rules.prev_education = {
          required: true,
          min: 1,
          max: 14
      }
  }
  if (typeof(is_leo) != 'undefined' && is_leo) {
      validate_messages.prev_education = "Education does not meet requirements";
  }


  if ((typeof(is_devry) != 'undefined' && is_devry) || (typeof(is_keller) != 'undefined' && is_keller)) 
  {
      validate_rules.on_campus = {
          required: true,
          min: 0,
          max: 2
      };
	  validate_messages.on_campus = "Please select your class type preference";
      validate_rules.consent_flag = {
          required: true,
          min: 0,
          max: 1
      };
	  validate_messages.consent_flag = "Please indicate if we can contact you by phone";	
	
  }
	
  if (typeof(is_phoenix) != 'undefined' && is_phoenix) {
      validate_messages.salutation = "Please select your salutation";
      validate_messages.foreign = "Please choose yes or no";
      validate_messages.campus = "Please select your preferred learning location";
      validate_messages.agree = "Please acknowledge that you may be contacted";

      validate_rules.salutation = {
          required: true,
          min: 1,
          max: 3
      };
      validate_rules.foreign = {
          required: true,
          min: 1,
          max: 2
      };
      validate_rules.campus = {
          required: true,
          min: 1,
          max: 2
      };
      validate_rules.agree = {
          required: true,
          min: 1,
          max: 1
      };
      validate_rules.evening_phone = {
          required: false
      };
  }

  if (typeof(is_wgu) != 'undefined' && is_wgu) {
      validate_rules.enroll = {
        required: true,
        min: 1,
        max: 13
      };
      validate_rules.commit = {
        required: true,
        min: 1,
        max: 4
      };
      validate_rules.learner = {
        required: true,
        min: 1,
        max: 3
      };
      validate_rules.rn_license = {
        required: false,
        min: 1,
        max: 1
      };

      validate_messages.enroll = "Please indicate when you plan to enroll";
      validate_messages.commit = "Please indicate how much time you can commit";
      validate_messages.learner = "Please rate yourself as a self-directed learner";
      validate_messages.rn_license = "<p>WGU's Nursing degree programs require students to already possess a current, unencumbered RN (registered nurse) license. If you do not currently possess an RN license, you are not eligible for admission into this program. If you are not sure whether your RN license is current and/or unencumbered, please contact your state's licensing board for more information.</p>";
  }

  $("#combo_form").validate({
    rules: validate_rules,
    messages: validate_messages,
	errorPlacement:function(error,element){
		error.find("br").remove();
		error.insertAfter(element);
	}

  });

  $("#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();});

  if (typeof(is_phoenix) != 'undefined' && is_phoenix) {
      $("#campus_select").change(function(){filter_programs();});
      $("#zipcode_input").change(function(){filter_programs();});
  }

  if (typeof(is_leo) != 'undefined' && is_leo) {
      $("#prev_education").change(function(){filter_programs();});
      $("#program").change(function(){filter_education();});
  }
}

function filter_programs()
{
  new_category_id     = $("#category_select").val();
  if(new_category_id==null){
  	new_category_id=12;
  }
  new_degree_level_id = $("select[name='degree_level_id']").val();
  new_education_level = $("#prev_education").val();
  current_program = $("#program").val();

    // since u of rockies doesn't include area of study, assume they want undecided
    if(typeof(is_rockies) != 'undefined' && is_rockies)
    {
          new_category_id = 12;
    }

    // since strayer doesn't include area of study, hard code to 1
    if(typeof(is_strayer) != 'undefined' && is_strayer)
    {
          new_degree_level_id = 1;
    }

	if(typeof(is_phoenix) != 'undefined' && is_phoenix)
	{
		campus_pref = $("select[name='campus']").val();
		entered_zipcode = $("#zipcode_input").val();
		
		if (new_category_id == 0 || new_degree_level_id == 0 || campus_pref == 0 || entered_zipcode == '')
	  	{
	    	$("select[name='program_id']").attr("disabled","disabled");
	    	$("select[name='program_id']").parent().parent().css("color","gray");
	    	$("select[name='program_id']").empty();
	    	return false;
	  	}
		var postdata = {};
		postdata['category_id'] = new_category_id;
		postdata['degree_level_id'] = new_degree_level_id;
		postdata['campus_pref'] = campus_pref;
		postdata['zipcode'] = entered_zipcode;

		$.ajax({
                url: '/ajax/get_uop_progs.php',
                type: "POST",
                data: postdata,
                cache: false,
                async:false,
                dataType: "html",
                success: function(data){
					if (data != '')
					{
						// we've got programs - populate and activate the dropdown
						$("select[name='program_id']").html(data);
						$("select[name='program_id']").removeAttr("disabled");
						$("select[name='program_id']").parent().parent().css("color","black");
						$("#combo_form").validate().element("select[name='program_id']");
						
						// remove error prompt if it exists
						if ($("#noprog_error").get(0) != undefined)
						{
							$("#noprog_error").remove();
						}				
					}
					else
					{
						$("select[name='program_id']").attr("disabled","disabled");
						$("select[name='program_id']").parent().parent().css("color","gray");
						
						// add error message if it isn't already there
						if ($("#noprog_error").get(0) == undefined)
						{
							$("#campus_select").after('<label id="noprog_error" class="error" for="campus_select" generated="true">No programs match your criteria - please change your campus preference.</label>');
						}
					}
				}
		});
	}
	else
	{

	  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 program_names_displayed = []; // added to dedupe the undecided category
	  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];

	    // Ugly hack required by stleo to limit programs displayed by education level
	    if (typeof(is_leo) != 'undefined' && is_leo) {
	        if ((my_category_id == new_category_id || new_category_id == 12) &&
	            (my_degree_level_id == new_degree_level_id || new_degree_level_id == 15) &&
	            (new_education_level == 0 || new_education_level > 5 || my_degree_level_id != 2)) {
	            // 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++;
	        }
	    }
	    else 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;
	      my_program_name=$(this).text();

		  if(my_program_name in program_names_displayed)
		  {
		  	// screw troy
		  }
		else
		  { // added to dedupe the undecided category

	         $("select[name='program_id']").append($(this).clone());
	           inserted_count++;
		      program_names_displayed.push(""+my_program_name);

	      }
	    }
	    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
	  {
	      if (!(new_category_id == 12 && new_degree_level_id == 15)) {
	        $("select[name='program_id']").prepend("<option value='0' selected='selected'>Please select one:</option>");
	      }
	      $("select[name='program_id']").removeAttr("disabled");
	      $("select[name='program_id']").parent().parent().css("color","black");
	      $("#combo_form").validate().element("select[name='program_id']");
	  }

	  //  commented out for custom form $(teach_row).hide();
	  $(license_row).hide();
	  if (typeof(is_gcu) != 'undefined')
	  {
	      $(mgmt_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
	  {
	      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();
	      }
	  }

	  if (typeof(is_gcu) != 'undefined' && new_category_id == 1 && new_degree_level_id == 2)
	  {
	      $(mgmt_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 filter_education()
{
	var sel_program = $("#program").val();
    var edu_select = $("#prev_education").val();
	var sel_degree = $("option[value='"+sel_program+"']").attr('degree_level_id');

	if (sel_degree == 2) {
		//Empty the education options and replace with a filtered list
		$("select[name='prev_education']").empty();

		full_edu_list.children().each(function () {
			var value = $(this).val();
			if (value > 5) {
				$("select[name='prev_education']").append($(this).clone());
			}
		});
		$("select[name='prev_education']").prepend("<option value='0' selected='selected'>Please select one:</option>");
	}
	else {
		// repopulate
		$("select[name='prev_education']").empty();
		full_edu_list.children().each(function () {
			$("select[name='prev_education']").append($(this).clone());
		});
	}
	$("#prev_education").val(edu_select);
}

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
    });
}

