/**************************************************************

general.js - General Purpose and OnLoad Functions

If you wish to have functionality added onload, you can add the 
appropriate functions to this file and call them in the event 
attaching function below.

we should probably switch all of this code to be a singleton closure
and basically namespace our functions

**************************************************************/

// initialization - setup of Lotsa Helping Hands code

var LHH = window.LHH || {};
	
if (!(LHH.prefs)) {
	LHH.prefs = [];
}

if (!(LHH.community)) {
	LHH.community = '';
}

if (!(LHH.theme)) {
	LHH.theme = 'standard';
}

LHH.css = [];

LHH.css['checkbox-cal-on'] = 'checkbox-cal-on';
LHH.css['checkbox-cal-off'] = 'checkbox-cal-off';

LHH.images = [];

LHH.images['hoverTabLeftImage'] = '/themes/' + LHH['theme'] + '/images/backgrounds/hover-tab-left.jpg';
LHH.images['hoverTabRightImage'] = '/themes/' + LHH['theme'] + '/images/backgrounds/hover-tab-right.jpg';

LHH.images['highlightedTopLeftImage'] = '/themes/' + LHH['theme'] + '/images/backgrounds/highlighted-top-left.gif';
LHH.images['highlightedBottomLeftImage'] = '/themes/' + LHH['theme'] + '/images/backgrounds/highlighted-bottom-left.gif';
LHH.images['highlightedTopRightImage'] = '/themes/' + LHH['theme'] + '/images/backgrounds/highlighted-top-right.gif';
LHH.images['highlightedBottomRightImage'] = '/themes/' + LHH['theme'] + '/images/backgrounds/highlighted-bottom-right.gif';

LHH.formContentChanged = 0;
LHH.formSubmitted = 0;
LHH.submissionInterval = 0;



// function definitions

function setContentChanged() {
	LHH.formContentChanged = 1;	
}

function unsetContentChanged() {
	LHH.formContentChanged = 0;	
}

function focusFirstTextField() {

	// this function focuses on the first text field in the document
	// $('input:text:first').focus(); // (another way to do it, more magical)
	$('form.firstfocus input[type=text]').slice(0,1).focus();

}

function addNavigationHovers() {

	if (window.XMLHttpRequest) { return; } // this code isn't necessary for IE 7, Firefox, Safari and Opera

	var spans = document.getElementsByTagName("SPAN");
		
	var left, right, container;
	
	for (var i = 0; i < spans.length; i++) {
	
		if (spans[i].className == "left-side") {
		
			left = spans[i];
			right = left.childNodes[0];
			container = spans[i].parentNode.parentNode; // the enclosing LI
			
			left.originalBackgroundImage = left.style.backgroundImage;
			right.originalBackgroundImage = right.style.backgroundImage;
			
			container.leftSide = left;
			container.rightSide = right;
			
			container.onmouseover = function() {
				this.leftSide.style.backgroundImage =  'url(' + LHH['images']['hoverTabLeftImage'] + ')';
				this.rightSide.style.backgroundImage = 'url(' + LHH['images']['hoverTabRightImage'] + ')';
			};

			container.onmouseout = function() {
				this.leftSide.style.backgroundImage =  this.leftSide.originalBackgroundImage;
				this.rightSide.style.backgroundImage = this.rightSide.originalBackgroundImage;
			};
		
		}
	
	}

}

function addSectionNavigationHovers() {

	if (window.XMLHttpRequest) { return; } // this code isn't necessary for IE 7, Firefox, Safari and Opera

	var spans = document.getElementsByTagName("SPAN");
		
	var tl, tr, bl, br, container;
	
	for (var i = 0; i < spans.length; i++) {
	
		if (spans[i].className == "top-left" && spans[i].parentNode.className != "softgray") {
		
			tl = spans[i];
			tr = tl.childNodes[0];
			bl = tr.childNodes[0];
			br = bl.childNodes[0];
			container = spans[i].parentNode.parentNode; // the enclosing LI
			
			tl.originalBackgroundImage = tl.style.backgroundImage;
			tr.originalBackgroundImage = tr.style.backgroundImage;
			bl.originalBackgroundImage = bl.style.backgroundImage;
			br.originalBackgroundImage = br.style.backgroundImage;
			
			container.topLeft = tl;
			container.topRight = tr;
			container.bottomLeft = bl;
			container.bottomRight = br;

			container.onmouseover = function() {
				this.topLeft.style.backgroundImage =  'url(' + LHH['images']['highlightedTopLeftImage'] + ')';
				this.topRight.style.backgroundImage = 'url(' + LHH['images']['highlightedTopRightImage'] + ')';
				this.bottomLeft.style.backgroundImage = 'url(' + LHH['images']['highlightedBottomLeftImage'] + ')';
				this.bottomRight.style.backgroundImage = 'url(' + LHH['images']['highlightedBottomRightImage'] + ')';
			};

			container.onmouseout = function() {
				this.topLeft.style.backgroundImage =  this.topLeft.originalBackgroundImage;
				this.topRight.style.backgroundImage = this.topRight.originalBackgroundImage;
				this.bottomLeft.style.backgroundImage = this.topLeft.originalBackgroundImage;
				this.bottomRight.style.backgroundImage = this.bottomRight.originalBackgroundImage;
			};
		
		}
	
	}

}

