$(document).ready( Setup );

var siblingshown = false;

function Setup()
{
	$("#demosdiv").append( "<p id=\"pleasewait\">Please wait while we gather a list of available classes &hellip;</p>" ); 
	
	Ajax( "IMACSWeb", "demos", { dbname: $("#dbname").val() }, 
		function( xml )
		{
			var demos = $(xml).find( "d" );

			siblingshown = false;

			if ( demos.length > 0 )
			{
				var s = 
					"<div id=\"demolist\">" +
					"<p>To reserve a space, please call IMACS at " + $(xml).find( "info" ).attr( "phone" ) + 
					" or register on-line by clicking on a \"sign-up!\" link below.</p>" +
					"<table id=\"demotable\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">" +
					"<tr class=\"title\"><td>Grades</td><td>Date</td><td>Time</td><td>Location</td><td>&nbsp;</td></tr>";
			
				demos.each(
					function()
					{				
						var	demo = $(this),
							memo = demo.attr( "e" ),
							n = parseInt( demo.attr( "n" ) ),
							maxstudents = parseInt( demo.attr( "m" ) );
								
						s += "<tr>" +
							"<td>" + demo.attr( "g" ).replace( /-/, " &ndash; " ) + "</td>" +
							"<td>" + demo.attr( "d" ) + "</td>" +
							"<td class=\"t\">" + demo.attr( "t" ) + "</td>" +
							"<td>" + demo.attr( "o" ) +
								(memo != null ? "<div><em>" + memo + "</em></div>" : "") +
								"</td>" +
							"<td>" +
								(n >= maxstudents ? "<em>FULL</em>" : "<a href=\"#\" id=\"demo" + demo.attr( "i" ) + "\" class=\"demolink\">Sign up!</a>") +
								"</td>" +
							"</tr>";
					}
				);
				
				s += "</table></div>";
				
				$("#demosdiv")
					.empty()
					.append( s + 
						"<div id=\"registerdiv\"></div>" +
						"<div id=\"afterregisterdiv\"></div>" );
				
				$("#demosdiv .demolink").click(
					function()
					{
						$(this).attr( "id" ).match( /demo(\d+)/ );
						DemoRegister( xml, parseInt( RegExp.$1 ) );
						return false;
					}
				)
			}		
			else
			{
				$("#pleasewait").hide();
				
				$("#demosdiv").append( 
					"<p>For information on free demonstration classes at this location, please call IMACS at <span style=\"white-space:nowrap;\">" + $(xml).find( "info" ).attr( "phone" ) + "</span>.</p>" );
			}			
		},
		function()
		{
			alert( "Please contact IMACS for information on free demonstration classes." );
		} );
}

function DemoRegister( xml, demoid )
{
	var	demo = $(xml).find( "d[i='" + demoid + "']" );
	
	if ( $("#registerdiv").children().size() == 0 )
	{
		$("#registerdiv")
			.append( "<div id=\"whichdemo\"></div>" + 
				"<p>If this is not the class you wish to register for, click " +
				"<a href=\"#\" id=\"backlink\" onclick=\"$('#demolist').show();$('#registerdiv').hide();return false;\">&lt; Back</a>. " +
				"To reserve a space in this class for you and your child, please complete the following form:</p>" +
				$(xml).find( "form" ).text() )
			
		$("#registerdiv .siblinglink").click( 
			function()
			{
				$(".child2").show();
				$(".removesibling").show();
				$(this).hide();
				siblingshown = true;
				return false;
			}
		);
				
		$("#registerdiv .removesibling").click( 
			function()
			{
				$(".child2").hide();
				$(".siblinglink").show();
				$(this).hide();
				siblingshown = false;
				return false;
			}
		);
	}
	else
	{
		$("#registerdiv .removesibling").hide();
		$("#registerdiv .siblinglink").show();
		$(".child2").hide();
	}
	
	$("#registerdiv .submitbutton").unbind( "click" ).click(
		function()
		{
			SubmitForm( demo );
			return false;
		}
	);
		
	$("#whichdemo")
		.empty()
		.append( "<p>You are registering for the free demonstration class at our " +
				"<strong>" + demo.attr( "o" ) + "</strong> location on " +
				"<strong>" + demo.attr( "d" ) + "</strong> at " +
				"<strong>" + demo.attr( "t" ) + "</strong>. " +
				"This class is designed for students in <strong>grades " + demo.attr( "g" ).replace( /-/, " &ndash; " ) + "</strong>.</p>" );
	
	$("#registerdiv").show();
	$("#afterregisterdiv").hide();
	$("#demolist").hide();
}

