$(function(){
    jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
      phone_number = phone_number.replace(/\s+/g, "");
      return this.optional(element) || phone_number.length > 9 &&
        phone_number.match(/^(1-?)?(\([2-9][0-8][0-9]\)|[2-9][0-8][0-9])-?[2-9]\d{2}-?\d{4}$/);
    }, "Please enter a valid phone number");

    /* Validator: Non Repeating
     * To ensure input is not all one alphanumeric character.
     * @param val {string} The form input value
     * @param element {string} The validator element property name
     * @param param {bool|object|array} Accepts a variety of input
     */
    jQuery.validator.addMethod("nonRepeating", function(val, element, params) {
      if( val.length === 0 && this.optional(element) || val.length === 1 ){
        return true;
      }
      // strip non-alphanumeric because phone_fixer() adds "()-"
      val = val.replace(/[^\w]/g, '');
      // make sure params is an array
      if( params.length === undefined ){
        params = [params];
      }
      for(var k = 0; k != params.length; k++){
        var param = params[k],
          start_char = (param.start === undefined) ? 0 : param.start,
          val_length = (param.len === undefined) ? val.length : param.len,
          first_char = val.charAt(start_char),
          valid = false; // reset for each test case

        for(var i=start_char, n = 0+start_char+val_length; i < n; ++i){
          // if only one character is different, it passes
          if( val.charAt(i) !== first_char ){
            valid = true;
            break;
          }
        }
        if( valid ){
          continue;
        }
        return false;
      }
      return true;
    }, "Please enter a non-repeating value");

    jQuery.validator.setDefaults({debug: true});

    if ($("#matched_form").is("form")){
        matched_init();
        matched_validation();

        if (sequential_exclusive) {
            matched_process_sequential_exclusive();
        }
        else if (oneschool) {
            matched_process_oneschool();
        }
        else if(oneschool_fix) {
            matched_process_oneschool_fix();
        }
        else {
            matched_process();
        }
    }

    $("#school_button").click(function(){
        var school_selected = 0;
        $(".degree_list").each(function(i){
            if (this.value.match(/_/)){
                school_selected = 1;
                return false;
            }
            return true;
        });
        if (school_selected === 0)
        {
            //alert("Please select your program choices to continue");
            $("#school_error_message").show();
        }
        else
        {
            $("#school_error_message").hide();
            disable_popup();
			if (match_first == 'false') {
	            $("#matched_form").submit();
			}
			else {
				ajax_question(20);
				$("#infobox").show();
				$("#schoolbox").hide();
				return false;
			}
        }
    });

	if (match_first == 'false') {
	    $("#schoolbox").css({display: "none"});
	} else {
		$("#infobox").css({display: "none"});
	}
});

function matched_init()
{
    $('input[name="jsenabled"]').val(1);

    // 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 : '');


    phone_fixer();
    //dropdown_fixer();

    initialize_popup(survey_urls[3]); // p2

    $("#contact_info").append('<button id="info_button" name="info_button" type="button"></button>');

	if (match_first == 'false') {
		ajax_question(20);
	    $("#info_button").addClass("match_button").append("Match Me<br>Now!");
	} else {
		ajax_question(30);
		$("#info_button").addClass("match_button").append("Send");
	}
}

function matched_validation() {

    var validator_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,
            minlength: 2
        },
        day_phone: {
            required: true,
            phoneUS: true,
            nonRepeating: [
                {start:0, len:3},
                {start:0, len:10},
                {start:3, len:7}
            ]
        },
        evening_phone: {
            phoneUS: true,
            nonRepeating: [
                {start:0, len:3},
                {start:0, len:10},
                {start:3, len:7}
            ]
        },
        start_date: {
            required: true,
            min: -1,
            max: 6
        }
    };

    var validator_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",
        city: "Please enter your city",
        state: "Please enter your state",
        day_phone: {
            required: "Please enter your daytime phone",
            phoneUS:  "Please enter a valid phone number",
            nonRepeating:  "Please enter a valid phone number"
        },
        evening_phone: "Please enter a valid phone number"
    };

    if (require_evening_phone) {
        validator_rules.evening_phone.required = true;
        validator_messages.evening_phone = {
            required: "Please enter your evening phone",
            phoneUS:  "Please enter a valid phone number",
            nonRepeating:  "Please enter a valid phone number"
        };
    }

    $("#matched_form").validate({
        rules: validator_rules,
        messages: validator_messages
    });
}

