$(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.addMethod("phoneChecker", function(val, element) {
        if( val.length === 0 && this.optional(element) || val.length === 1 ){
        return true;
        }
        // strip non-alphanumeric because phone_fixer() adds "()-"
        val = val.replace(/[^\w]/g, '');

        area_code = val.substr(0,3);
        exchange = val.substr(3,3);

        // Make an ajax call to test the phone number against the db
        return (phone_checker(area_code, exchange) == 1);
    }, "Please enter a working phone number");

    // avoid excessive repetition of a char
    jQuery.validator.addMethod("notLikeXXXX", function(val) {

        var val_len = val.length;
        var last_char = '';
        var seq = 1;
        
        for(var k = 0; k < val.length; k++){
            
            this_char = val.charAt(k);
            if( this_char !== last_char ){
                last_char = this_char;
                seq = 1;
            } else {
                seq++;
                if (seq > 3){
                    return false;
                    break;
                }
            }
        }
        return true;

    }, "Please do not enter fake information.");

    // Real addresses contain numbers and letters
    jQuery.validator.addMethod("realAddress", function(addr) {
        return addr.match(/\d+.+\D+/);
    }, "Please enter a valid address");

    jQuery.validator.addMethod("realName", function(name) {
        if (!name.match(/\btest\b/i)) {
            return true;
        }
    }, "Please correct your name");
    
    jQuery.validator.addMethod("targus", function(name) {
        if ($("input[name='first_name']").val() == '' || $("input[name='last_name']").val() == '' || $("input[name='street_addr']").val() == '' || $("input[name='day_phone']").val() == '')
        {
            return false;
        }

        eid = $("input[name='check_kaptar']").val();

        data = $("#matched_form").serialize();

        // do ajax call with user entered values
        $.ajax({
                url: 'ajax/targus_check.php',
                type: "POST",
                data: data,
                cache: false,
                async:false,
                dataType: "json",
                success: function(data) {
                    bucketlist = $("#schre6").attr("title");

					if (data.bucket == 'A')
					{
						$("option.6progB").remove();
						$("option.6progC").remove();
					}
					
					if (data.bucket == 'B')
					{
						$("option.6progA").remove();
						$("option.6progC").remove();
					}
					
					if (data.bucket == 'C')
					{
						$("option.6progA").remove();
						$("option.6progB").remove();
					}

                    // if associates is in the bucket list and it's on the page, 
                    // check to see if we need to remove
                    if(bucketlist.indexOf("s") != -1 && $("#6og5").length != -1)
                    {
                        bucketkey = "s"+data.bucket;
                        // is the lead's scored bucket in the bucketlist?
                        if(bucketlist.indexOf(bucketkey) == -1)
                        {
                            // not there, so remove kaplan associate's prgorams from the list
                            $("#6og5").remove();
                        }

                    }
                    // if associates is in the bucket list and it's on the page, 
                    // check to see if we need to remove
                    if(bucketlist.indexOf("h") != -1  && $("#6og4").length != -1)
                    {
                        bucketkey = "h"+data.bucket;
                        // is the lead's scored bucket in the bucketlist?
                        if(bucketlist.indexOf(bucketkey) == -1)
                        {
                            // not there, so remove kaplan bachelor's programs from the list
                            $("#6og4").remove();
                        }
                    }
                    // if graduate is in the bucket list and it's on the page, 
                    // check to see if we need to remove
                    if(bucketlist.indexOf("g") != -1  && ($("#6og2").length != -1 || $("#6og8").length != -1))
                    {
                        bucketkey = "g"+data.bucket;
                        // is the lead's scored bucket in the bucketlist?
                        if(bucketlist.indexOf(bucketkey) == -1)
                        {
                            // not there, so remove kaplan masters and certificate programs from the list
                            $("#6og2").remove();
                            $("#6og8").remove();                            
                        }
                    }                   

                    // are we out of optgroups now?  if so, we have to remove the school entirely.
                    if ($(".og-6").length === 0)
                    {
                        $("#schre6").remove();
                    }

                    // was kaplan the only school?
                    if($("div.match_school").length == 0)
                    {
                        // we're out of matches, change up all of page 3
                        $("#schoolbox").children().remove();
                        $("#schoolbox").html("<h3>Thank you for filling out the form!</h3><br /><p style='font-size:12pt;'>A representative will be contacting you shortly to help you in achieving your educational goals.</p>");
                    }
                    $("input[name='check_kaptar']").remove();
                }
            });
                return true;
    }, "");
    
    jQuery.validator.addMethod("ebureau", function(name) {

        // serialize all the values of the form
        data = $("#matched_form").serialize();

        // do ajax call with user entered values
        $.ajax({
                url: 'ajax/eb.php',
                type: "POST",
                data: data,
                cache: false,
                async:false,
                dataType: "json",
                success: function(data) {
                    if (data.passed == true) {
                    // do nothing
                    }
                    else
                    {
                        did_remove = false;
                        // failed ebureau, so remove the schoolbox and start over
                        $('#schoolbox').remove();
                        $("input[name='check_devkel']").remove();
                        
                        did_remove = true;   

                        // get new html
                        getschoolparams = "";
            
                        $.ajax({
                                url: 'ajax/get_schools.php',
                                type: "POST",
                                data: "phpsessionid="+phpsessionid,
                                cache: false,
                                async:false,
                                dataType: "html",
                                success: function(data) {
                                    if (data) {
                                        // put the new html on the page                         
                                        $(data).appendTo('#matched_form');
                                        
                                        // rebind and redo a bunch of stuff so the form works correctly
                                        browser_based_resize()

                                           set_popup(survey_urls[4]); //p3

                                        ajax_question(30);
                                        appStartResize();
                                        set_arrow();

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

                                        $(".int_sel").change(function(){
                                            $("#school_error_message").hide();
                                            set_arrow();
                                        });                                     
                                        
                                         var current_arrow = 1;

                                        bind_school_button();

                                        if (match_first == 'false') {
                                              $("#schoolbox").css({display: "none"});
                                        } else {
                                            $("#infobox").css({display: "none"});
                                        }                                       
                                        
                                    }
                                    else
                                    {
                                        
                                    }
                                }
                                });             
                    }
                }
                });
                
        return true;
    }, "Please be more awesome.");

    jQuery.validator.addMethod("ebureau_eveo", function(name) {

        // serialize all the values of the form
        data = $("#matched_form").serialize();      
        
        // do ajax call with user entered values
        $.ajax({
                url: 'ajax/eb.php',
                type: "POST",
                data: data,
                cache: false,
                async:false,
                dataType: "json",
                success: function(data) {
	
				
                    if (data.test_results == null) {
                    // do nothing
                    }
                    else
                    {
						// shared online not valid
						if (data.test_results.shared.online == false)
						{
                        	$("#online_shared").children("#schre483").remove();	
						}
						// shared campus not valid
						if (data.test_results.shared.campus == false)
						{
                        	$("#campus_shared").children("#schre484").remove();	
						}
						// exclusive campus not valid
						if (data.test_results.exclusive.campus == false)
						{
                        	$("#campus_excl").children("#schre484").remove();
						}
	
                        //failed the testing, so we have to remove the school
                        $("input[name='check_eveo']").remove();

                        if($("#campus_shared").children(".match_school").length == 0)
                        {
                            $("#campus_shared").remove();
						}
						
                        if($("#online_shared").children(".match_school").length == 0)
                        {
                            $("#online_shared").remove();
						}

                        // was everest the only school?
                        if($("div.match_school").length == 0)
                        {
                            // we're out of matches, change up all of page 3
                            $("#schoolbox").children().remove();
                            $("#schoolbox").html("<h3>Thank you for filling out the form!</h3><br /><p style='font-size:12pt;'>A representative will be contacting you shortly to help you in achieving your educational goals.</p>");
                        }                       
                    }
                 }
            });

        return true;
    }, "Please be more awesome.");
    
    jQuery.validator.setDefaults({debug: true});

    var matched_form = $("#matched_form");

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

        // Bind handler to the matched.info-sent event, triggered after contact info 
        // is sent to the server. If we're using a captcha, we run the captcha; if not,
        // we simply trigger the matched.post-info-sent event.
        var senthandler = captcha.useit === true ?
                              function() { matched_form.captchaTest(); } :
                                 function() { $(document).trigger("matched.post-info-sent") };
        $(document)
           .bind("matched.info-sent", senthandler);

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

    bind_school_button();

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

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 = {
        check_devkel: {
            ebureau: true
        },
        check_eveo: {
            ebureau_eveo: true
        },
        check_kaptar: {
            required: false,    
            targus: true
        },
        salutation: {
            required: true,
            min: 1,
            max: 3
        },
        first_name: {
            required: true,
            minlength: 2,
            realName: true,
            notLikeXXXX: true
        },
        last_name: {
            required: true,
            minlength: 2,
            realName: true,
            notLikeXXXX: true
        },
        street_addr: {
            required: true,
            minlength: 2,
            realAddress: true,
            notLikeXXXX: true
        },
        city: {
            required: true,
            minlength: 2
        },
        state: {
            required: true
        },
        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 = {
        salutation:  "Please enter your salutation",
        first_name:  "Please enter your real first name",
        last_name:   "Please enter your real last name",
        street_addr: "Please enter your real 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"
        };
    }

    // When we roll the phonecheck LMI across all LMIs,
    // move this code up into the definitions rather than here
    if (phonecheck) {
        validator_rules.day_phone.phoneChecker =  {
            area_start:0,
            area_len: 3, 
            exch_start:3, 
            exch_len:3
        };

        validator_rules.evening_phone.phoneChecker =  {
            area_start:0,
            area_len: 3, 
            exch_start:3, 
            exch_len:3
        };
    }

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

var appStartResize = function(){
    // make sure #appStart is tall enough to fit its contents
    // fix for IE redraw bug (IE7)

    // don't resize if in a Facebook iframe
    if (fbversion !== "false"){
       return;
    }
    var $appStart = $('#appStart');
    var $wrapper = $appStart.find('> .appStartContentWrapper');
    if( $wrapper.length == 0 ){
        $appStart.wrapInner('<div class="appStartContentWrapper" />');
        $wrapper = $appStart.find('> .appStartContentWrapper');
    }
    if ($appStart.height() < $wrapper.height()) {
        $appStart.height($wrapper.height());
    }
};
$(function(){
    if( $("#matched_form")[0] ){
        appStartResize();
    }
});

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();
            browser_based_resize();
//          ping_eb_standard_verification();
            set_popup(survey_urls[4]); //p3

            // bind post-contact-info behavior 
            $(document).bind("matched.post-info-sent", function(){
               if (match_first == 'false') {
                   ajax_question(30);
                   $("#contact_info").css({display: "none"});
                   $("#messagebox").css({display: "none"});
                   $("#schoolbox").css({display: "block"});
                   $(".submit_disclaimer").css({display: "block"});
                   $("#pixel_school_selection").append(pixel_school_selection);
                   appStartResize();
                   set_arrow();
               }
               else {
                    $("#matched_form").submit();
               }
            });

            // broadcast info-sent event
            $(document).trigger("matched.info-sent");
        }
    });

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

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

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

    var current_arrow = 1;

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

    function ping_eb_standard_verification(){
        data = $("#matched_form").serialize();

        // do ajax call with user entered values
        $.ajax({
                url: 'ajax/eb.php?mn=9',
                type: "POST",
                data: data,
                cache: false,
                async: true,
                dataType: "json",
                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)
{

    var v = $("#matched_form").serialize();

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

function phone_checker(area_code, exchange)
{
    found = 0; 

    $.ajax({
        type: "POST",
        url: "/ajax/phoneChecker.php",
        data: "area_code="+area_code+"&exchange="+exchange,
        async: false,
        success: function(msg){
            found = msg;
        }
    });

    return found;
}

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

    });
}

