/*********************************************************************
 ** GLOSSARY CODE
 ********************************************************************/

var Glossary = function ( parentElem, options ) { 
    this.initialize( parentElem, options);
}

Glossary.Terms = { };

Glossary.Log = function(txt) {
    return true;
    var logger = $( 'glogger' );
    if( !logger ) {
	logger = document.createElement( 'textarea' );
	logger.id = 'glogger';
	logger.style.width = '400px';
	logger.style.height = '320px';

	var parent = $( 'mainContent' );
	parent.insertBefore( logger, parent.firstChild );
    }

    logger.value = txt + "\n" +logger.value;

    return true;
}

Glossary.prototype = {

    parent_element : null,
    options        : null,
    terms          : null,
    
    initialize : function (parentElem, options) {

	// Set instance data
	this.parent_element = parentElem;
	this.options        = options || {};

	// Setup default options
	if( typeof this.options.glossary_url == 'undefined' )
	    this.options.glossary_url = '/services/glossary.json';

	if( typeof this.options.skip_elements == 'undefined' )
	    this.options.skip_elements = 'h1,h2,h3,h4,h5,h6,a,strong';
	
	// Call this function after you load glossary terms via ajax
	var afterLoadTerms = this.linkTerms.bind( this );
	this.loadTerms( afterLoadTerms );
	
	return true;
    }, // initialize

    
    loadTerms  : function ( cback ) {
	
	var url = this.options.glossary_url;

	// If terms were already loaded
	if( this.terms != null ) {
	    if( cback ) // then just call callback
		cback();
	}
	// If terms were already loaded or started to load for this url
	else if( Glossary.Terms[url] ) {
	    var loadedTerms = Glossary.Terms[url];
	    
	    // If still loading
	    if( loadedTerms.state == "loading" ) {

		// Setup a func to call after terms are loaded
		var afterTermsLoad = function () {

		    // Set terms 
		    this.terms = Glossary.Terms[url].terms;

		    if( cback ) // call callback
			cback();
		};

		loadedTerms.cbacks.push( afterTermsLoad.bind( this ) );
	    }
	    else { // if already loaded
		this.terms = loadedTerms.terms;
		if( cback )
		    cback();
	    }
	}
	else {
	    Glossary.Terms[url] = {
		state  : 'loading',
		cbacks : [],
		terms  : null
	    };

	    var successFunc = function (resp) {
		Glossary.Terms[url].terms
		    = this.terms 
		    = resp.responseJSON
		    ;

		Glossary.Terms[url].state = 'done';
		
		try {
		    $A( Glossary.Terms[url].cbacks ).each( 
			function (cback) {
			    cback();
			}
		    );
		
		    if( cback )
			cback();
		} catch( e ) {
		    Glossary.Log( 'ERROR: ' + e );
		}
	    };

	    Glossary.Log( 'Loading terms' );
	    new Ajax.Request( 
		url,
		{ 
		    onSuccess : successFunc.bind( this )
		}
	    );
	}

	return true;
    }, // loadTerms
    
    linkTerms : function() {
	Glossary.Log( 'linkTerms: Start' );
	
	// Get all text in document
	var text  = this._findText( this.parent_element );

	// Loop through each piece of text
	for( var textIdx = 0; textIdx < text.length; textIdx++ ) {
	    var txt = text[textIdx];

	    //Glossary.Log( 'Text: ' + txt.text + ';' );

	    // Split text into words by splitting 
	    // on any non alphanumeric character
	    var re    = new RegExp( '[\\s!-\\/:-@[-`{-~]+' );
	    var words = txt.text.split( re );

	    // If we find a glossary term in this text, we will need to 
	    // restructure the DOM by replaceing this text node with the 
	    // nodes below.
            var nodes = [ document.createTextNode( '' ) ];
	    
	    // Create a data structure to help keep track of found terms
	    var finder = {
		index_of_last_found_term : 0,
		current_position_in_text : 0,
		nodes                    : nodes
	    };

	    // Keep track of words that aren't terms, in cause that may
	    // compose multi-word terms
	    var nonTermIndexes = [];
	    
	    // Loop through each word in the text
	    for( var j = 0; j < words.length; j++ ) {
		var wrd = words[j];
		if( wrd == '' )
		    continue;
		
		// If this word exists in the glossary
		// and this is the first time we are encountering it
		var glossaryEntry = this.terms[wrd.toUpperCase()];
		if( glossaryEntry 
		    && (typeof glossaryEntry.count == "undefined"
			|| glossaryEntry.count < 1) )
		{
		    this._foundTerm( glossaryEntry,
				     wrd,
				     txt,
				     finder );
		    
		    nonTermIndexes = [];
		}
		// If this "single" word does not exist in the glossary
		else {
		    /*
                      Then check to see if this word, combined with the words
		      before it exist in the glossary (multi-word terms)
                    */

		    // Get the index of this word in the text
		    var idx = txt.text.indexOf( 
			wrd,
			finder.current_position_in_text
		    );

		    var found = false;

		    // If the word before this one was not a glossary term
		    if( nonTermIndexes.length > 0 )
		    {
			// Loop through each word before this one
			var found = false;
			for( var k = nonTermIndexes.length-1; k >= 0; k-- ) {

			    // Determine multi-word phrase
			    var matchIdx = nonTermIndexes[k];
			    var phrase   = txt.text.substr( 
				matchIdx,
				(idx + wrd.length) - matchIdx 
			    );

			    // If this phrase exists in the glossary
			    var glossaryEntry 
				= this.terms[phrase.toUpperCase()];
			    if( glossaryEntry 
				&& (typeof glossaryEntry.count == "undefined"
				    || glossaryEntry.count < 1) )
			    {
				this._foundTerm( glossaryEntry,
						 phrase,
						 txt,
						 finder );
				
				nonTermIndexes = [];
				found = true;
				break;
			    } // if phrase found
			} // foreach index in list
		    }

		    if( !found ) {
			// Update the count to right after this word
			finder.current_position_in_text = idx + wrd.length + 1;

			nonTermIndexes.push( idx );
		    }
		} // else "single" word term not found
	    } // for each word

	    // If we found terms and create a new DOM structure
	    if( nodes.length > 1 ) {
		this._replaceTerm( txt, finder );
	    }
	} // foreach piece of text

	Glossary.Log( 'linkTerms: DONE' );

	return true;
    }, // linkTerms

    _replaceTerm : function (txt, finder) {
	
	// Make sure we add any trailing text onto nodes list
	if( finder.index_of_last_found_term < txt.text.length ) {
	    finder.nodes.push( document.createTextNode( 
		txt.text.substr( finder.index_of_last_found_term )
	    ) );
	}
		    
	// Keep track of next sibling, so we can use DOM insertBefore
	var sibling = null;

	// Loop through each node
	for( var j = 0; j < finder.nodes.length; j++ ) {
	    // If this is the first node
	    if( j == 0 ) {
		// Then replace the original text node with this node
		txt.node.parentNode.replaceChild( finder.nodes[j], txt.node );
		
		// Set sibling
		sibling = finder.nodes[j].nextSibling;
	    }
	    else {
		// If there is a sibling set
		if( sibling ) {
		    // Then insert this node before the sibling
		    sibling.parentNode.insertBefore( finder.nodes[j], sibling );
		} 
		else { // if no sibling set
		    // Then append node
		    finder.nodes[0].parentNode.appendChild( finder.nodes[j] );
		}
	    }
	} // foreach node

	return true;
    }, // replaceTerm

    _foundTerm : function( entry, wrd, txt, finder ) {
	
	// Update the count for this term
	if( typeof entry.count == "undefined" ) {
	    entry.count = 1;
	}
	else
	{
	    entry.count++;
	}
	
	// Determine the index of this word in the surrounding text
	var position_of_term_in_text 
	    = txt.text.indexOf( wrd, finder.index_of_last_found_term );

	// Break off all text before this term into its own text node
	var currTxtNode  = finder.nodes[finder.nodes.length-1];
	currTxtNode.data = txt.text.substr( 
	    finder.index_of_last_found_term,
	    position_of_term_in_text - finder.index_of_last_found_term
	);
	
	// Update finder numbers
	finder.index_of_last_found_term 
	    = position_of_term_in_text + wrd.length;

	finder.current_position_in_text 
	    = position_of_term_in_text + wrd.length + 1;
		    
	// Create link that will wrap term
	var link        = document.createElement( 'a' );
	var firstLetter = wrd.substring( 0, 1 ).toUpperCase();
	link.href       = '/glossary.html?active_letter=' + firstLetter;
	link.className  = 'glossary';

	// Save exact term and definition into link for easy access
	link.definition = entry.definition;
	link.term       = entry.term;
	
	// Show defintion on mouse over
	link.onmouseover = function (evt) { 
	    if( !evt )
		evt = event;
			    
	    // Create definition element if not found
	    var def = $( 'glossary-definition' );
	    if( !def ) {
		def               = document.createElement( 'div' );
		def.id            = 'glossary-definition';
		def.style.display = 'none';
		document.body.appendChild( def );
	    }
			    
	    // Position definition above mouse and to the right a bit
	    def.style.top  = (evt.clientY - 0) + 'px';
	    def.style.left = (evt.clientX + 4) + 'px';
	    
	    // Write the definition
	    var thisLink = this;
	    def.innerHTML 
		= '<strong>' + thisLink.term + '</strong> &mdash; '
		+ thisLink.definition
	        ;
	    
	    // Reposition the definition after we know the height
	    def.style.top  = (evt.clientY 
			      - Element.getDimensions( def ).height - 5) 
		           + 'px'
	                   ;

	    // Show the definition
	    Element.show( def );
	}; // on mouse over
			
	// Hide the definition
	link.onmouseout = function () {
	    var def = $( 'glossary-definition' );
	    if( def )
		Element.hide( def );
	}; // on mouse out

	// Set the inner HTML of the link to the word(s)
	link.innerHTML = wrd;
	
	// Add this link to the list of new nodes, plus a new empty text node
	finder.nodes.push( link );
	finder.nodes.push( document.createTextNode( '' ) );

	return true;
    }, // _foundTerm

    _skipElement : function( el ) {
	var skip = false;

	if( this.options.skip_elements != null
	    && this.options.skip_elements != '' ) {
	    
	    var list = ',' + this.options.skip_elements + ',';
	    if( list.toUpperCase().indexOf( ',' + el.tagName.toUpperCase() + ',' ) != -1 ) {
		skip = true;
	    }
	}

	return skip;
    }, // skipElement

    _findText : function(el) {
	
	var text   = [];
	var childs = el.childNodes;

	// Loop through child nodes
	for( var i = 0; i < childs.length; i++ ) {
	    var chld = childs[i];
	    
	    // If child node is text
	    if( chld.nodeType == Node.TEXT_NODE ) {
		// Then save it
		text.push( { node : chld, text : chld.data } );
	    }
	    // If child node is an element
	    else if( chld.nodeType == Node.ELEMENT_NODE ) {
		if( !this._skipElement( chld ) ) {
		    // Then find text within that element
		    var texts = this._findText( chld );

		    // And save it
		    for( var j = 0; j < texts.length; j++ ) {
			text.push( texts[j] );
		    }
		}
	    }
	} // for
	
	return text;
    } // _findText
};

