$(function(){

	if ( $("#RegisterFormbox").length > 0 ) {
		registerInit();
	}

	if ( $("#LogosFormbox").length > 0 ) {
		logosformInit();
	}

	if ( $("#Tally").length > 0 ) {
		TallyInit();
	}

	if ( $("#TallyTopStates").length > 0 ) {
		TallyTopStatesInit();
	}

	});

function TallyTopStatesInit() {

	var s = '';
	s += '<h3>';
	s += '<span>Top 10 Schools<br />per State</span>';
	s += '</h3>';

	s += '<ul>';

	s += '<li>';
	s += '<a href="javascript:void(0);" rel="NSW,ACT" class="top-state-active"><span>NSW<br />ACT</span></a>';
	s += '</li>';

	s += '<li>';
	s += '<a href="javascript:void(0);" rel="VIC,TAS"><span>VIC<br />TAS</span></a>';
	s += '</li>';

	s += '<li>';
	s += '<a href="javascript:void(0);" rel="WA"><span class="short">WA</span></a>';
	s += '</li>';

	s += '<li>';
	s += '<a href="javascript:void(0);" rel="QLD"><span class="short">QLD</span></a>';
	s += '</li>';

	s += '<li>';
	s += '<a href="javascript:void(0);" rel="SA,NT"><span>SA<br />NT</span></a>';
	s += '</li>';

	s += '</ul>';
	
	s += '<div class="clear"></div>';
	s += '<div id="TallyTopStatesDataset"></div>';

	$('#TallyTopStates').html(s);

	$('#TallyTopStates a').click( function () {
			$('#TallyTopStates a').removeClass( 'top-state-active' );
			$(this).blur();
			$("#TallyTopStatesDataset").load("/competition/__top?q=" + $(this).attr('rel') );
			$(this).addClass( 'top-state-active' );
		});

	$("#TallyTopStatesDataset").load("/competition/__top?q=NSW,ACT" );

}

function TallyInit() {

	var searchDefault = 'Enter School Name or Postcode';

	var s = '';
	s += "\n";
// 	s += '<div class="formbox">' + "\n";

	s += '<div id="TallyTitle">';
	s += '<span>School Ranking</span>';
	s += '</div>' + "\n";
	
	s += '<div id="searchbox">' + "\n";
	s += '<form action="" method="post" id="searchForm">' + "\n";
	s += '<input type="text" name="search" id="search" value="' + searchDefault + '" class="search-prompt" />' + "\n";
	s += '<input type="submit" id="search-submit" value="Search" />' + "\n";
	s += '<input type="hidden" name="search_id" id="search_id" value="" />' + "\n";
	s += '<input type="hidden" name="tally_base" id="tally_base" value="0" />' + "\n";
	s += '</form>' + "\n";
	s += '</div>' + "\n";
	s += '<div class="clear"></div>' + "\n";

	s += '<div id="TallyDataset">' + "\n";
	s += '</div>' + "\n";

// 	s += '</div>' + "\n";

	$('#Tally').html(s);

	$("#searchForm").submit( function ( event ) {
			TallyPopulate();
			event.preventDefault();  
		});

	$("#search-submit").click( function ( event ) {
			$(this).blur();
			if ( $('#search').val() == searchDefault ) {
				return false;
			}
			$('#search_id').val( $('#search').val() );
			TallyPopulate();
			return false;
		});

	$("#search").focus( function () {
			if  ( $(this).val() == searchDefault ) {
				$(this).val('');
				$(this).removeClass('search-prompt');
			} else {
				$(this).select();
			}
		});

	$("#search").blur( function () {
			if  ( $(this).val() == searchDefault || $(this).val() == '' ) {
				$(this).val( searchDefault );
				$(this).addClass('search-prompt');
			}
			$(this).select();
		});

	$("#search").autocomplete("/competition/__search", { minChars:2, onItemSelect: selectSearch } );
	TallyPopulate();

}



function selectSearch(li) {

	$('#tally_base').val('0');

	if ( li.length == 0 ) {
		return false;
	}

	if ( ! li.extra ) {
		return false;
	}

 	$('#search_id').val( li.extra[0] );
 	TallyPopulate();

}

function TallyPopulate() {

 	var q = $('#search_id').val();

	$('#TallyPager a').unbind('click');

	var base = $('#tally_base').val();
	var url = false;

	if ( q != '' ) {
		q = q.split(' ').join ('%20');
		url = "/competition/__tally?q=" + q + '&base=' + base;
	} else {
		url = "/competition/__tally?q=top" + '&base=' + base;
	}

	$("#TallyDataset").load( url, false, function() {
			$('#TallyPager a').click ( function() { 
					$('#tally_base').val( $(this).attr('rel') ); 
					TallyPopulate(); 
					return false;
				});
		});

}


