// JavaScript Library for Trinity

/*
Table of Contents / Function Names & Parameters
- addLoadEvent(func)
- getElementsByClass(SEARCHCLASS,NODE,TAG)
- removeById(KILLTHIS)
- $() [getElementById shortcut]
- gtags(TAG,NODE) [getElementsByTagName shortcut]
- appendClass(TARGET,NEWCLASS)
- toggleClass(ITEMtoTOGGLE,CLASS1,CLASS2)
- stripeTable()
- stripeAnything(CONTAINER,ITEM,ALTCLASS)
- Lightbox (as external js file - lightBox.js)
- insertAfter(NEWELEMENT,TARGETELEMENT)
- labelHover(WHICHFORM)
- getCookie(name)
- setCookie(name,value,expires,path,domain,secure)
- deleteCookie(name,path,domain)
- collapse()
- basic form validation MULTIPLE FUNCTIONS HERE
	- isFilled()
	- isEmail()
	- prepFormById()
	- SimpleFormValidator()
	- autoFormCheck()
*/




/* Simon Wilson's addLoadEvent - http://simon.incutio.com/archive/2004/05/26/addLoadEvent */
/* Attach more onload functions without worrying about erasing previously applied onload function. */
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}
/* To use:
addLoadEvent(nameOfFunctionToRunOnPageLoad);
addLoadEvent(function() {
  // more code to run on page load 
  thisFunctionHasArguements(foo,bar,suckit);
});
*/




function prepareLinks() {
	if (!document.getElementsByTagName) return false;
	var links = document.getElementsByTagName("a");
	for ( var i=0; i<links.length; i++ ) {
		if (links[i].getAttribute("class") == "popup") {
			links[i].onclick = function() {
				popUp(this.getAttribute("href"));
				return false;
			}
		}
	}
}
function popUp(winURL) {
	window.open(winURL,"popup","width=600,height=480,scrollbars=yes");
}
addLoadEvent(prepareLinks);



//http://www.dustindiaz.com/getelementsbyclass/
function getElementsByClass(SEARCHCLASS,NODE,TAG) {
	var classElements = new Array();
	if ( NODE == null )
		NODE = document;
	if ( TAG == null )
		TAG = '*';
	var els = NODE.getElementsByTagName(TAG);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+SEARCHCLASS+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}




/* Simple remove element function */
function removeById(KILLTHIS) {
	var el = document.getElementById(KILLTHIS);
	el.parentNode.removeChild(el);
}





/* This is a shorthand way to call document.getElementById("foo")  (http://prototype.conio.net) */
function $() {
  var elements = new Array();
  for (var i = 0; i < arguments.length; i++) {
    var element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);
    if (arguments.length == 1)
      return element;
    elements.push(element);
  }
  return elements;
}
/* To use:
	var foo = $("foo"); (finds the element with ID of foo)
/*




/* GP's shorthand function for getElementsByTagName */
function gtags(TAG,NODE) {
	if (NODE == null) 
		NODE = document
	var el = NODE.getElementsByTagName(TAG);
	return el;
}
/* To use:
	var foo = gtags("a"); (finds all the anchor tags on a page)
	var bar = gtags("a",mainDiv); (finds all the anchor tags inside the node collected under the 'mainDiv' variable)
/*






/* GP's appendClass Function */
function appendClass(TARGET,NEWCLASS) {
	var oldClass = TARGET.className;
	if (oldClass == null) { TARGET.className = NEWCLASS; } 
	else { TARGET.className = oldClass + " " + NEWCLASS; }
}




/* GP's toggleClass Function */
function toggleClass(ITEMtoTOGGLE,CLASS1,CLASS2) {
	if (CLASS2 == null) CLASS2 = "";
	if (ITEMtoTOGGLE.className != CLASS1) {
		ITEMtoTOGGLE.className = CLASS1;
	} else {
		ITEMtoTOGGLE.className = CLASS2;
	}
}
/* To use:
	element.onclick = function() {
		toggleClass(this,"oneClass","anotherClass");
	}
	This toggles the elements class from "oneClass" to "anotherClass" every time the 
	element is clicked. If it didnt' have any class to begin with, the element will
	get Class1 first.
*/