function linkGlossaryTerms()
{
    if( navigator.userAgent.indexOf( 'MSIE 6.0' ) != -1 )
	return;

    $A( document.getElementsByClassName( 'wysiwyg' ) ).each(
	function (el) {
	    new Glossary( el );
	    return;
	}
    );

    return;
} // linkGlossaryTerms

function initializeGlossaryPage()
{
    // Get letter index links and get terms for each letter
    var letterIdx = $A( $( 'alpha-index' ).getElementsByTagName( 'A' ) );
    
    // For each letter link in the top index
    letterIdx.each(
	function( link ) {

	    // When the user clicks on a letter link
	    link.onclick = function () { 

		// Figure out currently active link
		var currActiveLink
		    = $( 'alpha-index' ).select( '.active' )[0];
		
		// Mark it as inactive
		Element.removeClassName( currActiveLink, 'active' );
		
		// Figure out the current active letter
		var currActiveLetter 
		    = currActiveLink.className.substr( "letter".length, 1 );
		    
		// Hide terms for current active letter
		Element.hide( 'names-' + currActiveLetter );

		// Figure out which letter the user clicked
		var clickedLetter 
		    = link.className.substr( "letter".length, 1 );

		// Mark clicked letter's link on top index active
		Element.addClassName( link, 'active' );
		
		// Show the terms for the letter the user clicked
		Element.show( 'names-' + clickedLetter );

		// Do not follow actual link
		return false;
	    } // onclick
	} // each link
    );
    
    return true;
}

