/****************************************************************
*
*	Atlanta Falcons Javascript Library
*	Author: Michael Turnwall - Digitaria Inc.
*	Created: 5.03.2007
*	Various fuctions
*
****************************************************************/


//onload function written by Simon Willison - http://simon.incutio.com
// use this function instead of window.onload - usage addLoadEvent(functionName) or addLoadEvent(function(){ some code;} )
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}
// end addLoadEvent()
/*----------------------*/

// function that allows getting elements by their class name. Returns the found elements in an array
// arguments: className - class name to search for, element - a starting point to start the search
// if no element is specified, all the nodes on the page are searched
document.getElementsByClassName = function(className,element)
{
	if(element)
	{
		var el = document.getElementById(element);
		var children = el.getElementsByTagName('*');
	}
	else
	{
		var children = document.getElementsByTagName('*') || document.all;
	}
	
	var elements = [];
	var regexp = new RegExp(className,"ig");
	for(i = 0; i < children.length; i++)
	{
		if(children[i].className.match(regexp))
			elements.push(children[i]);
	}
	if(elements.length > 0)
		return elements;
	else
		return false;
}
/*----------------------*/


function setOpacity(obj, opacity)
{
	// check first if the object even exists
	if(!obj)
		return false;
	opacity = (opacity == 100)?99.999:opacity;
	
	// IE/Win
	obj.style.filter = "alpha(opacity:"+opacity+")";
	
	// Safari < 1.2, Konqueror
	obj.style.KHTMLOpacity = opacity/100;
	
	// Older Mozilla and Firefox
	obj.style.MozOpacity = opacity/100;
	
	// Safari 1.2, newer Firefox and Mozilla, CSS3
	obj.style.opacity = opacity/100;
}
/*----------------------*/

// opacity is the starting opacity
var fadeInTimer;
function fadeIn(objId,opacity,target,speed,callback)
{
	clearTimeout(fadeInTimer);
	obj = document.getElementById(objId);
	if (document.getElementById && obj)
	{
		if (opacity <= target)
		{
			setOpacity(obj, opacity);
			opacity += 10;
			fadeInTimer = window.setTimeout("fadeIn('"+objId+"',"+opacity+","+target+","+speed+","+callback+")", speed);
		}
		else
		{
			// time to remove the loading graphic from the background
			// do this because in Firefox, the loading graphic eats up a lot of cpu time when something covers it *shrug*
			/*
			var parent = obj.parentNode;
			if(parent && parent.nodeType == 1)
			{
				if(parent.style.backgroundImage != "url()")
					parent.style.backgroundImage = "url()";
			}*/
			if(typeof callback == "function")
				callback();
		}
	}
}
/*----------------------*/


// id of element to fade, final opacity, speed in milliseconds, finished - what to do when fadeout is finished (hide/delete/fadeIn)
var fadeOutTimer;
function fadeOut(objId,opacity,target,speed,finished,callback)
{
	clearTimeout(fadeOutTimer);
	obj = document.getElementById(objId);
	if (document.getElementById && obj)
	{
		if (opacity >= target)
		{
			setOpacity(obj, opacity);
			opacity -= 10;
			fadeOutTimer = window.setTimeout("fadeOut('"+objId+"',"+opacity+","+target+","+speed+",'"+finished+"',"+callback+")", speed);
		}
		else
		{
			if(finished == "hide")
				obj.style.display = "none";
			else if(finished == "delete")
			{
				var parentNode = obj.parentNode;
				parentNode.removeChild(obj);
				return true;
			}
			else if(finished == "fadeIn")
			{
				fadeIn(objId,opacity,100,speed);
				if(ajax.responseText)
				{
					obj.innerHTML = ajax.responseText;
					exeJavascript(ajax.responseText);
				}
			}

			if(typeof callback == "function")
				callback();
		}
	}
}
/*----------------------*/

