// jQuery Functions:
// (Requires style.lib.js)

// input[value="Don\'t Trust"] <-- has to be at the end of the string unless it will crash in IE6 + IE7, jquery does not like the escaped sequence anywhere else
var item_actions = 'input[value="Trust"], input[value="Delete"], input[value="E-Mail"], input[value="Approve"], input[value="Queue"], input[value="Reject"], input[value="Send E-Mail"], input[value="Don\'t Trust"]';

$(function() {
	
	// Program Tooltip
	$("img#program_question, div#program_tooltip_wrapper").hover(
		function () {
			$("div#program_tooltip_wrapper").show();
		},
		function () {
			$("div#program_tooltip_wrapper").hide();
		}
	);

	// Event Tooltip
	$("img#event_question, div#event_tooltip_wrapper").hover(
		function () {
			$("div#event_tooltip_wrapper").show();
		},
		function () {
			$("div#event_tooltip_wrapper").hide();
		}
	);


	// City spaces error
   $("input#organization_city").change(function() {
		if (this.value.split(' ').length >= 4) {
			$(this).parent().addClass('city_error');
			$(this).parent().append('<span id="city_error_text"><strong>NOTE:</strong> The city name entered does not appear to be valid. Please double check the city name and make any necessary corrections. If the city name is correct as is, please click "Continue" again.</span>');
		} else {
			$(this).parent().removeClass('city_error');
			$("span#city_error_text").remove();
		}
	});

	//Email List Function.  Emails all selected email addresses after a button click.  
   $("#emailButton").click(function() {
	var counter = 0;
	var emails = "";
    $('#table_entries tr').each(function() {
    var email = "";
	//Find the email field
	
	if ($(this).find(".email").text().length > 1)
	email = $(this).find(".email").text();
	else
	email = $(this).find(".email").val();
	
	
	var selector = $(this).find(".selector").is(':checked'); //Find the selector and check if its checked

	if (counter >= 1){	
		if (selector==true){
		emails =  email + ', ' + emails;}
	}
	counter = counter + 1;});
	
	emails = emails.trim().chop();

	if (emails.length > 1){
		emails = "mailto:?bcc=" + emails;
		window.open(emails);}
	else 
	alert('Please make a selection.');
	
	counter = 0;
   });

	// Enable item specific buttons
	if ($('tr td input.selector:checked:first').length > 0) {
	 	$(item_actions).removeAttr('disabled');
		//$('input[value="Export All"]').val('Export');

	// Disable item specific buttons
	} else {
		//$(item_actions).attr('disabled','disabled');
		//$('input[value="Export"]').val('Export All');
	}

	// Indicate selected rows
	$('tr td input.selector').each(function () {

			// Selected
			if (this.checked == true) {
				$(this).parent().parent().addClass('selected');
				
			// Unselected
			} else {
				$(this).parent().parent().removeClass('selected');
			}
		})
		.change(function () {

			// Selected
			if (this.checked == true) {
				$(this).parent().parent().addClass('selected');

				// Enable item specific buttons
				$(item_actions).removeAttr('disabled');
				//$('input[value="Export All"]').val('Export');
				
			// Unselected
			} else {
				$(this).parent().parent().removeClass('selected');

				// Enable item specific buttons
				if ($('tr.selected:first').length > 0) {
					$(item_actions).removeAttr('disabled');
					//$('input[value="Export All"]').val('Export');
			
				// Disable item specific buttons
				} else {
					$(item_actions).attr('disabled','disabled');
					//$('input[value="Export"]').val('Export All');
				}
			}
		});

	// Select All button
	$('input#selectAll').click(function () {
		if (this.value == 'Select All') {
			$('tr td input.selector').attr('checked','checked');
			$('tr:has(td input.selector)').addClass('selected');
			$(item_actions).removeAttr('disabled');
			//$('input[value="Export All"]').val('Export');
			this.value = 'Deselect All';
		} else {
			$('tr td input.selector').removeAttr('checked');
			$('tr:has(td input.selector)').removeClass('selected');
			$(item_actions).attr('disabled','disabled');
			//$('input[value="Export"]').val('Export All');
			this.value = 'Select All';
		}
	});
	
});


// Submit form on limit change
$(submitLimit);
function submitLimit(){
	var jInput = $("#limit");
		jInput.change(
				function( objEvent ){
				$("#form_actions").submit();
		}
	);
}

// Submit form on filter change
$(submitFilter);
function submitFilter(){
	$("select#show, select#category").change(function () {
		$("#form_actions").submit();
	});
}