function SubmitForm( demo )
{
	var data = { demoid: demo.attr( "i" ), dbname: $("#dbname").val() };

	var tocheck = 
	[ 
		[ "email", "your email address" ], 
		[ "firstname", "your first name" ], 
		[ "lastname", "your last name" ],
		[ "addr", "your street address" ],
		[ "city", "your city" ],
		[ "state", "your state" ],
		[ "zip", "your zip code" ],
		[ "phone1", "your area code and phone number" ]
	];
	
	for ( var i = 0 ; i < tocheck.length ; i++ )
	{
		var val = $.trim( $("#" + tocheck[ i ][ 0 ]).val() );
		
		if ( val == "" )
		{
			alert( "Please enter " + tocheck[ i ][ 1 ] + "." );
			$("#" + tocheck[ i ][ 0 ])[ 0 ].scrollIntoView();
			$("#" + tocheck[ i ][ 0 ])[ 0 ].focus();
			return false;
		}
		else
		{
			data[ tocheck[ i ][ 0 ] ] = val;
		}
	}

	if ( !CheckValidEmail( $("#email").val() ) )
	{
		alert( "Please enter your email address in the space provided." );
		$("#email")[ 0 ].focus();
		$("#email")[ 0 ].scrollIntoView();
		return false;
	} 
	
	if ( $("#who1:checked,#who2:checked,#who3:checked").size() == 0 )
	{
		alert( "Please indicate whether you are the mother, father, or guardian." );
		$("#who1")[ 0 ].scrollIntoView();
		$("#who1")[ 0 ].focus();
		return false;
	}
	
	if ( $.trim( $("#sourcenote").val() ) == "" )
	{
		alert( "Please tell us how you heard about IMACS." );
		$("#sourcenote")[ 0 ].scrollIntoView();
		$("#sourcenote")[ 0 ].focus();
		return false;
	}
	
	// check child information
	if ( !CheckChild( data, $("#childinfo tr:not('.child2')"), "1" ) )
		return false;
	
	if ( siblingshown && !CheckChild( data, $("#childinfo tr.child2:visible"), "2" ) ) // visible doesn't seem to work in IE6
		return false;
	
	data[ "who" ] = $("#registerform input[name='who']:checked").val();
	data[ "sourcenote" ] = $("#sourcenote").val();
	data[ "phone2" ] = $("#phone2").val();
	
	var m = location.href.match( /landingid=(\d+)/ );
	if ( m != null )
		data[ "landingid" ] = m[ 1 ];
	
	Ajax( "IMACSWeb", "demoreg", data, 
		function()
		{
			var oldloc = location.href;
				newloc = oldloc.replace( /DemoClasses([A-Z][A-Z]\.htm)/gi, "DemoThankYou$1?demoid=" + demo.attr( "i" ) );
				
			location.href = newloc;
			return false;
		}
	)
}

function CheckChild( data, a, postfix )
{
	if ( a.size() == 0 )
		return true;
		
	var childfirst = a.find( "[name='childfirst']" ),
		childlast = a.find( "[name='childlast']" );
	
	var f = 
	[
		[ childfirst, "first name" ],
		[ childlast, "last name" ]
	];
	
	for ( var i = 0 ; i < f.length ; i++ )
	{
		var val = $.trim( f[ i ][ 0 ].val() );
		if ( val == "" )
		{
			alert( "Please provide the child's " + f[ i ][ 1 ] + "." );
			try
			{
				f[ i ][ 0 ][ 0 ].scrollIntoView();
				f[ i ][ 0 ][ 0 ].focus();
			}
			catch ( e )
			{
			}
			return false;
		}
	}
	
	if ( a.find( "[name='childschool']" ).val() == 0 && $.trim( a.find( "[name='childschoolname']" ).val() ) == "" )
	{
		alert( "Please indicate your child's current school." );
		var schoolselect = a.find( "[name='childschool']" );
		schoolselect[ 0 ].scrollIntoView();
		schoolselect[ 0 ].focus();
		return false;
	} 
	
	data[ "haschild" + postfix ] = "1";
	data[ "childfirst" + postfix ] = childfirst.val();
	data[ "childlast" + postfix ] = childlast.val();
	data[ "childage" + postfix ] = a.find( "[name='childage']" ).val();
	data[ "childgrade" + postfix ] = a.find( "[name='childgrade']" ).val();
	data[ "childgradeyear" + postfix ] = a.find( "[name='childgradeyear']" ).val();
	data[ "childmale" + postfix ] = a.find( "input[name='childmale" + postfix + "']:checked" ).val();
	data[ "childschool" + postfix ] = a.find( "[name='childschool']" ).val();
	data[ "childschoolname" + postfix ] = a.find( "[name='childschoolname']" ).val();
	
	return true;
}

function CheckValidEmail( email )
{
	if ( email == null || $.trim( email ) == "" )
		return false;

	var at = email.indexOf( "@" );		
	
	// must contain @ sign internally
	if ( at <= 0 || at >= (email.length - 1) )
		return false;
		
	// @ must be followed at some point by a period
	if ( email.substr( at ).indexOf( "." ) <= 0 )
		return false;
		
	return true;
}