function enlargeText()
{
    var activeStyleSheet, currentStyleSheet, newStyleSheet;

    activeStyleSheet = getActiveStyleSheet();

    if( !activeStyleSheet || activeStyleSheet.toLowerCase() == "default" )
    {
		newStyleSheet = "Large";
    }
    else if( activeStyleSheet == "Large" )
    {
		newStyleSheet = "Larger";
    }
    else if( activeStyleSheet == "Small" )
    {
		newStyleSheet = "default";
    }
    else
    {
		newStyleSheet = "Larger";
    }
    
    if( newStyleSheet != activeStyleSheet )
    {
 		createCookie("style", newStyleSheet );

		// set the active stylesheet
		setActiveStyleSheet( newStyleSheet );
    }
} // enlargeText()

function reduceText()
{
    var activeStyleSheet, currentStyleSheet, newStyleSheet;

    activeStyleSheet = getActiveStyleSheet();
    if( !activeStyleSheet || activeStyleSheet.toLowerCase() == "default" )
    {
		newStyleSheet = "Small";
    }
    else if( activeStyleSheet == "Larger" )
    {
		newStyleSheet = "Large";
    }
    else if( activeStyleSheet == "Large" )
    {
		newStyleSheet = "default";
    }
    else
    {
		newStyleSheet = "Small";
    }
    
    if( newStyleSheet != activeStyleSheet )
    {
 		createCookie("style", newStyleSheet );

		// set the active stylesheet
		setActiveStyleSheet( newStyleSheet );
    }
} // reduceText()