function stripeTable() {
	var tables = document.getElementsByTagName("table");
	for (var i=0; i<tables.length; i++) {
		if (tables[i].className.indexOf("stripe") != -1) {
			var target = tables[i];
			var rows = target.getElementsByTagName("tr");
			var counter = 0;
			for (var j=0; j<rows.length; j++) {
				counter = counter + 1;
				if (counter % 2 == 0) { 
					appendClass(rows[j],"altItem");
				}
			}
		}
	}
}
addLoadEvent(stripeTable);
// To use, just apply a class of 'stripe' on the TABLE tag.




// This nifty function will apply a custom class to alternating instances of a tag inside an ID'd parent element.
function stripeAnything(CONTAINER,ITEM,ALTCLASS) {
	var stripeInThis = $(CONTAINER);
	var items = gtags(ITEM,stripeInThis);
	var counter = 0;
	for (var i=0; i<items.length; i++) {
		counter = counter + 1;
		if (counter % 2 == 0) { 
			appendClass(items[i],ALTCLASS);
		}	
	}
}

// To use, see sample below which applies a class of 'altItem' to alternating P tags inside div#stripeThese.
//   addLoadEvent( function() {
//  	  stripeAnything("stripeThese","p","alt2");
//   });



// This imports the Lightbox JavaScript code, which is 400+ lines long.
document.write('<script type="text/javascript" src="http://assets.alachuacounty.us/script/lightBox.js"></script>');



function insertAfter(NEWELEMENT,TARGETELEMENT) {
	var parent = TARGETELEMENT.parentNode;
	if (parent.lastChild == TARGETELEMENT) {
		parent.appendChild(NEWELEMENT);
	} else {
		parent.insertBefore(NEWELEMENT,TARGETELEMENT.nextSibling);
	}
}



function labelHover(WHICHFORM) {
	var forms = gtags("form");
	  var labels = null;
	  var oldClass = null;
	if(WHICHFORM == null) { WHICHFORM = "common"; }
	for (var i=0; i<forms.length; i++) {
		if (forms[i].className.indexOf(WHICHFORM) != -1) {
			labels = gtags("label",forms[i]);
			for (var j=0; j<labels.length; j++) {
				oldClass = labels[j].className;
				labels[j].onmouseover = function() { appendClass(this,"over"); }
				labels[j].onmouseout = function()  { this.className = oldClass; }
			}
		}
	}
}
addLoadEvent(labelHover);
// This script is applied to all forms w/ class of "common" automatically.
// To target a differnt form, use the form's class as the WHICHFORM argument.




// 3 Cookie function from Dustin Diaz that are very useful
// http://www.dustindiaz.com/top-ten-javascript

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 setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}





// Gp's custom XML-style collapsing/expanding list effect - applies to any UL.collapseLists.
// You MUSSSST wrap a span around the text which is clicked to expand a sub-list beneath it.
// You can't apply any classes on the sub-ULs as they are overwritten to show/hide the ULs by the Javascript.
// See http://www.alachuacounty.us/government/depts/epd/natural/waterquality/reports.aspx for an example.
// Need to abstract this thing more....
function collapse() {
	var main = getElementsByClass("collapseLists",$("content"));
	for (i=0; i<main.length; i++) {
		var subs = gtags("ul",main[i]);
		for (var j=0; j<subs.length; j++) { subs[j].className = "dNone"; } // Apply class to uls inside main ul to hide them
		var drops = gtags("span",main[i]); 
		for (var j=0; j<drops.length; j++) { // For each span:
			drops[j].style.cursor = "pointer";
			var img = document.createElement("img");
			img.setAttribute("src","http://www.alachuacounty.us/assets/images/toggle1.gif");
			img.setAttribute("width","12");
			drops[j].insertBefore(img,drops[j].firstChild); // Create an IMG tag for the icon and insert it before the span
			drops[j].onclick = function() {
				// Each time the span is clicked, toggle its sub-UL's class from "dNone"(display:none) to ""(null).
				toggleClass(this.nextSibling.nextSibling,"dNone"); 
			}
		}
	}
}
addLoadEvent(collapse);




