
//	global variable for the timer that fires show/hide of list items / rows
var type_timer;
//	global variable for the timer that fires show/hide of controls
var controls_timer;

/* =from simon willison, http://simon.incutio.com/
--------------------------------------------------------------------- */
function addLoadEvent(func)
{
	var oldonload = window.onload;
	if(typeof window.onload != 'function')
	{
		window.onload = func;
	}
	else
	{
		window.onload = function()
		{
			oldonload();
			func();
		}
	}
}

/* =Written by Jonathan Snook, http://www.snook.ca/jonathan
--------------------------------------------------------------------- */
function getElementsByClassName(node, classname)
{
    var a = [];
    var re = new RegExp('(^| )'+classname+'( |$)');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

/* =cookie stuff
--------------------------------------------------------------------- */
/* ************************************************************************** */ 

function setCookie(name, value, expires, path, domain, secure) {
	var cookie_string = name + "=" + escape(value);  cookie_string +=
	(expires) ? ";expires=" + expires.toGMTString() : "";  cookie_string +=
	(path) ? ";path=" + path : "";  cookie_string += (domain) ? ";domain=" +
	domain : "";  cookie_string += (secure) ? ";secure=" + secure : "";
	
	document.cookie = cookie_string;
}

function getCookie(name) {  
	var start =
	document.cookie.indexOf(name + "=");  var len = start + name.length + 1;
	
	if((!start) && (name != document.cookie.substring(0,name.length)))
	{
	 return null;
	}
	if(start == -1){ return null; }
	
	var end = document.cookie.indexOf(";",len);  if(end == -1){ end =
	document.cookie.length; }
	
	return unescape(document.cookie.substring(len, end)); }

function deleteCookie(name, path, domain) {
   if(getCookie(name))
{
 document.cookie = name + "=" + "";
 document.cookie += ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
 document.cookie += (path) ? ";path=" + path : "";
 document.cookie += (domain) ? ";domain=" + domain : "";  } }

/* ************************************************************************** */

/* =stripe table rows
--------------------------------------------------------------------- */
function stripe_list_items()
{
	var oldLis = $A(document.getElementsByTagName("tr"));
	var lis = oldLis.findAll(function(li){
		return li.parentNode.id == 'list' && li.style.display != 'none';
	});
	
	var color = false;
	
	lis.each(function(li){
		if(color == true)
		{
			Element.addClassName(li, "c");
			color = false;
		}
		else
		{
			Element.removeClassName(li, "c");
			color = true;
		}
	});
}

/* =show/hide list items based on search terms on household view
--------------------------------------------------------------------- */
show_hide_households = Class.create();
show_hide_households.prototype = {
	initialize: function()
	{
		//	global vars
		this.timer;
		//	protections
		if(!$('showHideForm')) return false;
		//	class vars
		this.form = $('showHideForm');
		this.field = $('showHideField');
		this.fieldVal;
		this.content;
		this.events();
	},
	
	events: function()
	{
		this.field.onkeyup = this.delay.bindAsEventListener(this);
	},
	
	delay: function()
	{
		if(!this.timer)
		{
			//	delay the onkeyup event
			this.timer = setTimeout(this.exec.bind(this), 1000);
		}
		//	if the timer variable is set, the above function is in process (in the setTimeout queue)
		//	so, kill that one and start a new one when the user keeps typing
		else
		{
			//	reset the onkeyup event before sending the request to the server
			clearTimeout(this.timer);
			this.timer = setTimeout(this.exec.bind(this), 1000);
		}
	},
	
	exec: function()
	{
		//	get all rows that are children of list
		var oldLis = $A(document.getElementsByTagName("tr"));
		var lis = oldLis.findAll(function(li){
			//	parent is tbody
			return li.parentNode.id == 'list';
		});

		//	make lowercase this.field.value
		this.fieldVal = this.field.value.toLowerCase();
		this.fieldVal = this.fieldVal.replace(/,/g," ");
	
		//	separate all search terms
		var fieldVal_array = this.fieldVal.split(" ");

		for(var i=0; i < lis.length; i++)
		{
			//	make lowercase the list item innerHTML
			var con = lis[i].innerHTML.toLowerCase();			

			var count = 0;
			for(var j=0; j < fieldVal_array.length; j++)
			{
				//	search the innerHTML of each row for the search terms
		 		var search = con.indexOf(fieldVal_array[j]);
	
				//	if there is a match, increment count
				if(search != -1) 
				{
					count++;
				}
			}

			if(count == fieldVal_array.length) 
			{
				lis[i].style.display = "";
			}
			else
			{
				lis[i].style.display = "none";			
			}
		}
		stripe_list_items();
	}
}

/* =ajax form that returns people from the server
--------------------------------------------------------------------- */
build_list = Class.create();
build_list.prototype = {
	initialize: function(){
		this.timer;

		if(!$('searchForm')) return false;

		this.sForm = $('searchForm');
		this.sField = $('searchField');	
		this.defaultValue = 'first or last name';
		this.sField.value = this.defaultValue;
		this.clear = $('clearList');
		this.form_events();
	},

	form_events: function()
	{
		// do not execute without a searchForm on the page
		if(!$('searchForm')) return false;
		//	do not execute without
		//if(!$('clearList')) return false;

		//	hide the default value of the form field when the field is focused
		this.sField.onfocus = this.remove_default.bindAsEventListener(this);
		//	rebuild the default value of the form field when blurred
		this.sField.onblur = this.set_default.bindAsEventListener(this);

		//	bind the onkeyup event to a delay function
		if(this.sField.value != this.defaultValue || this.sField.value)
			this.sField.onkeyup = this.make_delay.bindAsEventListener(this);
		
		//	disable form submit
		this.sForm.onsubmit = function(){return false;}
	},

	remove_default: function()
	{
		//	remove the value when the field is focused, if it matches the default value or in empty
		if(this.sField.value=='' || this.sField.value == this.defaultValue)
		{
			this.sField.value = '';
		}
	},

	set_default: function()
	{
		//	rebuild the default value of the form field when it is blurred, and is null or default at that time
		if(this.sField.value=='' || this.sField.value == this.defaultValue)
		{
			this.sField.value = this.defaultValue;
		}
	},
	
	make_delay: function()
	{
		if(this.sField.value)
		{
				Element.addClassName($(this.sForm.parentNode),'processing');
		}
		if(!this.timer)
		{
			//	delay the onkeyup event
			this.timer = setTimeout(this.make.bind(this), 1000);
		}
		//	if the timer variable is set, the above function is in process (in the setTimeout queue)
		//	so, kill that one and start a new one when the user keeps typing
		else
		{
			//	reset the onkeyup event before sending the request to the server
			clearTimeout(this.timer);
			this.timer = setTimeout(this.make.bind(this), 1000);
		}
	},

	make: function()
	{
		//	build the post var to send to the .php file
		var params = 'searchField=' + this.sField.value;
		//	send the moo ajax, using attributes on the form and form field
		new ajax(this.sForm.action, {postBody: params, update: $(this.sForm.className)});	
		
		Element.removeClassName($(this.sForm.parentNode),'processing');
		if(this.sField.value)
		{
			Element.addClassName($(this.sForm.className),'showingResults');
		}
		else
		{
			Element.removeClassName($(this.sForm.className),'showingResults');
		}
	},
	
	clear_list: function()
	{
//Element.removeClassName($(this.sForm.className),'showingResults');
		$(this.sForm.className).removeChild($(this.sForm.className).lastChild);
		this.sField.value = this.defaultValue;
	}
};

/* =puts nav list items into new containers (CSS moves them around the page)
--------------------------------------------------------------------- */
move_nav = Class.create();
move_nav.prototype = 
{
	//	get all the unique classes in the nav-start container, whihc are classes on the lis
	//	build divs with child uls for each unique class
	//	where there is a match between the class of the li and the class of teh new div, move the li into the ul of the matching div
	//	add each div as the last child of the container

	initialize: function()
	{
		//	define the container
		this.con = $('container');
		//	define the container where nav lives off the server
		this.nav = $('nav-start');

		//	get all the lis in that container to looop through
		this.lis = $A(this.nav.getElementsByTagName("li"));
		//alert(this.classes.inspect());

		//	build divs based on classes
		this.build_divs();
		//	move lis to new divs
		this.add_lis_to_divs();
		//	clean up - remove the nav-start container
		this.nav.parentNode.removeChild(this.nav);
	},

	get_classes: function()
	{		
		//	create the uls object to store class names
		var classes = new Object();
		
		//	get the classes and put them into the uls array
		this.lis.each(function(li){
			classes[li.className] = li.className;
		});

		//	convert the uls hash to a prototype hash
		classes = $H(classes);

		//	return the hash
		return classes;
	},
	
	build_divs: function()
	{
		var classes = this.get_classes();
		//	loop through the hash object
		classes.each(function(c){
			//	get the container again
			var con = $('container');
			//	create a div
			var div = document.createElement("div");
			//	creata a ul for the div
			var newUl = document.createElement("ul");
			
			//	give the new div the class of nav
			div.className = 'nav';
			//	give the new ul the id of the old ul class
			div.id = c.value;
			
			//	append the newUl to the div
			div.appendChild(newUl);
			//	append the div to the container
			con.appendChild(div);			
		});
	},
	
	add_lis_to_divs: function()
	{
		//	put each li that matches the class of the div into the child ul
		this.lis.each(function(li){
			$(li.className).lastChild.appendChild(li);
		});	
	}
}

/* =activate the nav link that represents the page you're on
ADD THIS TO MOVE NAV CLASS?
--------------------------------------------------------------------- */
function activate_links()
{
	var lis = $A(document.getElementsByTagName('li'));
//	var goodForms = forms.findAll(function(goodForm)
	var output = lis.findAll(function(li){
		return li.parentNode.parentNode.className == 'nav';
	});

	//	alert(output.length);
	output.each(function(li){
		if(li.id == document.getElementsByTagName("body")[0].className)
			Element.addClassName(li,'active');
	});

}

/* =compiles form field values in a lightbox
--------------------------------------------------------------------- */
function updater(els)
{

	var arr = '';
	//	var arr = new Array();
	
	for(var x=0; x<els.length; x++)
	{
		//	ding submit and redirect
		if(els[x].name == 'submit' || els[x].name == 'redirect' || els[x].type == 'submit') continue;

		//	only include radios that are checked
		if(els[x].type == 'radio' && els[x].checked != true) continue;

		if(els[x].nodeName == 'FIELDSET' || els[x].type == 'LEGEND') continue;
		//alert(els[x].nodeName);
		//	build arr like a querystring array, so that moo can post and php can access it
		arr += '&' + els[x].name + '=' + els[x].value;	
		//	delete first character
	}
	//	remove the leading ampersand
	arr = arr.substring(1);
	//alert(arr);
	//	return the string
	return arr;
}

/* =handles lightbox form submissions (sends form to a php script that delivers xhr content)
--------------------------------------------------------------------- */
function lb_submit()
{
	if(!$("lightbox")) return false;

	var lightboxs = $('lightbox');

	var forms = $A(lightboxs.getElementsByTagName("form"));

	var goodForms = forms.findAll(function(goodForm)
	{
		return goodForm.className != 'uploadForm';
	});
//	alert(forms.length);
	//	do not process winnow forms, upload forms

	goodForms.each(function(form)
	{
		form.onsubmit = function()
		{
			var formEls = this.elements;
			var arr = updater(formEls);

			//	build params and include the pageId from the querystring (global variable)
			var params = arr;
			
			new ajax(this.action, {postBody: params, update: $(this.name)});
			
			//	hide lightbox
			lightbox.prototype.deactivate();
	
			return false;
		}
	});
}

/* =crawls up from a delete to find the relevant container
--------------------------------------------------------------------- */
function find_container_from_delete_link(el)
{
	//	if class = 'module', return id
	if(Element.hasClassName(el,'house'))
	{
		//	processing($(el));
		return (el.getAttribute('id'));
	}
	else 
	{
		return find_container_from_delete_link(el.parentNode);
	}
}

/* =confirms deletes
--------------------------------------------------------------------- */
function delete_confirm()
{
	if(!document.getElementsByClassName("del")[0]) return false;

	//	find all links with the class of 'del'
	var dels = document.getElementsByClassName("del");

	//	turn the dels array into a prototype array
	dels = $A(dels);
	
	//	loop through the prototype array
	dels.each(function(del)
	{
		del.onclick = function()
		{
			//	confirm the delete, and use the title from the link as context
			Element.addClassName(del,'deleting');
			
			var ok = confirm('Are you sure you want to ' + del.title + '?\nNote: This can NOT be undone.');
			//	if cancelled, kill the action
			if(!ok)
			{
				Element.removeClassName(del,'deleting');
				return false;
			}
	
			//	find the id of the ancestor of the 'del' link with the class of 'module'
			var update = find_container_from_delete_link(del.parentNode);
			//	alert(update);

			new ajax(del.href, {update: $(update)});
			return false;
		}
	});	
}

/* =highlight containers when links are clicked
--------------------------------------------------------------------- */
highlighterxxx = Class.create();
highlighterxxx.prototype = 
{

	initialize: function(el)
	{
		this.links = this.get_links();	
		this.highlight();
	},

	get_links: function()
	{
		//	get all links that are lbOn or del links
		var oldLinks = $A(document.getElementsByTagName("a"));
		var links = oldLinks.findAll(function(link){
			return link.className == 'lbOn' || link.className == 'del';
		});
		return links;
	},
	
	highlight: function()
	{
		this.links.each(function(link){
			//link.onclick = this.highlight2.bindAsEventListener(this);
		});
	},
	
	highlight2: function()
	{
		this.style.color = 'red';
		alert('hi');
	},

	remove_highlight: function()
	{
	}
}

highlighter = Class.create();
highlighter.prototype = 
{

	initialize: function(el)
	{
		//	get to the parent of the xhr image, which is the household li
		this.el = el.parentNode;
		//	define the class for the highlight on the li
		this.label = 'processed';
		//	call the function to highlight the li
		this.highlight();
		//	after a while, remove the highlight
		setTimeout(this.remove_highlight.bind(this), 1000);
	},

	highlight: function()
	{		
		if(!Element.hasClassName(this.el, this.label))
		{
			return Element.addClassName(this.el, this.label);
		}
	},
	
	remove_highlight: function()
	{
			return Element.removeClassName(this.el, this.label);
	}
}

/* =hide row to be deleted so that stripe rows skips over it
--------------------------------------------------------------------- */
function hide_row_to_be_deleted(row)
{
	row.style.display = 'none';
}


/* =move the user down the page to the id of the affected / inserted row
ONLY called on addhousehold.php
--------------------------------------------------------------------- */
function move_down(el)
{

	location.hash = '#h' + el;
}

/* =for IE, make the first .mod container have a right margin of 6%
other browsers use first:child to handle this
--------------------------------------------------------------------- */
function fix_first_mod_right_margin_for_IE()
{
	if(!document.getElementsByClassName("mod")[0]) return false;

	var mods = getElementsByClassName(document, 'mod');
	//alert(mods.length);
	Element.addClassName(mods[mods.length - 1], 'fixRightMarginForIE');
}


/* =functions called by images loaded by XHR on ADMIN pages affected by XHR
--------------------------------------------------------------------- */
function for_xhr_households(el)
{
	//	trigger lightbox
	initialize();	
	delete_confirm();
	stripe_list_items();
/*
	if(el)
	{
		//	pass the xhr image to the highlighter
		new highlighter(el);		
	}
*/
	new show_hide_households();
	$('loader').style.display = 'none';
}

/* =functions called when the lightbox is visible
--------------------------------------------------------------------- */
function for_lightboxes()
{
	lb_submit();
}

/* =functions called when ANY pages are built
--------------------------------------------------------------------- */
function get_list_results()
{
	new build_list();
	new move_nav();	
	activate_links();	
	//	for IE, make the first .mod container have a right margin of 6%
	fix_first_mod_right_margin_for_IE();
}
addLoadEvent(get_list_results);