// stripes alt rows, className is the element class to look for
function initStripe(className,elID,table,hover,oddRow,evenRow)
{
	if(oddRow == null)
		oddRow = "oddRow";
	if(evenRow == null)
		evenRow = "evenRow";

	if(elID)
	{
		var element = document.getElementById(elID);
		if(table == true)
		{
			var tables = element.getElementsByTagName("table");
			for(var i = 0; i < tables.length; i++)
			{
				var regexp = new RegExp(className, "i");
				if(tables[i].className.match(regexp))
				{
					stripeRows(tables[i].getElementsByTagName("tr"),oddRow,evenRow);
				}
			}
		}
		else
		{
			var elements = element.getElementsByClassName(className);
			stripeRows(elements,oddRow,evenRow);
		}
	}
	else
	{
		var elements = document.getElementsByClassName(className);
		stripeRows(elements,oddRow,evenRow);
	}
}
/*----------------------*/

function stripeRows(elements,oddRow,evenRow)
{
	for(var i = 0; i < elements.length; i++)
	{
		regexp = new RegExp("(\\s"+oddRow+"|\\s"+evenRow+"|"+oddRow+"\\s|"+evenRow+"\\s)");
		elements[i].className = elements[i].className.replace(regexp,"");
		//alert(elements[i].className);
		regexp = new RegExp("(\\s"+oddRow+"|\\s"+evenRow+"|"+elements[i].className+"(?!\\S))");
		//alert(regexp);
		if(i%2)
		{
			//elements[i].className += " " + evenRow;
			elements[i].className = elements[i].className.replace(regexp,elements[i].className + " " + evenRow);
		}
		else
		{
			//elements[i].className += " " + oddRow;
			elements[i].className = elements[i].className.replace(regexp,elements[i].className + " " + oddRow);
		}
	}
	delete regexp;
}
/*----------------------*/

//
function fontSizing(dir)
{
	var article = document.getElementById("articleBody");
	var children = article.getElementsByTagName('*') || document.all;
	for(var i = 0; i < children.length; i++)
	{
		if(children[i].nodeType == 1 && children[i].nodeName.toLowerCase() != "div")
		{
			// get the current font size
			if(children[i].currentStyle)
				var fontSize = children[i].currentStyle["fontSize"];
			else if(window.getComputedStyle)
				var fontSize = document.defaultView.getComputedStyle(children[i],null).getPropertyValue("font-size");
			
			// remove the px so we have an integer
			fontSize = fontSize.replace("px","");
			if(dir == "plus")
				children[i].style.fontSize = Math.round(fontSize * 1.2) + "px";
			else if(dir == "minus")
				children[i].style.fontSize = Math.round(fontSize/1.2) + "px";
		}
	}
}
/*----------------------*/

function textInput(id)
{
	if(id)
	{
		var el = document.getElementById(id);
		var inputs = document.getElementsByTagName("input");
	}
	else
	{
		var inputs = document.getElementsByTagName("input");
	}	

	oldInputObj = "";
	oldValue = "";
	for(var i = 0; i < inputs.length; i++)
	{
		var typeAtt = inputs[i].getAttribute("type");
		if(typeAtt.toLowerCase() == "text")
		{
			inputs[i].onfocus = function()
			{ 
				oldInputObj = this;
				oldValue = this.value;
				this.value = "";
			}
			inputs[i].onblur = function()
			{
				if(this.value == "")
					this.value = oldValue;
			}
		}
	}
}
/*----------------------*/

// validation for the falcons fan poll
var pollID;
var pollSelection = false
function falconPoll(form)
{
	//var form = document.getElementById(id);
	pollID = form.pollID.value;
	for(var i = 0; i < form.pollQuestion.length; i++)
	{
		if(form.pollQuestion[i].checked)
		{
			pollSelection = form.pollQuestion[i].value;
		}
	}
	if(pollSelection == false)
	{
		alert("Please select a poll answer")
		return false
	}
	else
		return true;
	//
}
/*----------------------*/