function registerInit() {

	var s = '';
	s += "\n";
	s += '<div id="RegisterForm">' + "\n";
	s += '<div class="formbox">' + "\n";

	s += '<h3>' + "\n";
	s += 'Registration Form' + "\n";
	s += '</h3>' + "\n";


	s += '<p>';
	s += 'For New Zealand registration <a href="http://sunricedifference.co.nz">click here</a><br />' + "\n";
	s += '<br />Please fill in all the fields in the form</p>' + "\n";

	s += '<form action="" method="post">' + "\n";

	s += '<p>' + "\n";
	s += '<label for="email">Your Email</label>' + "\n";
	s += '<input type="text" name="email" id="email" />' + "\n";
	s += '<span id="email-error"></span>' + "\n";
	s += '</p>' + "\n";

	s += 'You will use this email address and the password you select to log in.' + "\n";
	s += '<div class="clear"></div>' + "\n";


	s += '<p>' + "\n";
	s += '<label for="password">Choose Password</label>' + "\n";
	s += '<input type="password" name="password" id="password" size="8" />' + "\n";
	s += '<span id="password-error"></span>' + "\n";
	s += '</p>' + "\n";
	s += '<div class="clear"></div>' + "\n";

	s += '<p>' + "\n";
	s += '<label for="password_confirm">Confirm Password</label>' + "\n";
	s += '<input type="password" name="password_confirm" id="password_confirm" size="8" />' + "\n";
	s += '<span id="password_confirm-error"></span>' + "\n";
	s += '</p>' + "\n";
	s += '<div class="clear"></div>' + "\n";

	s += '<p>' + "\n";
	s += '<label for="name_first">First Name</label>' + "\n";
	s += '<input type="text" name="name_first" id="name_first" />' + "\n";
	s += '<span id="name_first-error"></span>' + "\n";
	s += '</p>' + "\n";
	s += '<div class="clear"></div>' + "\n";

	s += '<p>' + "\n";
	s += '<label for="name_last">Last Name</label>' + "\n";
	s += '<input type="text" name="name_last" id="name_last" />' + "\n";
	s += '<span id="name_last-error"></span>' + "\n";
	s += '</p>' + "\n";
	s += '<div class="clear"></div>' + "\n";

// 	s += '<p>' + "\n";
// 	s += '<label for="school_postcode">School Postcode</label>' + "\n";
// 	s += '<input type="text" name="school_postcode" id="school_postcode" size="4" maxlength="4" />' + "\n";
// 	s += '<span id="school_postcode-error"></span>' + "\n";
// 	s += '</p>' + "\n";
// 	s += '<div class="clear"></div>' + "\n";

	s += '<p>' + "\n";
	s += '<label for="school_title">School Name</label>' + "\n";
	s += '<input type="text" name="school_title" id="school_title" />' + "\n";
	s += '<span id="school_title-error"></span>' + "\n";
	s += '</p>' + "\n";

	s += 'If you can\'t find your school, please <a href="/contact">Click Here</a>' + "\n";

	s += '<div class="clear"></div>' + "\n";


	s += '<p>' + "\n";
	s += '<label for="school_population">Number of Pupils</label>' + "\n";
	s += '<input type="text" name="school_population" id="school_population" />' + "\n";
	s += '<span id="school-population-error"></span>' + "\n";
	s += '</p>' + "\n";
	s += '<div class="clear"></div>' + "\n";

	s += '<p>' + "\n";
	s += '<label for=""></label>' + "\n";
	s += '<input type="image" src="/images/register.png" style="bordeR: 0;" id="RegisterSubmit" value="Register" />' + "\n";
	s += '</p>' + "\n";
	s += '<br />' + "\n";
	s += '<input type="hidden" name="school_id" id="school_id" value="" />' + "\n";

	s += '</form>' + "\n";
	s += '</div>' + "\n";
	s += '</div>' + "\n";

	s += '<div id="RegisterProcessing">' + "\n";
	s += '<span>Submitting your details...</span>' + "\n";
	s += '</div>' + "\n";

	s += '<div id="RegisterProcessed">' + "\n";
	s += '<br />' + "\n";
	s += '<h3>Your registration is complete</h3>' + "\n";
	s += '<h4>thank you for participating!</h4>' + "\n";
	s += '</div>' + "\n";

	$('#RegisterFormbox').html(s);
	$('#email').blur( function () { registerEmailRegisteredCheck(); return false; });
	$('#email-reason').show();
	$("#school_title").autocomplete("/competition/__school", { minChars:3, onItemSelect: selectSchool } );
	$('#school_title').blur( function () { validateSchoolAvailable(); });
	$('#RegisterSubmit').click( function () { $(this).blur(); registerFormProcess(); return false; });
	$('#email').focus();

	$('#school_population').bind( 'keypress', function ( evt ) { 
			var charCode = (evt.which) ? evt.which : window.event.keyCode; 
			return ( charCode <= 13 || ( charCode >= 48 && charCode <= 57 ) );
		});

}

