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

var item_actions = 'input[value="Trust"], input[value="Don\'t Trust"], input[value="Delete"], input[value="E-Mail"], input[value="Approve"], input[value="Queue"], input[value="Reject"], input[value="Send E-Mail"]';

$(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
	});
	
	elements.each(function() {
		var default_value = 'mm/dd/yyyy';
		
		if ($(this).val() == '') $(this).val(default_value);
		
		$(this).focus(function() {
			if(this.value == default_value) {
				this.value = '';
			}
		});
		$(this).blur(function() {
			if(this.value == '') {
				this.value = default_value;
			}
		});
	});
}

// Time <INPUT>
function timeInput(scope) {
	var elements;
	
	if (scope) {
		elements = $("input.time",scope);
	} else {
		elements = $("input.time");
	}
	
	elements.each(function() {
		var default_value = 'hh:mm';
		
		if ($(this).val() == '') $(this).val(default_value);
		
		$(this).focus(function() {
			if(this.value == default_value) {
				this.value = '';
			}
		});
		$(this).blur(function() {
			if(this.value == '') {
				this.value = default_value;
			}
		});
	});
}

// Create Date Set
function addDate(container,offset) {
	var element;
	var wrapper;
	var c;
	
	// Validate Input
	if (!container) {
		alert("The container ID has not been specified in addDate()");
		return false;
	}
	if (!offset) offset = 0;
	
	// Persistent Count
	if (typeof addDate.counter == "undefined") addDate.counter = offset;
	c = addDate.counter;
	
	// Container by ID
	if (!(element = document.getElementById(container))) {
		alert("The container ID \""+container+"\" specified in addDate() does not exist");
	}
	// Prep HTML
	var source = document.getElementById('date_source').innerHTML;
	source = source.replace(/-_-/g,addDate.counter);
	source = source.replace(/_copy/g,'');

	// Container
	var new_dates = document.createElement('div');
	new_dates.innerHTML = source;

	// Initialize Date/Time Fields
	dateInput(new_dates);
	timeInput(new_dates);
	
	// Add to document
	element.appendChild(new_dates);
	
	addDate.counter = c + 1;
	return false;
}

// Remove Date
function date_remove(id){
	
	var scope = document.getElementById('fieldset_opportunity_occurrence');
	var count = $('div.date_set',scope).length;
	
	// Many Dates
	if (count > 2) {
		$(document.getElementById(id)).remove();
		
	// Only 1 Date
	} else {
		alert('You must have at least one date.');
		//$('a.remove_date').hide();
	}
	
	return false;
}

/*
Setup:
 	Date/Time Input Fields
 	Program/Event Toggle
 */
$(function() {
	dateInput();
	timeInput();
	
	// Program Toggle
	$('input#opportunity_type_program').click(function() {
		if ($(this).attr('checked')) {
			$('div.event').hide();
			$('div.program').show();
			$('div.date_entry').hide();
			$('div.date_entry:first').show();
		}
	});

	// Event Toggle
	$('input#opportunity_type_event').click(function() {
		if (this.checked) {
			$('div.event').show();
			$('div.program').hide();
			$('div.date_entry').show();
		}
	});
});