// get the results for the falcons fan poll
function getPollResults()
{
	var url = "/System/Polls/SaveResults.aspx?pollId="+pollID+"&poll="+pollSelection;
	createCookie(pollID, "true", 30)
	initRequest('GET',url,true, function(){writePollResults('pollMain',false)});
}
/*----------------------*/

function writePollResults(id,js)
{
	if(ajax.readyState == 4 && ajax.status == 200)
	{
		var el = document.getElementById(id);
		//setOpacity(el,0)
		//fadeIn(id,0,100,10);
		el.innerHTML = ajax.responseText;
		//var pollRows = document.getElementsByClassName("pollRow",id);
		//alert(pollRows.length);
		if(js)
			exeJavascript(ajax.responseText)
	}
}
/*----------------------*/

function checkPollCookie(id,url)
{
	var cookieExists = readCookie(id);
	if(readCookie(id))
		initRequest('GET',url,true, function(){writePollResults('pollMain',false)});
}
/*----------------------*/

function createCookie(name,value,days)
{
	if(days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else
		var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
/*----------------------*/

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0; i < ca.length; i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0)
			return c.substring(nameEQ.length,c.length);
	}
	return false;
}
/*----------------------*/

function eraseCookie(name)
{
	createCookie(name,"",-1);
}
/*----------------------*/

// empties a text field of it's default value when a user first clicks into the text field
// when the text field loses focus, the default value is written back if no user defined value is entered
function scanInputs()
{
	var combinedFields = new Array();		// going to hold the the NodeLists for both inputs[text] and textareas
	
	// grab all inputs with a type of text and push the returned NodeList to the array. Repeat for textareas
	var inputs = document.getElementsByTagName("input");
	for(var i = 0; i < inputs.length; i++)
	{
		combinedFields.push(inputs[i]);
	}
	var textAreas = document.getElementsByTagName("textarea");
	for(var i = 0; i < textAreas.length; i++)
	{
		combinedFields.push(textAreas[i]);
	}

	inputValuesArray = new Array();		// holds the associative array [name] = value/innerHTML

	for(var i = 0; i < combinedFields.length; i++)
	{
		// check to see if it's a text field. The first part of the statement is so we don't throw an error when on textareas since they don't have type attr
		if(combinedFields[i].getAttribute("type") && combinedFields[i].getAttribute("type").toLowerCase() == "text")
		{
			inputValuesArray[inputs[i].getAttribute("name")] = inputs[i].value;
			combinedFields[i].onfocus = function()
			{
				if(this.value == inputValuesArray[this.getAttribute("name")]) 
					this.value = "";
			}
			combinedFields[i].onblur = function()
			{
				if(this.value == "")
					this.value = inputValuesArray[this.getAttribute("name")];
			}
		}
		else if(combinedFields[i].nodeName.toLowerCase() == "textarea")
		{
			inputValuesArray[combinedFields[i].getAttribute("name")] = combinedFields[i].innerHTML;
			combinedFields[i].onfocus = function()
			{
				if(this.innerHTML == inputValuesArray[this.getAttribute("name")]) 
					this.innerHTML = "";
				
			}
			combinedFields[i].onblur = function()
			{
				if(this.innerHTML == "")
					this.innerHTML = inputValuesArray[this.getAttribute("name")];
			}
		}
	}
}
/*----------------------*/

function openWin(url,wName,para)
{
	//alert(typeof(arguments[2]));
	if(typeof(arguments[2]) == "object")
		var values = _parameters(arguments[2]);
	window.open(url,wName,values);
}


function _parameters(attributes)
{
	var values = [];
	for(attribute in attributes)
	{
		values.push(attribute + "=" + attributes[attribute].toString());
	}
	return values.join(",");
}
/*----------------------*/