// ********************************************************
// BEGIN: Enlarge/Reduce Text Functions
// Originally written by Paul Sowden and published at:
//	http://www.alistapart.com/stories/alternate/
//
// Updated and tweaked by Rubenstein Technology Group, more info at:
//	http://www.rubensteintech.com/

function setActiveStyleSheet( title )
{
    var i, a, main;
    
    for( i = 0; (a = document.getElementsByTagName( "link" )[i]); i++ ) 
    {
	if( a.getAttribute("rel").indexOf("style") != -1 && 
	    a.getAttribute("title") )
	{
	    a.disabled = true;
	    if( a.getAttribute("title") == title )
	    {
			a.disabled = false;
	    }
	}
    }
}

function getActiveStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
  }
  return null;
}

function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}

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 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 null;
}

//
// ** this now gets called in loadMain()
//window.onload = function(e) {
//  var cookie = readCookie("style");
//  var title = cookie ? cookie : getPreferredStyleSheet();
//  setActiveStyleSheet(title);
//}

window.onunload = function(e) {
  var title = getActiveStyleSheet();
  createCookie("style", title );
}

//
// ** this now gets called in loadMain()
//var cookie = readCookie("style");
//var title = cookie ? cookie : getPreferredStyleSheet();
//setActiveStyleSheet(title);

// END: Enlarge/Reduce Text Functions
// ********************************************************




// HOMEPAGE WIDGET FUNCTIONS
show_stages = function() {
	$('stages').className = 'shown';
	$('stories').className = 'hidden';
	$('trials').className = 'hidden';

	$('tabStagesHref').className = "active";
	$('tabStoriesHref').className = "";
	$('tabTrialsHref').className = "";
}
show_stories = function() {
	$('stages').className = 'hidden';
	$('stories').className = 'shown';
	$('trials').className = 'hidden';

	$('tabStagesHref').className = "";
	$('tabStoriesHref').className = "active";
	$('tabTrialsHref').className = "";
}
show_trials = function() {
	$('stages').className = 'hidden';
	$('stories').className = 'hidden';
	$('trials').className = 'shown';

	$('tabStagesHref').className = "";
	$('tabStoriesHref').className = "";
	$('tabTrialsHref').className = "active";
}
show_stage0 = function() {
	$('stage0href').className = "active";
	$('stage1href').className = "";
	$('stage2href').className = "";
	$('stage3href').className = "";
	$('stage4href').className = "";
	
	$('stage0div').className = "shown";
	$('stage1div').className = "hidden";
	$('stage2div').className = "hidden";
	$('stage3div').className = "hidden";
	$('stage4div').className = "hidden";
}
show_stage1 = function() {
	$('stage0href').className = "";
	$('stage1href').className = "active";
	$('stage2href').className = "";
	$('stage3href').className = "";
	$('stage4href').className = "";

	$('stage0div').className = "hidden";
	$('stage1div').className = "shown";
	$('stage2div').className = "hidden";
	$('stage3div').className = "hidden";
	$('stage4div').className = "hidden";
}
show_stage2 = function() {
	$('stage0href').className = "";
	$('stage1href').className = "";
	$('stage2href').className = "active";
	$('stage3href').className = "";
	$('stage4href').className = "";

	$('stage0div').className = "hidden";
	$('stage1div').className = "hidden";
	$('stage2div').className = "shown";
	$('stage3div').className = "hidden";
	$('stage4div').className = "hidden";
}
show_stage3 = function() {
	$('stage0href').className = "";
	$('stage1href').className = "";
	$('stage2href').className = "";
	$('stage3href').className = "active";
	$('stage4href').className = "";

	$('stage0div').className = "hidden";
	$('stage1div').className = "hidden";
	$('stage2div').className = "hidden";
	$('stage3div').className = "shown";
	$('stage4div').className = "hidden";
}
show_stage4 = function() {
	$('stage0href').className = "";
	$('stage1href').className = "";
	$('stage2href').className = "";
	$('stage3href').className = "";
	$('stage4href').className = "active";

	$('stage0div').className = "hidden";
	$('stage1div').className = "hidden";
	$('stage2div').className = "hidden";
	$('stage3div').className = "hidden";
	$('stage4div').className = "shown";
}

