$(function()
{
	if ($("#lead_form").is("form"))
	{
		lead_form();
	}
}
);

if (!Array.prototype.indexOf)
{
	Array.prototype.indexOf = function(elt /*, from*/)
	{
		var len = this.length >>> 0;

		var from = Number(arguments[1]) || 0;
		from = (from < 0)
			? Math.ceil(from)
			: Math.floor(from);
		if (from < 0)
		from += len;

		for (; from < len; from++)
		{
		if (from in this &&
			this[from] === elt)
			return from;
		}
		return -1;
	};
}

function lead_form()
{
	if ($.cookie('lead_values'))  {lead_values = unserialize($.cookie('lead_values'));}
	if (lead_values["form_data"]) {reload_cookie_form();}

	initialize_popup(survey_urls[1]);

	//Since we are using javascript
	$('div.q_').hide();
	$('#submit_button').hide();
	$('.app_button').show();
	$('#appStart').css("height","330px");
	$('div.errormsg').hide();

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

	// current div is instantiated at 0 or value of DP get value
	// setting to 0 until value reinstantiation is working as well
	if (true || lead_values["current_div"] == undefined)
	{
		lead_values["current_div"] = 0;
	}
	lead_values["total_div"] = 16;//# of questions(starting 1)
	lead_values["debug"]     = 0;
	lead_values["hidden_q"]  = [ 7,8,9,10,11,12,13,14 ];
	// 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 : '');

	fetch_default_div(lead_values); // get the first screen

	// BACK BUTTON
	//        check which screen we are on, return the screen behind.
	$(".back_button").click(function()
	{
		lead_values["debug"] && alert("current_div is "+lead_values["current_div"]);
		$(".app_button").html("Next");//in case we re-wrote on last page
		$(".app_button").css("width","85px");
		set_current_div(lead_values["current_div"]-1);
	});

	// NEXT BUTTON
	//        validate information entered, if valid, continue to next screen, otherwise, show error
	$(".app_button").click(move_form_forward);

	//For auto step page onchange:
	if (autostep === true) {
		$("#formbox select").change(move_form_forward);
		$("#formbox input:radio:not(.campus_check)").click(move_form_forward);
	}

  // ENTER KEY
  // prevent form submission without validation
	function overrideEnterKey (e) {
		if (e.keyCode === 13) {
			e.preventDefault();
			$('.app_button').click();
		}
	}
	if ($.browser.mozilla) {
		$('#lead_form').keypress(overrideEnterKey);
	}else
	{
		$('#lead_form').keydown(overrideEnterKey);
	}

function move_form_forward()
{
	lead_values["debug"] && alert("current is "+lead_values["current_div"]);

	//validate answer to inputs in the current div

	var valid = true;
	var continue_anyway = 0;

	var validation_message = '';
	if(lead_values["current_div"] == 0){
		valid = false;
		validation_message = "Please choose a category";
		$('.program_category_id').each(
		function(){
			if($(this).attr('checked') == true)
			{
				valid = true;
				//Here we check for teaching / nursing categories
				//so we can toggle those questions from hidden_q array
				//Perhaps an association of which category goes with which
				//question would be better and more maintainable.
				//console.log("Checking "+$(this).attr('name'));
				if ($(this).attr('name') == "cat_3"){
					lead_values["hidden_q"].splice(lead_values["hidden_q"].indexOf(8),1);
					//console.log("Removing 8 from hidden_q");
				}else if ($(this).attr('name') == "cat_7"){
					lead_values["hidden_q"].splice(lead_values["hidden_q"].indexOf(7),1);
					//console.log("Removing 7 from hidden_q");
				}
			}else
			{
				if ($(this).attr('name') == "cat_3" && lead_values["hidden_q"].indexOf(8) == -1){
					lead_values["hidden_q"].push(8);
					//console.log("Adding 8 to hidden_q");
				}else if ($(this).attr('name') == "cat_7" && lead_values["hidden_q"].indexOf(7) == -1){
					lead_values["hidden_q"].push(7);
					//console.log("Adding 7 to hidden_q");
				}
			}
		}
		);
	}else if(lead_values["current_div"] == 1){
		valid = false;
		validation_message = "Please enter your highest level of education completed";
		if($('#prev_education').val() != 0)
		{
			valid = true;
		}
	}else if(lead_values["current_div"] == 2){
		valid = false;
		validation_message = "Please enter the year you obtained your highschool diploma / GED";
		if($('#grad_year option:selected').val() != 0)
		{
			valid = true;
		}
	}else if(lead_values["current_div"] == 3){
		valid = false;
		validation_message = "Please enter your current age";
		if($('#age option:selected').val() != 0)
		{
			valid = true;
		}
	}else if(lead_values["current_div"] == 4){
		valid = false;
		validation_message = "Please enter if you live in the U.S.";
		if($('input[name=live_us]:checked').val())
		{
			valid = true;
		}
	}else if(lead_values["current_div"] == 5){
		valid = false;
		validation_message = "Please enter if you are a U.S. citizen";
		if($('input[name=citizen]:checked').val())
		{
			valid = true;
		}
	}else if(lead_values["current_div"] == 6){
		valid = false;
		validation_message = "Please enter your military affiliation";
		if($('#military option:selected').val() != 0)
		{
			valid = true;
		}
	}else if(lead_values["current_div"] == 7){
		valid = false;
		validation_message = "Please enter your license information";
		if($('input[name=rn_license]:checked').val())
		{
			valid = true;
		}
	}else if(lead_values["current_div"] == 8){
		valid = false;
		validation_message = "Please enter your certificate information";
		if($('input[name=teach_cert]:checked').val())
		{
			valid = true;
		}
	}else if(lead_values["current_div"] == 15){
		valid     = false;
		var test1 = false;
		var test2 = false;
		var test3 = false;

		validation_message = "";

		if (/^((\d{5}-\d{4})|(\d{5}))$/.test($('#zipcode').val()))
		{
			test1 = true;
		}else{
			validation_message += "Please verify your zipcode<br />";
		}
		var email_val = $.trim( $('#email').val() );
		if(/^[A-Za-z0-9%._+-]+@[a-zA-Z0-9-.]+\.[a-zA-Z]{2,4}$/.test(email_val) &&
			/\.com\.com|\.net\.net|\.org\.org|\.edu\.edu$/.test(email_val) === false)
		{
			if (smtp_test_email == true && test1 == true)
			{
				test2 = smtp_validate_email(email_val);
			}
			else
			{
				test2 = true;
			}
		}else
		{
			validation_message += "Please verify your email<br />";
		}
		if (test1 && test2)
		{
			valid = true;
		}
	}

	if(valid == true)
	{
		// If this is last question, submit the form.
		if(valid == true && lead_values["current_div"] == lead_values["total_div"] - 1)
		{
			disable_popup();
			$("#lead_form").submit();
			return true;
		}

		$('#messagebox').html("");
		set_current_div(lead_values["current_div"] + 1);
	}
	else
	{
		// if answer invalid then show message
		$('#messagebox').show();
		$('#messagebox').html(validation_message);
	}
}//End app_buton click handler

function set_current_div(div_id)
{
	//Bounds Check
	if (div_id < 0) { div_id = 0; }
	if (div_id > lead_values["total_div"] - 1) { div_id = lead_values["total_div"] - 1; }

	//Check if div should be hidden
	if (lead_values["hidden_q"].indexOf(div_id) > -1){
		var new_div = lead_values["current_div"] > div_id ? div_id - 1 : div_id + 1;
		set_current_div(new_div);
		return true;
	}

	//Hide Current Div
	$('#q_' + (lead_values["current_div"])).css({display: "none"});
	lead_values["debug"] && alert("Hiding ID: q_"+lead_values["current_div"]);

	//Set New Div
	lead_values["current_div"] = div_id;

	//Fix Progress Bar
	//Notice this is a slightly bad math hack using zip/email page as final unhidden page.
	//Exercise for the reader to figure out why...
	var percent = (lead_values["current_div"]/(lead_values["total_div"]-lead_values["hidden_q"].length))*100;
	if (percent > 100){ percent = 100; }
	$('#prog_bar').css({width: percent.toString()+'%'});

	//Fix Back Button
	if(lead_values["current_div"] > 0)
		$(".back_button").show();
	else
		$(".back_button").hide();

	//Hide message box(new div, new validation)
	$('#messagebox').hide();

	//Store form into cookie
	//cookie_value = serialize(lead_values);
	//$.cookie('lead_values', cookie_value, { path: '/', expires: 10 });

	//Tell server which question user is entering
	ajax_question(lead_values["current_div"]);

	//Show New Div
	$('#q_' + lead_values["current_div"]).css({display: "block"});
	lead_values["debug"] && alert("Showing ID: q_"+lead_values["current_div"]);

	set_popup(survey_urls[1]); //p1aoe
	//Special logic for end of form:
	if(lead_values["current_div"] == lead_values["total_div"] - 1){
		$(".app_button").html("Find My<br>Schools");
		$(".app_button").css("width","110px");
		set_popup(survey_urls[2]); //p1aoe
	}
}

function fetch_default_div(values)
{
	$("#loading_div").fadeIn("fast");

	set_current_div(lead_values["current_div"]);
	do_extras();

	$("#loading_div").fadeOut("fast"); // get rid of the loading div
} // end FETCH DIV

function reload_cookie_form()
{
	return;
}

function do_extras() // this runs all the binders, etc that may need to be refreshed after we fetch a div
{
	phone_fixer();          // if there are phone fields, this will make them behave nicely
	zipcode_fixer();
	process_checkboxes();   // adds behaviour to change the value of checkboxs, because of the way we're saving answers
	tb_init('a.thickbox, area.thickbox, input.thickbox'); //pass where to apply thickbox
	imgLoader = new Image();                              // preload image for the thickbox
	imgLoader.src = tb_pathToImage;                       // more thickbox goodness

}

function custom_function_call(call_function)
{
}

function reset_programs()
{
}

function process_checkboxes()
{
	$("input:checkbox").click(function(){
		if ($(this).val() == 0) { $(this).val("1"); }
		else                    { $(this).val("0"); }
	});
}

function record_heatmap()
{
	$("#container").click(function(e)
	{
		var heatmap_data = {};
		var x = e.pageX - this.offsetLeft;
		var y = e.pageY - this.offsetTop;


		heatmap_data["x_coord"]        = x;
		heatmap_data["y_coord"]        = y;
		heatmap_data["screen_id"]      = lead_values["current_div"];
		heatmap_data["phpsessionid"]   = lead_values["phpsessionid"];
		heatmap_data["record_heatmap"] = 1;
		$.ajax({
			type: "POST",
			url: "/ajax/forms.php",
			data: heatmap_data,
			success: function(){}
		});

	});
}


}//end lead form function


function smtp_validate_email(email)
{
	$.ajax({
		type: "POST",
		url: "/ajax/check_email.php",
		data: "email="+email,
		success: function(msg)
		{
			if (msg == "1")
			{
				disable_popup();
				// append a value to the form, stating that this email is valid
				$('input[name="passed_valid_email"]').val(1);
				$("#lead_form").submit();
				return true;
			}
			else
			{
				$('#email_address_submitted').html(email);
				$('#check_your_email').show("fast");

				$(".continue_anyway").click(function(){
			                disable_popup();
					$("#lead_form").submit();
					$('#check_your_email').hide();
				}
				);

				$(".fix_it").click(function(){
					$("#email").focus().select();
					$('#check_your_email').hide();
				}
				);
				return false;
			}
		}
	});
}

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

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

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 PadDigits(n, totalDigits)
{
	n = n.toString();
	var pd = '';
	if (totalDigits > n.length)    {for (i=0; i < (totalDigits-n.length); i++)    {pd += '0';}}
	return pd + n.toString();
}