// takes a literal object and creates a string of attributes for elements
function _attributes(attributes)
{
	var values = [];
	for(attribute in attributes)
	{
		values.push((attribute=='className' ? 'class' : attribute) +
          '="' + attributes[attribute].toString() + '"');
	}
    return values.join(" ");
}
/*----------------------*/

function printPage()
{
	window.print();
}
/*----------------------*/

function printEvents()
{
	
	window.print();
	//set tracking vars
	s.linkTrackVars = "events,eVar3";
	s.linkTrackEvents = "event1";
	s.eVar3 = s.pageName // same value as s.pageName
	s.events = "event1";
	s.tl(this,"o","Print Schedule");
	//clear vars
	s.eVar3 = s.events = "";
}
/*----------------------*/

function validateForm(form)
{
	var errCount = 0;
	var ageField = document.getElementById("redirect");
	if(ageField)
		var ageCheck = checkAge(form,ageField);
	
	for(var i = 0; i < form.elements.length; i++)
	{
		var error = false
		// all fields with a _req at the end of their name are required fields
		// also check for the * at the end of the field

		if(form.elements[i].name.match(/_req$/) && form.elements[i].value.match(/\*$/))
			error = true;
		if(form.elements[i].type == "select-one")
		{
			//alert(form.elements[i].selectedIndex)
			if(form.elements[i].name.match(/_req$/) && (form.elements[i].options[form.elements[i].selectedIndex].value.match(/\*$/) || form.elements[i].options[form.elements[i].selectedIndex].text.match(/\*$/)))
				error = true;
		}
		if(error)
		{
			form.elements[i].style.color = "red";
			//form.elements[i].parentNode.style.backgroundColor = "yellow";
			errCount++;
		}
		else
		{
			form.elements[i].style.color = "#858585";
			//form.elements[i].parentNode.style.backgroundColor = "#ffffff";
			
		}
	}
	
	if(errCount != 0)
		return false;
	else if(ageCheck == "too young")
	{
		ageField.value = 1;
		//alert("too young")
		return true;
	}
	else
	{
		return true;
	}
}
/*----------------------*/

function checkAge(form,ageField)
{
	/* the minumum age you want to allow in */
	var min_age = 14;

	/* change "age_form" to whatever your form has for a name="..." */
	var year = parseInt(document.forms["contactForm"]["birthYear_req"].value);
	var month = parseInt(document.forms["contactForm"]["birthMonth_req"].value) - 1;
	var day = parseInt(document.forms["contactForm"]["birthDay_req"].value);

	var theirDate = new Date((year + min_age), month, day);
	var today = new Date;

	if ( (today.getTime() - theirDate.getTime()) < 0) {
		//alert("You are too young to enter this site!");
		return "too young";
	}
	else {
		return true;
	}
}
/*----------------------*/

var globalTileCount = 2;
var tileArray = new Array();
function getNextTileId(url) {
       if(url.length > 0)
       {
	        if(tileArray.length > 0)
	        {
		        if(tileArray[1][0] == url)
		        {
			        return tileArray[1][1];
		        }
		        else
		        {
			        for(var i = 2; i < tileArray.length; i++)
			        {
				        if(tileArray[i][0] == url)
				        {
					        return tileArray[i][1];
				        }
				        else
				        {
					        tileArray[i] = new Array();
					        tileArray[i][0] = url;
					        tileArray[i][1] = globalTileCount++;
					        return tileArray[i][1];
				        }
			        }
		        }
	        }
	        else
	        {
		        tileArray[1] = new Array();
		        tileArray[1][0] = url;
		        tileArray[1][1] = globalTileCount++;
		        tileArray[2] = new Array();
		        return tileArray[1][1];
	        }
       } else {
        return globalTileCount++;
   }
}
/*----------------------*/