// Anything with a class of 'hideLoad' will have it's display set to none (inline style) by this script.
function hideLoad() {
	var elems = getElementsByClass("hideLoad");
	for (var i=0; i<elems.length; i++) {
		elems[i].style.display = "none";
	}
}
addLoadEvent(hideLoad);



function switchBlockNone(elem) {
	if(elem.style.display == "block") {
		elem.style.display = "none";
	} else {
		elem.style.display = "block";
	}
}



/*********************** AJAX SECTION ******************************************/

function stat() {
	if (!getCookie("acstatTrak")) {
		var screenRes = screen.width + "x" + screen.height;
		createXMLHttpRequest();
		xmlHttp.onreadystatechange = function() {
			if (xmlHttp.readyState == 4) {
				if (xmlHttp.status == 200) {
					// if a good response comes back, set cookie.
					setCookie("acstatTrak","Stats recorded",30);
				}
			}
		}
		xmlHttp.open("POST","/acstats.aspx",true);
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
		xmlHttp.send("userRes=" + screenRes);
	}
}
//addLoadEvent(stat); Taken offline on 6/6/2007


function createXMLHttpRequest() {
	if (window.ActiveXObject) {
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	} else if (window.XMLHttpRequest) {
		xmlHttp = new XMLHttpRequest();
	} else {
		//alert("No xmlHttp created.");
	}
}


function AddMostRecentCUIssueButton() {
	//ul#ulComUpIssues li
	createXMLHttpRequest();
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4) {
			if (xmlHttp.status == 200) {
				// if a good response comes back, do some stuff
				// get response
				var d = xmlHttpResponse.Text;
				var findme = "<ul class=\"long\" id=\"ulComUpIssues\"><li><a href=\"";
				var startpos = d.indexOf(findme) + findme.length;
				
			}
		}
	}
}	



/************************ This section is for form validation. ********************/


// This checks to see if an element: (a) has a value and (b) that value is not it's default value.
function isFilled(FIELD) {
	if (FIELD.value.length < 1 || FIELD.value.length == FIELD.defaultValue) { return false; } 
	else { return true; }
}
// This checks to see if an element is a valid email address by the presence of the "@" and "." characters.
function isEmail(FIELD) {
	if(isFilled(FIELD)) {
		if(FIELD.value.indexOf("@") == -1 || FIELD.value.indexOf(".") == -1) {
			return false; 
		} else {
			return true;
		}
	} else {
		return true;
	}
}


// This is used to run a form's results through the common validator here.
function prepFormById(FORMID,USETHISVALIDATOR) {
	var form = $(FORMID);
	if (USETHISVALIDATOR == null) { USETHISVALIDATOR = SimpleFormValidator; }
	form.onsubmit = function() {
		return USETHISVALIDATOR(this);
	}
}
/* To use: 
	prepFormById("submitForm"); (runs form w/ id "submitForm" thru common validator called "SimpleFormValidator")
	prepFormById("userForm","customValidator"); (runs form w/ id "userForm" thru a custom function called "customValidator")
*/	