// Form Checking
function checkform(form) {
	var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
	//var timeExp = /^(\d{1,2}):(\d{2})$/;
	
	// Organization
	if (form.id == "form_organization") {

		// Organization Name
		if (form.organization_name.value == '') {
			alert("An Organization Name is required.");
			form.organization_name.focus();
			return false;
		}

		// Zip Code
		if (form.organization_zip.value == '') {
			alert("A Zip Code is required.");
			form.organization_zip.focus();
			return false;
		}

		// Official E-Mail
		if (form.organization_official_email.value == '' || !form.organization_official_email.value.match(emailExp)) {
			alert("A valid Official E-Mail Address is required.");
			form.organization_official_email.focus();
			return false;
		}

		// Password Confirmation
		if (form.user_password && form.user_password.value != '' && form.user_password.value != form.user_password_confirm.value) {
			alert("Please make sure you have confirmed your password correctly.");
			form.user_password.focus();
			return false;
		}
		
		// Extra E-Mails
		if (form.organization_extra_emails.value != '') {
			
			var emails = form.organization_extra_emails.value.split(',');
			for (var i = 0; i < emails.length; i++) {
				emails[i] = emails[i].trim();
				if (!emails[i].match(emailExp)) {
					alert("\""+emails[i]+"\" does not appear to be a valid e-mail address.");
					form.organization_extra_emails.focus();
					return false;
				}
			}
		}
		
		// Demographics
		if (
			parseFloat(form.organization_students_served_asian.value) +
			parseFloat(form.organization_students_served_black.value) +
			parseFloat(form.organization_students_served_hispanic.value) +
			parseFloat(form.organization_students_served_native.value) +
			parseFloat(form.organization_students_served_white.value) > 100
		) {
			alert("Demographics of students served exceeds 100%.");
			form.organization_students_served_black.focus();
			return false;
		}
		
	// Signup
	} else if (form.id == "form_signup") {

		// Organization Name
		if (form.organization_name.value == '') {
			alert("An Organization Name is required.");
			form.organization_name.focus();
			return false;
		}

		// Zip Code
		if (form.organization_zip.value == '') {
			alert("A Zip Code is required.");
			form.organization_zip.focus();
			return false;
		}

		// Official E-Mail
		if (form.organization_official_email.value == '' || !form.organization_official_email.value.match(emailExp)) {
			alert("A valid Official E-Mail Address is required.");
			form.organization_official_email.focus();
			return false;
		}
		
		// Extra E-Mails
		if (form.organization_extra_emails.value != '') {
			
			var emails = form.organization_extra_emails.value.split(',');
			for (var i = 0; i < emails.length; i++) {
				emails[i] = emails[i].trim();
				if (!emails[i].match(emailExp)) {
					alert("\""+emails[i]+"\" does not appear to be a valid e-mail address.");
					form.organization_extra_emails.focus();
					return false;
				}
			}
		}

		// Password Confirmation
		if (form.user_password.value != '' && form.user_password.value != form.user_password_confirm.value) {
			alert("Please make sure you have confirmed your password correctly.");
			form.user_password.focus();
			return false;
		}

		// Terms & Conditions
		if (form.organization_terms.checked != true) {
			alert("You must agree to the terms and conditions before proceeding.");
			form.organization_terms.focus();
			return false;
		}
		
		// Math captcha
		if( form.doMath.value == '' ) {
			alert( "Please do the math." );
			form.doMath.focus();
			return false;
		}
	}

	return true;
}

String.prototype.trim = function() {
   return this.replace(/^\s+|\s+$/g,"");
}

if(!String.chop)
	{String.prototype.chop = _chop;}

//While it might be tempting to use only a RegExp for this method, less greedy pattern matching (i.e. ?) is not implemented in all browsers resulting in untrimmed trailing spaces
	
function _chop(){
	if(this.length==0)
		{return this;}
	
	return this.substring(0,this.length-1);
}

// Date <INPUT>
function dateInput(scope) {
	var elements;
	
	if (scope) {
		elements = $("input.date",scope);
	} else {
		elements = $("input.date");
	}
	
	elements.datepicker({
		'changeMonth': true,
		'changeYear': true
	});
	
}

/*
Setup:
 	Date/Time Input Fields
 	Program/Event Toggle
 */
$(function() {
	
	// Prompt on reset
	$('form').bind('reset',function () {
		var reset = $(':reset',this);
		var message = (reset.attr('title'))? reset.attr('title') : 'Are you sure? All changes will be lost.';
		var redirect;
		
		if (confirm(message)) {
			if (redirect = reset.attr('name')) window.location = redirect;
		} else {
			return false;
		}
	});
	
	// Default to label
	$('input[title!=]')
		.focus(function () {
			if (this.value == this.title) this.value = '';
		})
		.blur(function () {
			if (this.value == '') this.value = this.title;
		})
		.blur();
		
	dateInput();
	
});