show_survivors0 = function() {
	$('survivors0href').className = "active";
	$('survivors1href').className = "";
	$('survivors2href').className = "";
	$('survivors3href').className = "";
	$('survivors4href').className = "";
	
	$('survivors0div').className = "shown";
	$('survivors1div').className = "hidden";
	$('survivors2div').className = "hidden";
	$('survivors3div').className = "hidden";
	$('survivors4div').className = "hidden";
}
show_survivors1 = function() {
	$('survivors0href').className = "";
	$('survivors1href').className = "active";
	$('survivors2href').className = "";
	$('survivors3href').className = "";
	$('survivors4href').className = "";

	$('survivors0div').className = "hidden";
	$('survivors1div').className = "shown";
	$('survivors2div').className = "hidden";
	$('survivors3div').className = "hidden";
	$('survivors4div').className = "hidden";
}
show_survivors2 = function() {
	$('survivors0href').className = "";
	$('survivors1href').className = "";
	$('survivors2href').className = "active";
	$('survivors3href').className = "";
	$('survivors4href').className = "";

	$('survivors0div').className = "hidden";
	$('survivors1div').className = "hidden";
	$('survivors2div').className = "shown";
	$('survivors3div').className = "hidden";
	$('survivors4div').className = "hidden";
}
show_survivors3 = function() {
	$('survivors0href').className = "";
	$('survivors1href').className = "";
	$('survivors2href').className = "";
	$('survivors3href').className = "active";
	$('survivors4href').className = "";

	$('survivors0div').className = "hidden";
	$('survivors1div').className = "hidden";
	$('survivors2div').className = "hidden";
	$('survivors3div').className = "shown";
	$('survivors4div').className = "hidden";
}
show_survivors4 = function() {
	$('survivors0href').className = "";
	$('survivors1href').className = "";
	$('survivors2href').className = "";
	$('survivors3href').className = "";
	$('survivors4href').className = "active";

	$('survivors0div').className = "hidden";
	$('survivors1div').className = "hidden";
	$('survivors2div').className = "hidden";
	$('survivors3div').className = "hidden";
	$('survivors4div').className = "shown";
}

show_treatments0 = function() {
	$('treatments0href').className = "active";
	$('treatments1href').className = "";
	$('treatments2href').className = "";
	$('treatments3href').className = "";
	$('treatments4href').className = "";
	
	$('treatments0div').className = "shown";
	$('treatments1div').className = "hidden";
	$('treatments2div').className = "hidden";
	$('treatments3div').className = "hidden";
	$('treatments4div').className = "hidden";
}
show_treatments1 = function() {
	$('treatments0href').className = "";
	$('treatments1href').className = "active";
	$('treatments2href').className = "";
	$('treatments3href').className = "";
	$('treatments4href').className = "";

	$('treatments0div').className = "hidden";
	$('treatments1div').className = "shown";
	$('treatments2div').className = "hidden";
	$('treatments3div').className = "hidden";
	$('treatments4div').className = "hidden";
}
show_treatments2 = function() {
	$('treatments0href').className = "";
	$('treatments1href').className = "";
	$('treatments2href').className = "active";
	$('treatments3href').className = "";
	$('treatments4href').className = "";

	$('treatments0div').className = "hidden";
	$('treatments1div').className = "hidden";
	$('treatments2div').className = "shown";
	$('treatments3div').className = "hidden";
	$('treatments4div').className = "hidden";
}
show_treatments3 = function() {
	$('treatments0href').className = "";
	$('treatments1href').className = "";
	$('treatments2href').className = "";
	$('treatments3href').className = "active";
	$('treatments4href').className = "";

	$('treatments0div').className = "hidden";
	$('treatments1div').className = "hidden";
	$('treatments2div').className = "hidden";
	$('treatments3div').className = "shown";
	$('treatments4div').className = "hidden";
}
show_treatments4 = function() {
	$('treatments0href').className = "";
	$('treatments1href').className = "";
	$('treatments2href').className = "";
	$('treatments3href').className = "";
	$('treatments4href').className = "active";

	$('treatments0div').className = "hidden";
	$('treatments1div').className = "hidden";
	$('treatments2div').className = "hidden";
	$('treatments3div').className = "hidden";
	$('treatments4div').className = "shown";
}

// END HOMEPAGE WIDGET FUNCTIONS