function matched_process(){
    $("#info_button").click(function(event){
        event.preventDefault();
        if ($("#matched_form").valid()){
        //if (1){
          //Send ajax call to save off contact
            save_contact_info();
            jQuery.each(jQuery.browser, function(i, val) {

                if(i=="msie" && catspec !== 'true' &&
                    (jQuery.browser.version.substr(0,3)=="6.0" ||
                     jQuery.browser.version.substr(0,3)=="7.0" ||
                     jQuery.browser.version.substr(0,3)=="8.0")) {
                        $("div.landing_sidebar").hide();
                        $("#appStart").css("width","auto");
                        $("#schoolbox").css("width","720px");
                        $(".degree_list").css("width","600px");
                        $(".submit_disclaimer").css("width","600px");
                }
            });

            $("#contact_info").css({display: "none"});
            $("#messagebox").css({display: "none"});

            set_popup(survey_urls[4]); //p3

			if (match_first == 'false') {
				ajax_question(30);
				$("#schoolbox").css({display: "block"});
				$(".submit_disclaimer").css({display: "block"});
	            $("#pixel_school_selection").append(pixel_school_selection);
				set_arrow();
			}
			else {
	            $("#matched_form").submit();
			}
        }
    });

	if (match_first == 'true') {
		set_arrow();
	}

    $(".degree_list").change(function(){
		$("#school_error_message").hide();
		set_arrow();
    });

    var current_arrow = 1;

    function set_arrow(){
		if (catspec !== 'true')
		{
        //Assuming each returns in order.
        //If this changes then possible this will break
        var low_arrow = 0;
        $(".degree_list").each(function(i){
            // Since we are passing school id for default option, just check
            // whether there is an underscore. Note this will change if we move
            // to using some unique id for programs rather than io_order_program
            if (!this.value.match(/_/)){
             low_arrow = i+1;
             return false;//to break out of each
            }
            return true;
        });

        $('#arrow'+current_arrow).css({visibility:"hidden"});
        current_arrow = low_arrow;
        $('#arrow'+current_arrow).css({visibility:"visible"});
		}
    }

    function save_contact_info(){
        $.ajax({
            type: "POST",
            url: "/ajax/save_contact.php",
            data: $("#matched_form").serialize(),
            success: function(msg){}
        });
    }
}


function dropdown_fixer(){
  $("select.degree_list").hover(
    function(){
      $(this)
        .data("origWidth", $(this).css("width"))
        .css("width", "auto");
    },
    function(){
      $(this)
        .css("width", $(this).data("origWidth"));
    });
}

function ajax_question(question_id)
{
	$.ajax({
		type: "POST",
		url: "/ajax/set_question.php",
		data: "phpsessionid="+phpsessionid+"&q="+question_id,
		success: function(msg){}
	});
}

function phone_fixer()
{
	/* Notice this function breaks backspace across ) barriers */
	$(".clean_phone").keyup(function(event){
		var ev = $(this).val();
		var o;
		ev = ev.replace(/\D/g,''); // strip out other stuff

		/* quick fix to let them backspace past paren */
		if (event.keyCode == 8 && ev.length == 3){
		ev = ev.replace(/^(\d\d)\d$/,'$1');
		}else if (ev.length >= 3)
		{
			o = '(';
			for(p=0;p<3;p++) {o+=ev.charAt(p);}
			o += ')';

			if (ev.length > 6)
			{
				o += ' ';
				for(p=3;p<6;p++) {o+=ev.charAt(p);}
			}
			else {for(p=3;p<ev.length;p++) {o+=ev.charAt(p);}}

			if (ev.length > 7)
			{
				o += '-';
				for(p=6;p<10;p++) {o+=ev.charAt(p);}
			}
			else {for(p=6;p<ev.length;p++) {o+=ev.charAt(p);}}

		} else { o = ev;}
		$(this).val(o); // return it formatted

	});
}