function addButtonHovers() {

	$(".button-set button").hover(
		function () {
			$(this).addClass("hover");
		}
	,
		function () {
			$(this).removeClass("hover").removeClass("active");
		}
	
	);

	$(".button-set button").mousedown(
		function () {
			$(this).addClass("active");
		}
	,
		function () {
			$(this).removeClass("active");
		}
	
	);

}

function addFormSubmitDisabler() {

	// this function will add disabling to the submit button on submitted forms
	
	$('form').each(
		
		function() {
		
			$(this).submit(
	
				function() {
	
					$(this).find('input[type=submit]').each(
						function() {
							$(this).attr('disabled', 'disabled').css('opacity',0.5);
						}
					);
	
					$(this).find('input[type=image]').each(
						function() {
							$(this).attr('disabled', 'disabled').css('opacity',0.5);
						}
					);
	
					$(this).find('button[type=submit]').each(
						function() {
							$(this).attr('disabled', 'disabled').css('opacity',0.5);
						}
					);
	
				
					// Toggle a form submitted number
					
					formSubmitted = new Date().getTime();

					// Set an Interval every second and check if formSubmitted is > 0 and greater than 10s from now
					submissionInterval = setInterval(
						function() {
							var now = new Date().getTime();
							if (formSubmitted > 0 && (now - formSubmitted) > 10000) {
								enableAllFormSubmits();
								formSubmitted = 0;
								clearInterval(submissionInterval);
							}
						}, 1000
					);

				}
			
			);
		
		}
	
	);

}

function enableAllFormSubmits() {

	// this function will run to avoid issues with user back button presses
	
	$('input[type=submit]').each(
		function() {
			$(this).removeAttr('disabled').css('opacity',1);
		}
	);

	$('input[type=image]').each(
		function() {
			$(this).removeAttr('disabled').css('opacity',1);
		}
	);

	$('button[type=submit]').each(
		function() {
			$(this).removeAttr('disabled').css('opacity',1);
		}
	);

}

function addFormConfirmations() {

	// we will add a change notice if the form is changed
	// since IE won't bubble these changes up, we'll need to 
	// add it to each element therin.

	var saveButtonName = 'SUBMIT';
	
	if (LHH.prefs['show_confirmations'] != 'no') {
	
		$('form.confirm').each(
		
			function() {
			
				$(this).one('change',setContentChanged);
			
				$(this).submit(
					function() {
						window.onbeforeunload = null;
					}
				);
				
				saveButtonName = 'SUBMIT';
				
				$(this).find('input[type=submit]').each(
					function() {
						saveButtonName = $(this).attr('value').toUpperCase();
					}
				);

				$(this).find('input[type=image]').each(
					function() {
						saveButtonName = $(this).attr('alt').toUpperCase();
					}
				);

				$(this).find('button[type=submit]').each(
					function() {
						saveButtonName = $(this).text().toUpperCase();
					}
				);

			}
		
		);
		
		// add the window onunload handler
		window.onbeforeunload = function() {
			if (LHH.formContentChanged > 0) {
				var unloadMessage = LHH.prefs["unload_before_button_text"] + " " + saveButtonName + " " + LHH.prefs["unload_after_button_text"];
				return unloadMessage;
			}
		}

	}

}

function preCacheImages() {

	// configuration
	
	var cachedImages = [];
	
	cachedImages.push(LHH.images['hoverTabLeftImage']);
	cachedImages.push(LHH.images['hoverTabRightImage']);
	cachedImages.push(LHH.images['highlightedTopLeftImage']);
	cachedImages.push(LHH.images['highlightedBottomLeftImage']);
	cachedImages.push(LHH.images['highlightedTopRightImage']);
	cachedImages.push(LHH.images['highlightedBottomRightImage']);
			
	var img = [];

	for (var i = 0; i < cachedImages.length; i++) {
	
		img[i] = new Image();
		img[i].src = cachedImages[i];
	}

}

