/***************************************************************************
*
*	Javascript Library
*	Author: Michael Turnwall
*	Created: 11.07.2006
*	Modified: 08.24.2007
*	Copyright 2006 Michael Turnwall - unless noted. Some Rights Reserved
*
*	This program is free software; you can redistribute it and/or modify
*	it under the terms of the GNU General Public License as published by
*	the Free Software Foundation (GPLv2). This copyright notice must
*	remain intact. All copyright information, including the copyright
*	information for individual functions, must remain intact.
*
*	This program is distributed in the hope that it will be useful,
*	but WITHOUT ANY WARRANTY; without even the implied warranty of
*	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
*	See http://creativecommons.org/licenses/GPL/2.0/ for more information.
*
***************************************************************************/

//onload function written by Simon Willison - http://simon.incutio.com Copyright Simon Willison
// 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("\\b"+className+"\\b","gi");
	for(i = 0; i < children.length; i++)
	{
		if(children[i].className.match(regexp))
			elements.push(children[i]);
	}
	return elements;
}
/*----------------------*/

//gets all elements by a specific element name and attribute
document.getElementsByAttribute = function(element, att)
{
	var elements = document.getElementsByTagName(element);
	var results = new Array();
	for(var i = 0; i< elements.length; i++)
	{
		if(elements[i].getAttribute(att))
		{
			results.push(elements[i]);
			results.push(elements[i].getAttribute(att));
		}
	}
	return results;
	
}
/*----------------------*/

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);
	if (document.getElementById)
	{
		obj = document.getElementById(objId);
		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)
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;
			}
			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);
		alert(element)
		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+")");
		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(id,dir)
{
	var el = document.getElementById(id);
	var children = el.getElementsByTagName('*') || document.all;
	for(var i = 0; i < children.length; i++)
	{
		childName = children[i].nodeName.toLowerCase();
		if(children[i].nodeType == 1 && (childName == "p" || childName == "li" || childName == "td" || childName == "h2" || childName == "h3" || childName == "h4"))
		{
			// get the current font size
			if(children[i].currentStyle)	// IE
				var fontSize = children[i].currentStyle["fontSize"];
			else if(window.getComputedStyle)	// everyone else
				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";
		}
	}
}
/*----------------------*/

// 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")];
			}
		}
	}
}
/*----------------------*/

// opens a new window
// url of page, name for the window, object containing attributes for the window - ex. {width:300,height:200,scrollbars:1,resizable:1}
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(",");
}
/*----------------------*/

// this takes an object in literal notation and concats them into a string for all the element's attributes
function _attributes(attributes)
{
	var values = [];
	for(attribute in attributes)
	{
		values.push((attribute=='className' ? 'class' : attribute) + '="' + attributes[attribute].toString() + '"');
	}
    return values;
}
/*----------------------*/

function removeElement(el)
{
	if(typeof el != "object")
		el = document.getElementById(el);
	el.parentNode.removeChild(el);
}

// from http://www.huddletogether.com/projects/lightbox/lightbox.js
// by Lokesh Dhakar
function getDocumentSize()
{
	var scrollX, scrollY, windowWidth, windowHeight;

	if (window.innerHeight && window.scrollMaxY)
	{	
		scrollX = document.body.scrollWidth;
		scrollY = window.innerHeight + window.scrollMaxY;
	}
	else if (document.body.scrollHeight > document.body.offsetHeight)
	{
		scrollX = document.body.scrollWidth;
		scrollY = document.body.scrollHeight;
	}
	else
	{
		scrollX = document.body.offsetWidth;
		scrollY = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	

	// for small pages with total height less then height of the viewport
	if(scrollY < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = scrollY;
	}

	// for small pages with total width less then width of the viewport
	if(scrollX < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = scrollX;
	}

	return new Array(windowWidth,windowHeight,pageWidth,pageHeight);
	
}
/*----------------------*/

function getPageScroll()
{
	var scrollX;
	var scrollY;
	if (self.pageYOffset)
	{
		scrollX = self.pageXOffset
		scrollY = self.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop)
	{
		scrollX = document.documentElement.scrollLeft;
		scrollY = document.documentElement.scrollTop;
	}
	else if (document.body)
	{
		scrollX = document.body.scrollLeft;
		scrollY = document.body.scrollTop;
	}
	return pageScrollArray = new Array(scrollX,scrollY);
}
/*----------------------*/

var userTitle = null;
var userSubject = null;
var userText;
function userPopup (id, popPage, fckeditor_id) {
  var form = document.getElementById(id);
  if (fckeditor_id != null) {
    var fck_editor = FCKeditorAPI.GetInstance(fckeditor_id);
    userText = fck_editor.GetXHTML(true);
  } else {
    var inputs = form.getElementsByTagName("textarea");
    userText = inputs[0].value;
    userText = userText.replace(/(\r\n|\r|\n)/g, "<br />");
  }
  var userTitle = document.getElementById('title');
  var userDate = document.getElementById('date');
  var queryStr = "?"
  if(userTitle != null)
  {
    queryStr += "title=";
    queryStr += escape(userTitle.value);
    queryStr += "&";
  }
 if(userDate != null)
 {
   queryStr += "date=";
   queryStr += escape(userDate.value);
   queryStr += "&";
 }
 queryStr += "userText="+escape(userText);
 openWin("/"+popPage+".php"+queryStr,"userInput",{width:650,height:450,resizable:1,scrollbars:1,menubar:1});
}
/*----------------------*/

var loseID = new Array("writeListField");
var destroyID = 0
function initDestroy(id)
{
	fadeOut(loseID[destroyID],100,0,50,"",function(){finishDestroy(loseID[destroyID])});
}
/*----------------------*/


function finishDestroy (id)
{
	var losses = document.getElementById(loseID[destroyID]);
	losses.value = "";
	if(destroyID < loseID.length-1)
	{
		fadeIn(loseID[destroyID],0,100,50);
		destroyID++;
		initDestroy();
	}
	else
	{
		fadeIn(loseID[destroyID],0,100,50,showDestroyMessage);
		destroyID = 0;
	}
}
/*----------------------*/

function showDestroyMessage () {
	surl = "/media/success.wav";
	document.getElementById("destroySound").innerHTML="<embed src='"+surl+"' hidden=true autostart=true loop=false>";
	document.getElementById("destroyedLetter").style.display = "block";
	fadeIn("destroyedLetter",0,100,25);
}

function hideMessage (id) {
	var el = document.getElementById(id)
	if(el && el.style.display != "none")
		el.style.display = "none"
}
/*----------------------*/




function validateTellAFriend()
{
  var errors = "";
  
  if (document.getElementById('nameField').value == "") {
    errors += 'Your Name is Required\n';
  }
  if (document.getElementById('emailField').value == "") {
    errors += 'Your Email Address is Required\n';
  }
  if (document.getElementById('recipientNameField').value == "") {
    errors += 'Recipient\'s Name is Required\n';
  }
  if (document.getElementById('recipientEmailField').value == "") {
    errors += 'Recipient\'s Email is Required\n';
  }
  if (errors != "") {
    alert(errors);
    return false;
  } else {
    alert("Thank you for telling a friend!");
    return true;
  }
}