function set_arrow(degree_list){
    if (catspec !== 'true')
    {
        // First, hide all arrows
        $('.school_arrow').each(function(){
            $(this).css({visibility:"hidden"});
        });

        // Now figure out which arrow to display
        //
        // If the interest questions are displayed on the match page
        // we want to use the arrows to call attention to them
        if ($('.int_sel').is('input') && degree_list)
        {
            $('#arrow_'+degree_list.name).css({visibility:"visible"});
        }
        else
        {
            //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;
            });

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

function bind_school_button()
{
    $("#school_button").click(function(){
         var school_selected = 0;
         var num_offered = 0;
         $(".degree_list").each(function(i){
             if (this.value.match(/_/)){
                 school_selected++;
             }
             num_offered++;
         });
         
         if (school_selected === 0)
         {
             $("#school_error_message").show();
         }
         else
         {
            // if factor min_school_select exists
            // if the user selected fewer schools than min_school_select
            // show an error message and return false
            if (typeof(min_select) !== 'undefined'){
                if (min_select <= num_offered ){ // first make sure that it is possible to comply with our request...
                    if (school_selected < min_select) {
                        $("#school_error_message").html("Please select at least "+min_select+" or more schools to make the most informed decision.");
                        $("#school_error_message").show();
                        return false;
                    }
                }
            }

             $("#school_error_message").hide();
             disable_popup();
            if (match_first == 'false') {
                ajax_question(33);
                 $("#matched_form").submit();
            }
            else {
                ajax_question(20);
                $("#infobox").show();
                $("#schoolbox").hide();
                return false;
            }
         }
    });     
}

jQuery.fn.captchaTest = function(){
   // Hack: clear appStartContentWrapper, 
   //    which breaks form#captcha positioning when present
   (function(wrapper){
      wrapper.replaceWith(wrapper.children());
   })( $("div.appStartContentWrapper") );

   return this.each(function(){
      var target = $(this),
          contextelem = target.parent(),
          // below dimensions are the size of the generated ReCaptcha table
          height = 170,
          width = 320,
          passed = function(){ 
             captchaform.remove();
             target.css({visibility: "visible"});
             $(document).trigger("matched.post-info-sent");
          },
          captchaform = $("<form id='recaptcha'>"
                         +"<h2 class='error' style='display:none;'>Please try again.</h2>"
                         +"<div id='recaptcha-hook'/>"
                         +"<input type='submit' value='Submit'/></form>")
                     .submit(function(event){
                        event.preventDefault();
                        $.ajax({
                           url: "/ajax/recaptcha.php"
                          ,data: $(this).serialize()
                          ,dataType: "json"
                          ,success: function(response){
                             if (!response.valid){
                                $("#recaptcha > .error").show();
                                Recaptcha.create(captcha.pubkey,"recaptcha-hook");
                             } else {
                                passed();
                             }
                          }
                        });
                     })
                     .css({
                        height: height+"px"
                       ,position: "absolute"
                       ,top: Math.max((contextelem.height() - height)/2, 0) + "px"
                       ,left: Math.max((contextelem.width() - width)/2, 0) + "px"
                     })
                     .insertBefore(target);

      target.css({visibility: "hidden"});
      Recaptcha.create(captcha.pubkey,"recaptcha-hook");
   });
}

function browser_based_resize()
{
    jQuery.each(jQuery.browser, function(i, val) {

        if(i=="msie" && catspec !== 'true' && fb_dmz == 'false' &&
            (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");
        }
    });
}

/*
	fraud monitor code
*/

var monitor = {};
var gotit = false;
var rec = false;

var pagename = window.location.pathname.toString();

pagename = pagename.replace(/\//g,"");

	monitor['window'] = {'pagename': encodeURIComponent(pagename), 'mousemove': 0, 'lostfocus': 0};

$(function(){

	  $(document).bind('mousemove', function(){
	  	monitor['window']['mousemove']++;
	  });
	  
	  $(window).bind('blur', function() {
	  	monitor['window']['lostfocus']++;
	  	gotit = true;
	  });
	  
	  // IE EVENTS
	  $(document).bind('focusout', function(){
		if (!gotit) {
		  monitor['window']['lostfocus']++;			
		}
	  });

	
   $(":input").keypress(monitorEvent);

});

function monitorEvent(event) {
	
	var input_name = event.target.name;
	var occurred = new Date();
	var ctrlKey = event.ctrlKey ? 1 : 0;
	
	 if(typeof monitor[input_name] == 'undefined') {
		monitor[input_name] = {"strokes": 1, last: occurred, ctrl: ctrlKey};
	} else {
		monitor[input_name]["strokes"] = monitor[input_name]["strokes"] + 1;
		
		if (ctrlKey && !monitor[input_name]["ctrl"]) { // if it's true now and was false (ie don't flip to false once it has occurred)
			monitor[input_name]["ctrl"] = ctrlKey;
		}
		
		monitor[input_name]["last"] = occurred;
	}

	if (!rec) {
		$(window).unload(function() { saveMonitor(); } );
		rec = true;
	}


}

function saveMonitor() {
	
		var d = "d=" + JSON.stringify(monitor);

		$.ajax({
                url: 'ajax/mtr.php',
                type: "POST",
                data: d,
                cache: false,
                async:false,
                dataType: "json",
                success: function(data) {
                 }
            });
}