// SEARCH BOX FUNCTION
function handleSearchInput( el, str, bRestore )
{
    if( bRestore ) { // restore string
		if( document.getElementById(el).value == "" ) {
		    document.getElementById(el).value = str;
		}
	    } else { // clear string
		if( document.getElementById(el).value == str ) {
		    document.getElementById(el).value = "";
		}
    }
} // handleSearchInput

// this function is needed to work around 
// a bug in IE related to element attributes
function hasClass(obj) {
   var result = false;
   if (obj.getAttributeNode("class") != null) {
       result = obj.getAttributeNode("class").value;
   }
   return result;
}

function stripeTables() {
	var even = false;
	var lightClass = "light";
	
	var tables = document.getElementsByTagName("table");
	var tbodies;
	
	
	for (var ta = 0 ; ta < tables.length ; ta++) {
		tbodies = tables[ta].getElementsByTagName("tbody");
		if ( !tbodies ) {
			// look for tr tds inside table then
			var trs = tables[ta].getElementsByTagName("tr");
			
		}
		else {
			// look for tr tds inside tbodies which are inside the table
			for (var tb = 0 ; tb < tbodies.length ; tb++) {
				var trs = tbodies[tb].getElementsByTagName("tr");
				
				for (var tr = 0 ; tr < trs.length ; tr++) {
					var tds = trs[tr].getElementsByTagName("td");
					
					even = false;
					
					for (var td = 0 ; td < tds.length ; td++ ) {
						var mytd = tds[td];
						
						if (! hasClass(mytd) && ! mytd.style.backgroundColor && !(td%2==0)) {
							mytd.className = lightClass;
						}
						
						even != even;
					}
				}
			}
		}
	}
}

function listenLanguages() {
	
	var flags = $$('div#flags img');
	
	flags.each( function(elm) {
					elm.observe('click', function() {
						if ( elm.readAttribute('lang') != null && elm.readAttribute('lang') != "en" ) {
							document.location.href = "http://translate.google.com/translate_p?client=tmpg&hl=en&langpair=en|" + elm.readAttribute('lang') + '&u=www.aimatmelanoma.org';
						}
					});
				}
	
	);
	
}

/*****************************************************************************
**
** Fundraiser registrant form
** 
*****************************************************************************/
document.observe( 'dom:loaded', function () { new EditFundraiserPage() } );

function EditFundraiserPage() {
    this.initialize();
    return this;
}

EditFundraiserPage.prototype = {

    walker_radios : null,
    edit_form     : null,
    swapping      : false,

    initialize : function () {

	var editForm = $( 'edit-your-fundraiser-page' );
	if( editForm ) {
	    
	    this.edit_form = editForm;
	    var content    = this.edit_form.elements['fundraising_content'];

	    if( content.value == '' ) {
		var newWalkerRadios = editForm.elements['new_walker_flag'];
		this.walker_radios = newWalkerRadios;

		content.onchange = function () {
		    self.unbindRadios();
		}

		var self = this;
		newWalkerRadios[1].onclick 
		    = newWalkerRadios[0].onclick 
		    = function () { self.swapContent() }
	            ;

		self.swapContent();
	    }
	}
    },

    swapContent : function () {
	
	var content    = this.edit_form.elements['fundraising_content'];
	var newContent = this.edit_form.elements['new_walker_fundraising_content'].value;
	var oldContent = this.edit_form.elements['old_walker_fundraising_content'].value;

	this.swapping = true;
	
	content.value = this.getWalkerValue() == 1 ? newContent : oldContent;

	this.swapping = false;
    },

    getWalkerValue : function () {
	var newWalkerVal = 1;
	for( var i = 0; i <= 1; i++ ) {
	    if( this.walker_radios[i].checked ) {
		newWalkerVal = this.walker_radios[i].value;
		break;
	    }
	}
	return newWalkerVal;
    },
    
    unbindRadios : function () {
		if( this.swapping )
			return;

		for( var i = 0; i <= 1; i++ ) {
			this.walker_radios[i].onclick = null;
		}
    }

} // prototype



Event.observe( window, 'load', function () {
    new Golf();
    new Memorial();
    new Donation();
	new Symposium();
} );

function Golf() {
    this.initialize();
    return this;
}