function help(url) {

	var w = 520; // 750 if ads are served
	var h = 500;
	var x = 0;

	if (screen) {
		x = screen.width - w - 20;
	}
	
	if (typeof(winHelp) == "undefined" || winHelp.closed) {
		winHelp = window.open(url, "help", "scrollbars,resizable,width=" + w + ",height=" + h + ",left=" + x + ",top=10");
	} else {
		winHelp.document.location = url;
	}

	winHelp.focus();

}
	
function displayPopup(element_name, caller) {

	/* this function takes an element_name, determines
	the DOM object for it, determines it's rendered size,
	then displays it, ensuring there is some space between
	the edges of the viewport and the object itself 
	
	caller is the calling element. Ideally, we just put 
	it with it's corner over the caller */
	
	// first close all the popups
	
	//$('#inline-popup-windows.cal-popup').css('visibility', 'visible').css('top', 300).css('left',1050);
	$('#inline-popup-windows .cal-popup').hide();
		
	var $popup = $('#' + element_name);

	var e = document.getElementById(element_name);
	
	// console.log(e.tagName + ':' + e.className + ':' + e.id);

	var t = $(caller).offset().top;
	var l = $(caller).offset().left;

	var w = $popup.width();
	var h = $popup.height();
	
	// now check the viewport size
	
	var vpw = $(window).width() - 25;
	var vph = $(window).height() - 25;

	// get viewport scroll position
	
	var vpst = $(document).scrollTop();
	var vpsl = $(document).scrollLeft();
	
	// the ideal poition is here, 10 pixels up and left of the calendar cell
	
	var et = t - 10;
	var el = l - 10;
	
	// see if our item falls outside of vieport and adjust accordingly
	
	var extra_w = el + w - vpw - vpsl;
	var extra_h = et + h - vph - vpst;
	
	if (extra_w > 0) {
		el = el - extra_w;
	}
	
	if (extra_h > 0) {
		et = et - extra_h;
	}
	
	// now make sure that we're not past the left or top of the screen
	
	if (et < 0) {
		et = 0;
	}
	
	if (el < 0) {
		el = 0;
	}
	
	/*
	// debugging
	console.log('w: ' + w);
	console.log('h: ' + h);
	console.log('t: ' + t);
	console.log('l: ' + l);
	console.log('vpw: ' + vpw);
	console.log('vph: ' + vph);
	console.log('vpsl: ' + vpsl);
	console.log('vpst: ' + vpst);
	console.log('et: ' + et);
	console.log('el: ' + el);
	console.log('extra_w: ' + extra_w);
	console.log('extra_h: ' + extra_h);
	*/
	
	$popup.css('top', et);
	$popup.css('left', el);
	$popup.css('height', h); // because sometimes this is lost after going invisible, then the boxes fall under the sides
	$popup.show();
	
}

function add_confirmation_ticks(base_field, confirm_field, base_tick, confirm_tick) {

	var valid_tick = '&nbsp;<img src="/images/silk-icons/tick.png" alt="/">';
	var invalid_tick = '&nbsp;<img src="/images/silk-icons/cross.png" alt="X">';

	$('#' + base_field).keyup(
		function(e) {
			var current_value = $(this).val();
			if (current_value.length > 0) {
				if (current_value.replace(/^\s+|\s+$/g,"") != "" && simple_email_check(base_field, current_value)) {
					$('#' + base_tick).empty().append(valid_tick);
				} else {
					$('#' + base_tick).empty().append(invalid_tick);
				}
			} else {
				$('#' + base_tick).empty();
			}
			$('#' + confirm_field).keyup();
		}
	);
	
	$('#' + confirm_field).keyup(
		function(e) {
			var current_value = $(this).val();
			if (current_value.length > 0) {
				if (current_value == $('#' + base_field).val()) {
					$('#' + confirm_tick).empty().append(valid_tick);
				} else {
					$('#' + confirm_tick).empty().append(invalid_tick);
				}
			} else {
				$('#' . confirm_tick).empty();
			}
		}
	);
	
	// run once after signin to make sure everything is in the correct state
	$(document).ready(
		function() {
			$('#' + base_field).keyup();
		}
	);

}

function simple_email_check(base_field, current_value) {

	if (base_field == 'ea') {
		if (!current_value.match(/^.+@.+\..+$/)) {
			return false;
		}
	}

	return true;

}


/* General Purpose JavaScript Functions */