// This is the simple validator which checks all elements.
// If an element has a class of "required" it checks it via the 'isFilled' function.
// If an element has a class of "email" it checks it via the 'isEmail' function.
// This version uses dialog boxes to alert users to missing elements.
function SimpleFormValidator(WHICHFORM) {
	var stopForm = false;
	for (var i=0; i<WHICHFORM.elements.length; i++) {
		var element = WHICHFORM.elements[i];
		if (element.className.indexOf("required") != -1) {
			if(!isFilled(element)) {
				alert("Please fill in the required field '" + element.name + "'.");
				stopForm = true;
			}
		}
		if (element.className.indexOf("email") != -1) {
			if(!isEmail(element)) {
				alert("Please enter a valid email address in the '" + element.name + "' field.");
				stopForm = true;
			}
		}
	}
	if (stopForm == true) { return false; }
	else { return true; }
}









function autoFormCheck() {
	var forms = gtags("form");
	for (var i=0; i<forms.length; i++) {
		if(forms[i].className.indexOf("common") != -1) {
			forms[i].onsubmit = function() {
				return SimpleFormValidator(this);
			}
		}
	}
}
addLoadEvent(autoFormCheck);


// Jeff's QueryString Object
var QueryString =  {

	keyValuePairs : Array, 
	q : "", 
	init : function () {
		
		this.q = window.location.search;
		if (this.q.length > 1) {
			this.q = this.q.substring(1, this.q.length);
		} else {
			this.q = null;
		}
		this.keyValuePairs = new Array();
		if (this.q) {
			for(var i=0; i < this.q.split("&").length; i++) {
				this.keyValuePairs[i] = this.q.split("&")[i];
			}
		}			
	}, 
	get : function(key) {
		for(var j=0; j < this.keyValuePairs.length; j++) {
			if(this.keyValuePairs[j].split("=")[0] == key)
				return this.keyValuePairs[j].split("=")[1];
		}
		return false;
	},
	toString : function() {return this.q;}, 
	getKeys : function() {
		var a = new Array(this.getLength());
		for(var j=0; j < this.keyValuePairs.length; j++) {
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
		return a;
	}, 
	
	getKeyValuePairs : function() {return this.keyValuePairs;}, 
	getLength : function() {return this.keyValuePairs.length;}		
  
}
QueryString.init();

addLoadEvent(function() {
  QueryString.init();
});





// GP's Modify Class Function
// Specify a target, a class, and whether you want to add that class or remove it.
// Prevents attatching multiple instances of a class to an element.
function changeClass(prmTarget,prmClass,prmAddRemove) {
	if (prmAddRemove==null) prmAddRemove = "add";
	var oldclass = prmTarget.className;
	if (prmAddRemove=="add") {
		if (oldclass=="")
			prmTarget.className = prmClass;
		else if (oldclass.indexOf(prmClass)==-1)
			prmTarget.className += " " + prmClass;
	} 
	else if (prmAddRemove == "remove" && oldclass.indexOf(prmClass)!=-1)
		prmTarget.className = oldclass.replace(prmClass,"");
}



function cleanme() {
	var div = $('ctl00_CPContent_contentDiv');
	var els = div.getElementsByTagName("*");
	for (var i=0; i<els.length; i++) {
		stripStyles(els[i]);
	}
}

function stripStyles(el) {
	//if (el.nodeName == "FONT") {
		el.removeAttribute("face");
		el.removeAttribute("color");
		el.removeAttribute("size");
	//}
	el.removeAttribute("style");
}



function loadNewsButt() {
		//IQT-link
		var area = getElementsByClass("IQT-link", document, "div")[0];
		//console.log(area.innerHTML);
		try {
		    area.innerHTML += "<div class='smallCommUpButtonArea'><a class='a1' href='/government/depts/comm/updatenewsletter.aspx' title='Archive'></a><a class='a2 exclude' href='http://visitor.constantcontact.com/email.jsp?p=oi&m=1102140924401' title='Subscribe'></a></div>";
		}
		catch(err) {}
		
		//console.log(area.innerHTML);
}
addLoadEvent(loadNewsButt);


function readMoreClick(el) {
	el.style.display = "none";
	el.parentNode.getElementsByTagName("p")[0].style.display = "block";
}





