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

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

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

// global browser sniffing

var ua = navigator.userAgent.toLowerCase();

var isOpera = (ua.indexOf('opera') > -1);
var isSafari = (ua.indexOf('safari') > -1);
var isGecko = (!isOpera && !isSafari && ua.indexOf('gecko') > -1);
var isIE = (!isOpera && ua.indexOf('msie') > -1); 
var isIEMac  = (isIE && ua.indexOf('mac') > -1);


// 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['checkbox-cal-on'] = 'checkbox-cal-on';
LHH['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;	


// function definitions

function setContentChanged() {
	LHH['formContentChanged'] = 1;	
}

function unsetContentChanged() {
	LHH['formContentChanged'] = 1;	
}

function focusFirstTextField() {

	// this function focuses on the first text field in the document
	// $('input:text:first').focus(); // (another way to do it, more magical)
	$('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 getSaveButtonName($form) {

	var saveButtonName = 'SUBMIT';

	saveButtonName = $($form).find('input[@type=submit]').attr('value').toUpperCase();

	saveButtonName = $($form).find('input[@type=image]').attr('alt').toUpperCase();
		
	return saveButtonName;

}

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);
			
				if (isIE) {
					$(this).find('input').one('change',setContentChanged);
					$(this).find('select').one('change',setContentChanged);
					$(this).find('textarea').one('change',setContentChanged);
					$(this).find('input[@type=checkbox]').one('change',setContentChanged);
					$(this).find('input[@type=radio]').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();
					}
				);

			}
		
		);
		
		// add the window onunload handler
		window.onbeforeunload = function() {
			if (LHH['formContentChanged'] > 0) {
				var unloadMessage = "You have made changes on this page.  To save those changes, you need to click the " + saveButtonName + " button at the bottom of the page. \n\nIf you press OK now, your changes will be lost.";
				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 hidePopup(e) {
	
	e.style.visibility = 'hidden';

}

function hideAllPopups() {

	// this function will hide all of the popups in inline-popup-windows
	
	var c = document.getElementById('inline-popup-windows');
	
	// find all children that have the cal-popup class
	
	for (var i = 0; i < c.childNodes.length; i++) {
	
		if (c.childNodes[i].className == "cal-popup") {
			
			hidePopup(c.childNodes[i]);
		
		}
	
	}
	
}

function getViewportHeight() {
  var height = self.innerHeight; // Safari, Opera
  var mode = document.compatMode;

  if ( (mode || isIE) && !isOpera ) { // IE, Gecko
	 height = (mode == 'CSS1Compat') ?
		    document.documentElement.clientHeight : // Standards
		    document.body.clientHeight; // Quirks
  }

  return height;
}

function getViewportWidth() {
  var width = self.innerWidth;  // Safari
  var mode = document.compatMode;
  
  if (mode || isIE) { // IE, Gecko, Opera
	 width = (mode == 'CSS1Compat') ?
		    document.documentElement.clientWidth : // Standards
		    document.body.clientWidth; // Quirks
  }
  return width;
}

function findPos(obj) {
	var curleft = 0;
	var curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [curtop,curleft];
}

function getViewportScrollPos() {

	var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
	var scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);

	return [scrollTop, scrollLeft];
	
}

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
	
	hideAllPopups();

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

	var coords = findPos(caller);
	
	var t = coords[0];
	var l = coords[1];

	var w = e.offsetWidth;
	var h = e.offsetHeight;
	
	// now check the viewport size
	
	var vpw = getViewportWidth() - 25;
	var vph = getViewportHeight() - 25;
	
	// get viewport scroll position
	
	var vps = getViewportScrollPos();
	
	var vpst = vps[0];
	var vpsl = vps[1];
	
	// the ideal poition is here
	
	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 with Firefox
	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);
	*/

	e.style.top = et + 'px';
	e.style.left = el + 'px';
	e.style.height = h + 'px'; // because sometimes this is lost after going invisible
	e.style.visibility = 'visible';
	
}

/* General Purpose JavaScript Functions */

function write_to_element(element_id, content) {

	var this_element = document.getElementById(element_id);
	this_element.innerHTML = content;

}

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) {

	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].disabled) {
			element_list[i].checked = 1;
		}
	}

}

function checkbox_select_none(element_name) {

	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 = 0;
		}
	}

}

function checkbox_select_opposite(element_name) {

	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].disabled) {
			element_list[i].checked = !element_list[i].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();
	}
);