// hack to allow alpha transparency for PNGs in IE6
var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])
function pngFix(id)
{
	if ((version >= 5.5) && (document.body.filters)) 
	{
		for(var i=0; i<document.images.length; i++)
		{
			var img = document.images[i]
			var imgName = img.src.toUpperCase()
			if (imgName.substring(imgName.length-3, imgName.length) == "PNG" || img.getAttribute("rel") == "pngHack")
			{
				var imgID = (img.id) ? "id='" + img.id + "' " : ""
				var imgClass = (img.className) ? "class='" + img.className + "' " : ""
				var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
				var imgStyle = "display:inline-block;"
				if (img.align == "left") imgStyle = "float:left;" + imgStyle
				if (img.align == "right") imgStyle = "float:right;" + imgStyle
				if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
				var strNewHTML = "<span " + imgID + imgClass + imgTitle
				+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle
				+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
				+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
				img.outerHTML = strNewHTML
				i = i-1
			}
		}
	}
}
/*----------------------*/

function evenColumns()
{
	if(document.getElementsByClassName("contentThin"))
		var contentCol = document.getElementsByClassName("contentThin");
	else if(document.getElementsByClassName("contentWide"))
		var contentCol = document.getElementsByClassName("contentWide");
	else if(document.getElementsByClassName("contentWideRight"))
		var contentCol = document.getElementsByClassName("contentWideRight");
	
	if(document.getElementById("leftCol"))
		var leftCol = document.getElementById("leftCol");
	else
		var leftCol = 0;
	if(document.getElementById("rightCol"))
		var rightCol = document.getElementById("rightCol");
	else
		var rightCol = 0;
	
	if(leftCol == 0 && rightCol == 0)
		return true;
	
	if(leftCol.offsetHeight > rightCol.offsetHeight || leftCol.offsetHeight > rightCol)
	{
		if(leftCol.offsetHeight > contentCol[0].offsetHeight)
		{
			if(document.all)
				contentCol[0].style.height = leftCol.offsetHeight-17 + "px";
			else
				contentCol[0].style.minHeight = leftCol.offsetHeight-17 + "px";
		}
	}
	else
	{
		if(rightCol.offsetHeight > contentCol[0].offsetHeight)
		{
			if(navigator.userAgent.indexOf("MSIE 6.0") != -1)
				contentCol[0].style.height = rightCol.offsetHeight-17 + "px";
			else
				contentCol[0].style.minHeight = rightCol.offsetHeight-17 + "px";
		}
	}
}
/*----------------------*/

function changeVenue(form)
{
	nextPage = form.options[form.selectedIndex].value;
	if (nextPage != "")
	{
		document.location.href = nextPage;
	}
}
/*----------------------*/



/* search box goodness */
function changeFormLocation(formref, radioname, serchParam) {
	var searchValue = document.getElementById("siteSearchInput").value;
	document.getElementById("searchAtlanta").value="/Search/Site.aspx";
	document.getElementById("searchWin").value="http://myfalconssearch.swagbucks.com/?t=w&p=1";
	
	
	allInputs=formref.getElementsByTagName('input');
	if ((typeof allInputs=="undefined") || (allInputs==null)) {
		alert("Unable to find any inputs.");
		return false;
	}
	var newval="";
	for (i=0; i<allInputs.length; i++) {
		if ((typeof allInputs[i].name!="undefined") && (allInputs[i].name!=null)) {
			if (allInputs[i].name==radioname) {
				if (allInputs[i].checked) {
					newval=allInputs[i].value;
					allInputs[i].value='null';
				}
			}
			if (allInputs[i].name==serchParam) {
					serchval=allInputs[i].value;
					
			}
		}
	}
	if (newval=="") {
		alert("Unable to find any radios with the name radioname that were checked.");
		return false;
	}
	
	if (newval=="http://myfalconssearch.swagbucks.com/?t=w&p=1") {
		formref.action = "";
		var newActionUrl = newval + '&q=' + searchValue;
		formref.action=newActionUrl;
		formref.target="_blank";	
	}
	if (newval=="/Search/Site.aspx") {
		formref.action=newval + '?q=' + serchval;
		formref.target="";
		
	}

	return true;
}