function array_search(needle, haystack) {

	if (haystack.length === 0) { return false; }
	
	for (var i = 0; i < haystack.length; i++) {
		if (needle == haystack[i]) { return true; }
	}
	
	return false;

}

function get_field_values_by_name(element_name) {

	// warning... if result is an integer, you'll need to cast it as such
	var these_values = [];
	var element_list = document.getElementsByTagName('input');
	for (var i = 0; i < element_list.length; i++) {
		if (element_list[i].name == element_name && element_list[i].checked==1) {
			these_values[these_values.length] = element_list[i].value;
		}
	}
	return these_values;

}

function get_field_value_by_name(element_name) {

	// warning... if result is an integer, you'll need to cast it as such

	var these_values = get_field_values_by_name(element_name);
	return these_values.join(',');

}


function match_checkboxes(master_id, element_name) {

	// master_name is the "id" of the field you're trying to match
	//    by giving it an id, we don't need to look through the whole object heirarchy
	// element name is the "name" of elements you're trying to change
	
	var master_setting = document.getElementById(master_id).checked;

	var element_list = document.getElementsByTagName('input');
	for (var i = 0; i < element_list.length; i++) {
		if (element_list[i].name == element_name) {
			element_list[i].checked = master_setting;
		}
	}

}

function checkbox_select_all(element_name) {

	$('input[name=' + element_name + ']').attr('checked',1);

}

function checkbox_select_none(element_name) {

	$('input[name=' + element_name + ']').attr('checked',0);

}

function checkbox_select_opposite(element_name) {

	$('input[name=' + element_name + ']').each(

		function() {
			$(this).attr('checked', !$(this).attr('checked'));
		}
	);

}

function get_select_box_value(element_id) {

	var e = document.getElementById(element_id);
	
	return e.options[e.selectedIndex].value;
	
}

function get_text_box_value(element_id) {

	var e = document.getElementById(element_id);
	
	return e.value;
	
}

function set_select_box_value(element_id, element_value) {

	var e = document.getElementById(element_id);
	
	for (var i = 0; i < e.options.length; i++) {
		if (e.options[i].value == element_value) {
			e.selectedIndex=i;
		}
	}

}

function hide_element(element_id) {

	var e = document.getElementById(element_id);
	e.style.display = 'none';	

}

function show_inline_element(element_id) {

	var e = document.getElementById(element_id);
	e.style.display = 'inline';	

}

function show_block_element(element_id) {

	var e = document.getElementById(element_id);
	e.style.display = 'block';	

}

function zero_pad(num, len) {
	var str = num.toString();
	while (str.length < len) {
		str = '0' + str;
	}
	return str;
}


// functions for removing elements

function deleteParent(element) {

	var parent = element.parentNode;
	var grandparent = parent.parentNode;
	grandparent.removeChild(parent);

}

function deleteGrandParent(element) {

	var parent = element.parentNode;
	var grandparent = parent.parentNode;
	var greatgrandparent = grandparent.parentNode;
	greatgrandparent.removeChild(grandparent);

}

function deleteGreatGrandParent(element) {

	var parent = element.parentNode;
	var grandparent = parent.parentNode;
	var greatgrandparent = grandparent.parentNode;
	var greatgreatgrandparent = greatgrandparent.parentNode;
	greatgreatgrandparent.removeChild(greatgrandparent);

}

function deleteGreatGreatGrandParent(element) {

	var parent = element.parentNode;
	var grandparent = parent.parentNode;
	var greatgrandparent = grandparent.parentNode;
	var greatgreatgrandparent = greatgrandparent.parentNode;
	var greatgreatgreatgrandparent = greatgreatgrandparent.parentNode;
	greatgreatgreatgrandparent.removeChild(greatgreatgrandparent);

}

function el(id)
{
	return document.getElementById(id);
}

function graycoord(fieldname,fieldname2)
{
	//
	// called onchange of a select 
	// disable a coordinator's checkbox in the grid of cc coordinators
	//
	var that = el(fieldname);
	if (!that) return; //ie6 can't find "that" when passed as function arg
	
	var matchvalue = that[that.selectedIndex].value;

	var ccs = that.form.elements[fieldname2];

	for(var i=0;i<ccs.length;i++)
	{
		if(!ccs[i]) continue;
		if (matchvalue == ccs[i].value)
			ccs[i].disabled = true;
		else
			ccs[i].disabled = false;
	}
}

$(document).ready(
	function() {
		focusFirstTextField();
		preCacheImages();
		addNavigationHovers();
		addSectionNavigationHovers();
		addFormConfirmations();
		addFormSubmitDisabler();
		addButtonHovers();
	}
);
