
var formChanges = new Array();
var formErrors = 0;

function showUnloadWarning() {
	alert(
		"* * * * * * * * * * * * * * * *\n" +
		"        W A R N I N G !\n" +
		"* * * * * * * * * * * * * * * *\n\n" +
		"Do not use the back button or\n" +
		"refresh this page, or all of your\n" +
		"changes will be lost!\n"
	);
}

function handleResponse(xml, textStatus) {
	formErrors = 0;

	if (xml) {
		var div = $("#formMessages");
		div.html("Your request had some errors, please correct them and retry:<ul></ul>");

		$("errors error", xml).each(function(){
			var message = $("message", this).text();
			var field = $("field", this).text();

			$("ul",div).append("<li>" + message + "</li>");
			$(field).parent().addClass("error");

			formErrors++;
		});

		$("body").focus();
	}
}

function sendChanges() {
	if (formChanges.length == 0) {
//		alert('Please make changes first, then try to submit again.');
		if (typeof(window['CoachesInsiderInterface']) != "undefined" && CoachesInsiderInterface == true) {
			window.location='thankyou.php';
//			window.location='logout.php';
		}
		return;
	}

	$.ajax({
		type: "POST",
		url: "jquery-changes-save.php",
		dataType: "xml",
		data: "changes="+formChanges.join("\n"),
		success: handleResponse,
		complete: function(req, status){
			if (!formErrors) {
				formChanges.length = 0; // sanity

				if (typeof(window['CoachesInsiderInterface']) != "undefined" && CoachesInsiderInterface == true) {
					window.location='thankyou.php';
					//window.location='logout.php';
				}
				else {
					alert("Your changes have been sent for approval.");
					//parent.report_build.runReport("#");
					parent.report_build.loadType(1,1);
				}
			}
		}
	});
}

function updateChanges(revid, approve) {
	$.ajax({
		type: "POST",
		url: "jquery-changes-update.php",
		dataType: "xml",
		data: "RevisionID="+revid+"&Status="+approve,
		success: handleResponse,
		complete: function(req, status){
			if (!formErrors) {
				formChanges.length = 0; // sanity
				if (approve)
					alert("The changes have been approved.");
				else
					alert("The changes have been denied.");
				//parent.report_build.runReport("#");
				parent.report_build.loadType(1,3);
			}
		}
	});
}


function encode64(input) {
	input = escape(input);
	var output = "";
	var chr1, chr2, chr3 = "";
	var enc1, enc2, enc3, enc4 = "";
	var i = 0;

	var keyStr = "ABCDEFGHIJKLMNOP" +
					 "QRSTUVWXYZabcdef" +
					 "ghijklmnopqrstuv" +
					 "wxyz0123456789+/" +
					 "=";

	do {
		chr1 = input.charCodeAt(i++);
		chr2 = input.charCodeAt(i++);
		chr3 = input.charCodeAt(i++);

		enc1 = chr1 >> 2;
		enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
		enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
		enc4 = chr3 & 63;

		if (isNaN(chr2)) {
			enc3 = enc4 = 64;
		} else if (isNaN(chr3)) {
			enc4 = 64;
		}

		output = output +
					keyStr.charAt(enc1) +
					keyStr.charAt(enc2) +
					keyStr.charAt(enc3) +
					keyStr.charAt(enc4);

		chr1 = chr2 = chr3 = "";
		enc1 = enc2 = enc3 = enc4 = "";

	} while (i < input.length);

	return output;
}

function saveChange(tableid, field, change) {
	if (!tableid)
		return;

	var tab = new Array();
	tab = tableid.split('-');

	var cval = new Array(6);
	cval[0] = tab[0]; // table name: Contact or School
	cval[1] = tab[1]; // record id: ID# or "New"
	cval[2] = tab[2];	// school ID
	cval[3] = tab[3]	// position ID
	cval[4] = encodeURIComponent(field);  // field that changed
	cval[5] = encode64(change);	// the value changed

	formChanges.push(cval.join("\t"));
}

function addEventHandlers() {
	$(":input").change(function(e){
		tableid = $(this).parents().eq(3).attr("id");
		if (!tableid)
			tableid = $(this).parents().eq(4).attr("id");

		var field = $(this).attr("name");
		var value = $(this).val();

		// syntax check for emails
		if (field == "Email" || field == "AlternateEmail") {
			if (value == "" || value.match(/^[\w\.\-\+\']+@[\w\.\-]+\.\w{2,4}$/)) {
				$(this).parent().removeClass("error");
			}
			else {
				$(this).parent().addClass("error");
				alert("You must enter a valid email address!");
				return false;
			}
		}

		if (field == "ActualDate") {
			if (value.match(/^\d{4}\-\d{2}\-\d{2}$/)) {
				$(this).parent().removeClass("error");
			}
			else {
				$(this).parent().addClass("error");
				alert("You must enter a valid date!");
				return false;
			}
		}

		if (field == "Phone" || field == "CellPhone" || field == "HomePhone" || field == "AthleticPhone" || field == "OfficePhone" || field == "GirlsPhone" || field == "Fax") {
			if (value == "" || value.match(/^\d{10}$/)) {
				$(this).parent().removeClass("error");
			}
			else {
				$(this).parent().addClass("error");
				alert("You must enter a valid 10-digit phone number");
				return false;
			}
		}

		if (field == "PhoneExt") {
			if (value == "" || value.match(/^\d{0,5}$/)) {
				$(this).parent().removeClass("error");
			}
			else {
				$(this).parent().addClass("error");
				alert("You may enter only up to 5 digits for phone extension");
				return false;
			}
		}
			

		saveChange(tableid, field, value);

		if (typeof(window['CoachesInsiderInterface']) == "undefined" || CoachesInsiderInterface != true)
			$("#formChangesSend").show();

      return true;
   });

	$("#formChangesSend").click(function(e) {
		sendChanges();
		return false;
	});

   $('table.zebrastripe tbody tr:not([th]):odd').addClass('odd');
   $('table.zebrastripe tbody tr:not([th]):even').addClass('even');

	$().keydown(function(e) {
		if (e.keyCode == 8 && e.target.id == '') {
			e.preventDefault();
			return false;
		}
	});

	if (typeof(window['CoachesInsiderInterface']) == "undefined" || CoachesInsiderInterface != true)
		$("#formChangesSend").hide();
//	$("#formMessages").hide();
}

$(document).ready(addEventHandlers);