Golf.prototype = {
    
	sponsorships : 0,
	pricePerPlayer : 125,
	total : 0,
	totalFromPlayers : 0,
	sponsorships : 0,
	totalText : "TOTAL DONATION: ",
	
    initialize : function () {
		var jqRenewForm = $$( 'div.donations.golf' );
		if( jqRenewForm.length == 1 ) {
		    this.total = 0;
		    this.totalFromPlayers = 0;
		    this.sponsorships = 0;
		    this.totalText = "TOTAL DONATION: ";
	
			this.pricePerPlayer = 125;
			
			if ( deltaDays <= 0 ) {
				this.pricePerPlayer = 150;
			}
			
			$('player-cost').innerHTML = "$0.00";//Tools.FormatMoney( pricePerPlayer );
						
			this.totalFromPlayers = 0;

			var radioGrp = document['forms']['frm_main']['hole_sponsorship'];
			for(i=0; i < radioGrp.length; i++){ 
				if (radioGrp[i].checked == true) { 
					var radioValue = radioGrp[i].value;
				} 
			}
			
			if ( radioValue != "None" && radioValue != null ) {
				
				this.sponsorships = radioValue/100;
			}
			else {
				this.sponsorships = 0;
			}

			this.total = this.totalFromPlayers + this.sponsorships;

			$('total').descendants()[0].innerHTML = this.totalText + Tools.FormatMoney( this.total );




			var i = 0;
			$$('fieldset#player div.multi-fields').each( function(elm) { if ( i >=0 ) { elm.hide(); } i++; } );
			
			var golfObj = this;
			var updateFunc = function() { return golfObj.updateGolfNumPlayers() };
			$('num-players').observe( 'change', updateFunc );
			
			var updateHole = function() { return golfObj.updateHoleSponsorships() };
			$$('fieldset#hole_sponsorships fieldset.radio').each( function(elm) { elm.observe( 'click', updateHole ) } );
			
		    	this.updateGolfNumPlayers();
		}
	},

	updateHoleSponsorships : function () {
		var radioGrp = document['forms']['frm_main']['hole_sponsorship'];
		for(i=0; i < radioGrp.length; i++) { 
			if (radioGrp[i].checked == true) { 
				var radioValue = radioGrp[i].value;
			} 
		}
					
		if ( radioValue != "None" && radioValue != null ) {
			this.sponsorships = radioValue/100;
		}
		else {
			this.sponsorships = 0;
		}

		this.total = this.totalFromPlayers + this.sponsorships;
	
		$('total').descendants()[0].innerHTML = this.totalText + Tools.FormatMoney( this.total );
	},

	updateGolfNumPlayers : function () {
		var i = 0;
		var playersToShow = $('num-players').value;
		$$('fieldset#player div.multi-fields').each( function(elm) { if ( i >=0 ) { elm.hide(); } i++; } );
		i = 0;
		$$('fieldset#player div.multi-fields').each( function(elm) { if ( i>=0 && i < playersToShow && playersToShow!=0) { elm.show(); } i++; } );

		this.totalFromPlayers = this.pricePerPlayer * playersToShow;
	
		$('player-cost').innerHTML = Tools.FormatMoney( this.totalFromPlayers );
				
		this.total = this.totalFromPlayers + this.sponsorships;

		$('total').descendants()[0].innerHTML = this.totalText + Tools.FormatMoney( this.total ) ;
	}
	
}

function Symposium() {
    this.initialize();
    return this;
}

Symposium.prototype = {

    initialize : function () {
		var jqRenewForm = $$( 'div.donations.symposium' );
		if( jqRenewForm.length == 1 ) {

			var i = 0;
			$$('fieldset#registrant div.multi-fields').each( function(elm) { if ( i >=0 ) { elm.hide(); } i++; } );
			
			var symposiumObj = this;
			var updateFunc = function() { return symposiumObj.updateSymposiumNumRegistrants() };
			$('num-registrants').observe( 'change', updateFunc );
	    	this.updateSymposiumNumRegistrants();
		}
	},

	updateSymposiumNumRegistrants : function () {
		var i = 1;
		var registrantsToShow = $('num-registrants').value;
		$$('fieldset#registrant div.multi-fields').each( function(elm) { 
		    if ( i >=1 ) { 
			elm.hide();
		    }
		    i++;
		} );
		i = 1;
		$$('fieldset#registrant div.multi-fields').each( function(elm) { 
		    if ( i>=1 && i < registrantsToShow && registrantsToShow!=1) {
			elm.show(); 
		    } 
		    i++; 
		} );

	}
	
}


function Memorial() {
    this.initialize();
    return this;
}