function selectSchool(li) {

	if ( li.length == 0 ) {
		return false;
	}

	if ( ! li.extra ) {
		return false;
	}

	$('#school_id').val( li.extra[0] );
	validateSchoolAvailable();

}

function validateSchoolAvailable() {

	var school_id = $('#school_id').val();
	
    if ( ! $('#school_id').val() ) {
        $('#school_title').addClass( 'invalid' );
        $('#school_title').focus();
		$('#school_title-error').html('Please select a school');
		$('#school_title-error').show();
        return false;
	}

	var request = {
		m: 'competition',
		rpc: 'school_registered',
		school_id: school_id
	};

	$.get( '/index.php', request, function ( response ) {
			if ( '1' == response ) {
				$('#school_title').addClass( 'invalid' );
				$('#school_title-error').html('This school is already registered');
				$('#school_title-error').show();
				$('#school_id').val( '' );
			} else {
				$('#school_title').removeClass( 'invalid' );
				$('#school_title-error').html('');
				$('#school_title-error').hide();
			}
		});

}

function registerFormProcess () {

    if ( ! registerFormValidate() ) {
        return false;
    }

    var request = {
        m: 'competition',
        rpc: 'register_process',
        name_first: $('#name_first').val(),
        name_last: $('#name_last').val(),
        password: $('#password').val(),
        email: $('#email').val(),
        school_id: $('#school_id').val(),
        population: $('#school_population').val()
    };

	$('#RegisterForm').fadeOut( 250, function() {
			$('#RegisterProcessing').fadeIn( 250, function () {
					$.post( '/index.php', request, function ( response ) {
							$('#RegisterProcessing').fadeOut( function () {
									$('#RegisterProcessed').fadeIn();
								});
						});
				});
			return false;
		});
	
}

function registerEmailRegisteredCheck () {

	var email = $('#email').val();

    if ( ! email ) {
        return false;
    }

    var request = {
        m: 'competition',
        rpc: 'email_registered',
        email: email
    };

	$.get( '/index.php', request, function ( response ) {
			if ( '1' == response ) {
				$('#email-error').html('That email address is already registered');
				$('#email-error').show();
			} else {
				$('#email-error').html('');
				$('#email-error').hide();
			}
		});


}

function registerFormValidate () {

    var valid = true;

    if ( ! $('#school_population').val() ) {
        $('#school_population').addClass( 'invalid' );
        $('#school_population').focus();
        valid = false;
    } else {
        $('#school_population').removeClass( 'invalid' );
    }

    if ( ! $('#school_id').val() ) {
        $('#school_title').addClass( 'invalid' );
        $('#school_title').focus();
		$('#school_title-error').html('Please select a school');
		$('#school_title-error').show();
        valid = false;
    } else {
        $('#school_title').removeClass( 'invalid' );
		$('#school_title-error').html('');
		$('#school_title-error').hide();
		validateSchoolAvailable();
    }

    if ( ! $('#name_last').val() ) {
        $('#name_last').addClass( 'invalid' );
        $('#name_last').focus();
        valid = false;
    } else {
        $('#name_last').removeClass( 'invalid' );
    }

    if ( ! $('#name_first').val() ) {
        $('#name_first').addClass( 'invalid' );
        $('#name_first').focus();
        valid = false;
    } else {
        $('#name_first').removeClass( 'invalid' );
    }

    if ( ! $('#password_confirm').val() || $('#password_confirm').val() != $('#password').val() ) {
        $('#password_confirm').addClass( 'invalid' );
        $('#password_confirm').focus();
        valid = false;
    } else {
        $('#password_confirm').removeClass( 'invalid' );
    }

    if ( ! $('#password').val() ) {
        $('#password').addClass( 'invalid' );
        $('#password').focus();
        valid = false;
    } else {
        $('#password').removeClass( 'invalid' );
    }

    if ( ! $('#email').val() || ! validateEmail ( $('#email').val() ) ) {
        $('#email').addClass( 'invalid' );
        $('#email').focus();
        valid = false;
    } else {
        $('#email').removeClass( 'invalid' );
    }

    return valid;

}