Memorial.prototype = {
    
    initialize : function () {
		var jqRenewForm = $$( 'div.donations.memorial' );
		if( jqRenewForm.length == 1 ) {
			Event.observe('donation_amount','change', function(evt) {
				if ( $('donation_amount').value != "custom" ) {
					$('amount').value = "";
					if ( $('amount_field').hasClassName('active') ) {
						$('amount_field').removeClassName('active');
					}
				}
				else {
					$('amount_field').addClassName('active');
				}
			} );
			
			Event.observe('amount','change', function(evt) {
				$('donation_amount').descendants().each(
					function(elm){
						elm.selected = false;
					}
				)
		
				if ( $('amount').value != "" ) {
					$('donation_amount').descendants()[4].selected = true;
					$('amount_field').addClassName('active');
				}
				else {
					if ( $('amount_field').hasClassName('active') ) {
						$('amount_field').removeClassName('active');
					}
				}
			} );
		}
	}
}


function Donation() {
    this.initialize();
    return this;
}

Donation.prototype = {
    
    initialize : function () {
		var jqRenewForm = $$( 'div.donations.only' );
		if( jqRenewForm.length == 1 ) {
			Event.observe('donation_amount','change', function(evt) {
				if ( $('donation_amount').value != "custom" ) {
					$('amount').value = "";
					if ( $('amount_field').hasClassName('active') ) {
						$('amount_field').removeClassName('active');
					}
				}
				else {
					$('amount_field').addClassName('active');
				}
			} );
			
			Event.observe('amount','change', function(evt) {
				$('donation_amount').descendants().each(
					function(elm){
						elm.selected = false;
					}
				)
		
				if ( $('amount').value != "" ) {
					$('donation_amount').descendants()[4].selected = true;
					$('amount_field').addClassName('active');
				}
				else {
					if ( $('amount_field').hasClassName('active') ) {
						$('amount_field').removeClassName('active');
					}
				}
			} );
			
		}
	}
}

/*****************************************************************************
**
** Homepage - News list animation
** 
*****************************************************************************/
document.observe( 'dom:loaded', function () { new NewsListAnimation() } );

function NewsListAnimation() {
    this.initialize();
    return this;
}

NewsListAnimation.prototype = {

    news_list       : null,
    news_count      : null,
    height           : null,
    container_height : null,
	shown_count		: null,
    initialize : function () {

	var newsList = $$( '#news-list dd dl' )[0];
	if( newsList ) {

	    this.news_list  = newsList;
	    this.height      = 	navigator.userAgent.indexOf("Safari") > 0 ? 82 : 83;
	    this.news_count = $$( '#news-list dd dl dt' ).length;
		this.shown_count = 0;
	    var container         = $$( '#news-list dd' )[0];
	    this.container_height = container.getHeight();

	    this.start();
	}
    },

    start : function () {
	    
	this.animate( 2, (-1 * this.height) );

    },

    restart : function () {
	// Hide the donor list and then move it back into place
	this.shown_count = 0;
	this.news_list.hide();
	this.news_list.setStyle( { top : 0 } );

	var self = this;
	this.news_list.appear( {
	    duration    : 2,
	    afterFinish : function () { self.animate( 2, (-1 * self.height) ) }
	} );
    },

    animate : function (delay, newY) {

	var dur  = 2;
	var self = this;

	new Effect.Move( 
	    this.news_list,
	    {
		delay    : delay,
		duration : dur,
		y        : newY,
		x        : 0,
		mode     : 'relative',
		transition : Effect.Transitions.linear,
		
		afterFinish : function () { 
				self.shown_count++;
				if (self.shown_count < self.news_count) {
					window.setTimeout(function() { self.animate(1, (-1 * self.height) ); }, 1000);
				} else {
					self.shown_count = 0;
					self.restart(); 
				}
			}
	    }
	);
    }
    
} // News List Animation prototype

function showProcessing( submitBtn )
{
    // We do a simple hide of the submit button here, w/o disabling
    // since browsers will remember it as disabled if you hit the back button
    // and/or the refresh button
    $( submitBtn ).hide();
    $( submitBtn.id + '-processing' ).style.display = 'block';
}

function _blank( link ) {
    window.open( link.href );
    return false;
} // _blank

function initGoogleSearchImage(boxId) { 
	var f = document.getElementById(boxId); 
	if (f) { 
		if (boxId != 'sq1') 	f.className = 'googleCSEImageOn';	
		var q = f; 
		var n = navigator; 
		var l = location; 
		if (n.platform == 'Win32') { 
			q.style.cssText = 'border: 1px solid #7e9db9; padding: 2px;'; 
		} 
		var b = function() { 
			if (q.value == '') { 
				q.className = 'googleCSEImageOn';
			}
		}; 
		var f = function() { 
			q.className = 'googleCSEImageOff'; 
		}; 
		q.onfocus = f; 
		q.onblur = b; 
		if (!/[&?]q=[^&]/.test(l.search)) { 
			b(); 
		} 
	} 
}