function logosformInit() {

	var s = '';
	s += "\n";
	s += '<div id="logosForm">' + "\n";
	s += '<div class="formbox">' + "\n";
	s += '<form action="" method="post">' + "\n";

	s += '<h3>' + "\n";
	s += 'Enter your Logos' + "\n";
	s += '</h3>' + "\n";

	s += 'For New Zealand promotion <a href="#">click here</a>' + "\n";

	s += '<p>' + "\n";
	s += '<label for="email">Your Email</label>' + "\n";
	s += '<input type="text" name="email" id="email" />' + "\n";
	s += '<span id="email-error"></span>' + "\n";
	s += '</p>' + "\n";
	s += '<div class="clear"></div>' + "\n";

	s += '<p>' + "\n";
	s += '<label for="password">Password</label>' + "\n";
	s += '<input type="password" name="password" id="password" size="8" />' + "\n";
	s += '<span id="password-error"></span>' + "\n";
	s += '</p>' + "\n";
	s += '<div class="clear"></div>' + "\n";

	s += '<p>' + "\n";
	s += '<label for="logos">Number of Logos collected</label>' + "\n";
	s += '<input type="text" name="logos" id="logos" />' + "\n";
	s += '<span id="logos-error"></span>' + "\n";
	s += '</p>' + "\n";
	s += '<div class="clear"></div>' + "\n";

	s += '<p>' + "\n";
	s += '<label for=""></label>' + "\n";
	s += '<input type="button" name="email" id="LogosSubmit" value="Submit" />' + "\n";
	s += '<span id="LogosSubmitProcessing"><span>Logging In...</span></span>' + "\n";
	s += '</p>' + "\n";

	s += '<div id="logosForm-error"></div>' + "\n";

	s += '</form>' + "\n";
	s += '</div>' + "\n";
	s += '</div>' + "\n";

	s += '<div id="LogosProcessing">' + "\n";
	s += '<span>Submitting your details...</span>' + "\n";
	s += '</div>' + "\n";

	s += '<div id="LogosProcessed">' + "\n";
	s += '<br />' + "\n";
	s += '<h3>Logo Submission Saved</h3>' + "\n";
	s += '</div>' + "\n";

	$('#LogosFormbox').html(s);
	$('#LogosSubmit').click( function () { $(this).blur(); logosFormProcess(); return false; });
	$('#logos').bind( 'keypress', function ( evt ) { 
			var charCode = (evt.which) ? evt.which : window.event.keyCode; 
			return ( charCode <= 13 || ( charCode >= 48 && charCode <= 57 ) );
		});
	$('#email').focus();

}

function logosFormProcess () {

    if ( ! logosFormValidate() ) {
        return false;
    }

    var request = {
        m: 'competition',
        rpc: 'logos_process',
        email: $('#email').val(),
        password: $('#password').val(),
        logos: $('#logos').val()
    };

	// validate username / password

	$('#LogosSubmit').fadeOut( 250, function() {
			$('#LogosSubmitProcessing').fadeIn( 250, function () {
					$.post( '/index.php', request, function ( response ) {
							if ( '1' == response ) {
								// OK
								$('#logosForm').fadeOut ( 250, function () {
										$('#LogosProcessed').show();
										$('#LogosProcessed').fadeOut( 3000, function () { logosformInit(); });
									});
							} else {
								// bad login
								$('#logosForm-error').html( response );
								$('#LogosSubmitProcessing').hide();
								$('#LogosSubmit').show();
								$('#password').addClass( 'invalid' );
								$('#password').focus();
							}
						});
				});
		});
	
}

function logosFormValidate () {

    var valid = true;

	$('#logosForm-error').html( '' );

    if ( ! $('#logos').val() ) {
        $('#logos').addClass( 'invalid' );
        $('#logos').focus();
        valid = false;
    } else {
        $('#logos').removeClass( 'invalid' );
    }

    if ( ! $('#password').val() ) {
        $('#password').addClass( 'invalid' );
        $('#password').focus();
        valid = false;
    } else {
        $('#password').removeClass( 'invalid' );
    }

    if ( ! $('#email').val() || ! validateEmail ( $('#email').val() ) ) {
        $('#email').addClass( 'invalid' );
        $('#email').focus();
        valid = false;
    } else {
        $('#email').removeClass( 'invalid' );
    }

    return valid;

}



function validateEmail(str) {

    var at="@";
    var dot=".";
    var lat=str.indexOf(at);
    var lstr=str.length;
    var ldot=str.indexOf(dot);
    if (str.indexOf(at)==-1) {
        return false;
    }

    if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) {
        return false;
    }

    if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) {
        return false;
    }

    if (str.indexOf(at,(lat+1))!=-1) {
        return false;
    }

    if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) {
        return false;
    }

    if (str.indexOf(dot,(lat+2))==-1) {
        return false;
    }

    if (str.indexOf(" ") != -1) {
        return false;
    }

    return true;
}

function log ( s ) {
	if ( $('#log').length == 0 ) {
		$('#background').prepend('<div id="log" style="background: #fc0;">-</div>');
	}
	$('#log').html(s);
}
