var ie6 = false;
var _CONTENT_CATEGORY_SUFFIX = "";
var _PAGE_NAME = "";

/*************************************************************
                            SETUP
 *************************************************************/


var flashFonts =
[
	{
		name: "Univers-67-CondensedBold",
		fpVersion: "6.0.65",
		instances:
		[
			{
				selector: ".right-sidebar h3.Univers-67-CondensedBold",
				height:    25,
				yPos:      3,
				color:    "0xFFFFFF",
				upperCase: true
			}
		]
	},
	{
		name: "Palatino",
		fpVersion: 8,
		instances:
		[
			// -- Global instances
			
			{
				selector:   "h2",
				height:      41,
				xPos:       -3,
				yPos:        11,
				indent:      20,
				size:        22,
//				indent:      10,
//				size:        16,
				color:      "0xFFFFFF",
				glow:       "0xFFFFBE,0.4,7,7,2,3"
			},
			{
				selector:   "h3.white-with-shadow",
				height:      68,
				yPos:        23,
				xPos:       -5,
				indent:      30,
				size:        27,
				color:      "0xFFFFFF",
				dropShadow: "1,60,0x000000,0.5,3,3,2,3"
			},
			
			// -- About NCI instances
			
			{
				selector:   "div.about-nci-layout h3.Palatino",
				height:      102,
				yPos:        40,
				xPos:       -3,
				size:        27,
				color:      "0x000000"
			},
			
			// -- Professionals instances
			
			{
				selector:   "div.pros-bio-layout div.right-col h4",
				height:      34,
				yPos:        8,
				xPos:        0,
				indent:      20,
				size:        19,
				color:      "0xFFFFFF"
			},
			{
				selector:   "div.pros-index-layout p.pro-attributes",
				height:      150,
				yPos:        5,
				xPos:        0,
				size:        30,
				color:      "0xFFFFFF",
				htmlText:    true,
				dropShadow: "1,60,0x000000,0.5,3,3,2,3"
			}
		]
	}
];



var imagesToPreload =
[
	"/images/site/header/nav/dropdown_background.png",
	"/images/site/header/nav/dropdown_shadow.png",
	"/images/site/header/biz_nav_background.png",
	"/images/site/header/search_input_focus_background.gif"
];



/*************************************************************
                      UTILITY FUNCTIONS
 *************************************************************/



function validateSearchForm()
{
	var keywords = $( "search-input" ).value;
	if( keywords.value == "" )
	{
		return false;
	}
	else if( keywords.length < 3 )
	{
		alert( "Search terms must be at least 3 characters in length" );
		return false;
	}
	else
	{
		return true;
	}
	//return( $( "search-input" ).value != "" );
}

function flashVersionIsValid( so )
{
	return( so.installedVer.versionIsValid( so.getAttribute( "version" ) ) );
}

function searchAndReplace( haystack, search, replace )
{
	if( search != replace )
	{
		while( haystack.indexOf( search ) != -1 )
		{
			var index = haystack.indexOf( search );
			haystack =
			(
				haystack.substring( 0, index ) +
				replace +
				haystack.substring( ( index + search.length ), haystack.length )
			);
		}
	}
	return haystack;
}

function searchAndDestroy( haystack, search )
{
	return searchAndReplace( haystack, search, "" );
}

function writeNoflashHTML( flashContainerID )
{
	var flashContainer = $( flashContainerID );
	if( !flashContainer ) return;
	var noflashHTML = flashContainer.innerHTML;
	noflashHTML = searchAndDestroy( noflashHTML, "<noscript>" );
	noflashHTML = searchAndDestroy( noflashHTML, "</noscript>" );
	noflashHTML = searchAndReplace( noflashHTML, "<span class=\"tohide\">", "<span class=\"hide\">" );
	flashContainer.innerHTML = noflashHTML;
}

function cleanse( str )
{
	if( !str ) return "";
	
	var oldstr = str;
	
	// Strip excluded chars from edges
	
	var allowedChars = "abcdefghijklmnopqrstuvwxyz0123456789ÃÅÃÂ¼ÃÂ¤ÃÃ©âÃ¨ÃªÃ§Ã³Ã­Ã¡Ã±Ã©ÃºÃÃÃÃÃÃÃÃÃÃÃ¤Ã¶Ã¼'";
	for( var i = 0; i < str.length; i ++ )
	{
		if( allowedChars.indexOf( str.charAt( i ).toLowerCase() ) != -1 )
		{
			str = str.substring( i );
			break;
		}
	}
	for( var i = (str.length - 1 ); i >= 0; i -- )
	{
		if( allowedChars.indexOf( str.charAt( i ).toLowerCase() ) != -1 )
		{
			str = str.substring( 0, ( i + 1 ) );
			break;
		}
	}
	
	// Remove all other excluded chars
	
	allowedChars += "&/_. ";
	var newstr = "";
	for( var i = 0; i < str.length; i ++ )
	{
		var char = str.charAt( i );
		if( allowedChars.indexOf( char.toLowerCase() ) != -1 )
		{
			newstr += char;	
		}
	}
	
	newstr = searchAndReplace( newstr, "  ", " " );
    newstr = searchAndReplace( newstr, "<em>", "");
    newstr = searchAndReplace( newstr, "</em>", "");
	
	return( newstr );
}



/*************************************************************
                      DOM LOAD FUNCTIONS
 *************************************************************/



function searchOverlabel()
{
	var searchForm = $( "search-form" );
	var searchInput = $( "search-input" );
	
	var searchLabel = document.createElement( "label" );
	searchLabel.appendChild( document.createTextNode( localized_search_entire_site ) );
	searchForm.insertBefore( searchLabel, searchInput );
	searchLabel.setAttribute( "for", "search-input" );
	
	searchForm.className = "overlabel";
	searchLabel.firstChild.nodeValue = localized_search_entire_site;
	
	searchLabel.onclick = function()
	{
		searchInput.focus();
	}
	searchInput.onfocus = function()
	{
		searchForm.addClassName( "focus" );
	}
	searchInput.onblur = function()
	{
		if( this.value === "" )
		{
			searchForm.removeClassName( "focus" );
		}
	}
	
	if( searchInput.value !== "" )
	{
		searchInput.onfocus();
	}
}



function writeFlashFonts()
{
	flashFonts.each( function( font )
	{
		var swf = "/flash/fonts/" + font.name + ".swf";
		font.instances.each( function( instance )
		{
			$$( instance.selector ).each( function( textContainer, index )
			{
				var id = font.name + "-" + index;
				
				if( instance.width ) var width = instance.width;
				else var width = "100%";

				var so = new SWFObject( swf, id, width, instance.height, font.fpVersion, "#000000"  );
				if( flashVersionIsValid( so ) )
				{
					so.addParam( "wmode",  "transparent" );
					so.addParam( "menu",   "false" );
					so.addParam( "scale",  "noscale" );
					so.addParam( "salign", "tl" );
					
					var a = textContainer.down( "a" );
					
					if( a && a.href )
					{
						so.addVariable( "link", encodeURIComponent( a.href ) );
						//var textValue = encodeURIComponent( cleanse( a.firstChild.nodeValue ) );
						var textValue = ( cleanse( a.innerHTML ) );
						var nextElement = a.next();
					}
					else
					{
						//var textValue = encodeURIComponent( textContainer.firstChild.nodeValue );
						var textValue = ( textContainer.innerHTML );

						var nextElement = textContainer.down();
					}
					
					if( textValue && textValue != "null" )
					{
						if( instance.upperCase ) textValue = textValue.toUpperCase();
					        textValue = searchAndReplace(textValue, '&amp;', '&');
					        textValue = searchAndReplace(textValue, '&amp', '&');
						so.addVariable( "textValue", encodeURIComponent(textValue) );

					    //If title exceeds 34 characters, reduce font size and indentation
						
					        if(textValue.length > 34) 
					        {
						    instance.size = 16;
						    instance.indent = 10;
					        }


						if( instance.indent )
						{
							textContainer.style.textIndent = '0';
							so.addVariable( "indent", instance.indent );
						}


						if( instance.size       ) so.addVariable( "size",       instance.size );
						if( instance.color      ) so.addVariable( "color",      instance.color );
						
						if( instance.dropShadow ) so.addVariable( "dropShadow", instance.dropShadow );
						if( instance.glow       ) so.addVariable( "glow",       instance.glow );
						
						if( instance.xPos       ) so.addVariable( "xPos",       instance.xPos );
						if( instance.yPos       ) so.addVariable( "yPos",       instance.yPos );
						
						if( instance.htmlText   ) so.addVariable( "htmlText",   1 );
						
						so.write( textContainer );
						
						if( nextElement ) textContainer.appendChild( nextElement );
					}
				}
				
			});
		});
		
	});
}



function addVirtualBriefcaseSWFs()
{
	if( !$( "virtual_briefcase" ) ) return;
	
	// pageID used to create page-specific LocalConnections between SWFs
	var pageID = Math.floor( Math.random() * 100000000000000 );
	
	var vb_so = new SWFObject( "/flash/virtual_briefcase.swf", "virtualBriefcase", "100%", "100%", 8 );
	if( !flashVersionIsValid( vb_so ) ) return;
	
	vb_so.addParam( "menu",   "false" );
	vb_so.addParam( "wmode",  "transparent" );
	vb_so.addParam( "scale",  "noscale" );
	vb_so.addParam( "salign", "tl" );
	vb_so.addVariable( "pageID",              pageID );
	vb_so.addVariable( "_stage_width",        195 );
	if( !ie6 ) vb_so.addVariable( "enableStageResizing", 1 );
	vb_so.addVariable( "localized_vb_title",  encodeURIComponent( localized_vb_title ) );
	vb_so.addVariable( "localized_vb_empty",  encodeURIComponent( localized_vb_empty ) );
	vb_so.addVariable( "localized_vb_intro",  encodeURIComponent( localized_vb_intro ) );
	vb_so.addVariable( "localized_vb_download_all",  encodeURIComponent( localized_vb_download_all ) );
	vb_so.write( "virtual_briefcase" );
	
	$$( "li.download" ).each( function( download )
	{
		var id = download.id;
		id = id.substring( 9, id.length );
		var type = $w( download.className )[ 1 ];
                var tle = download.down( "h5" ).innerHTML;
		var title = cleanse( tle.replace(/(<([^>]+)>)/ig,"") );
         	var list = download.down( "ul" );
		var a = list.down( "a" );
		a.downloadTitle = title;
		a.onclick = function()
		{
			track( "DL/DN/" + this.downloadTitle );
		}
		var url = a.href;
                var file_size = getFileSize(url);
	        
		var li = document.createElement( "li" );
		var swfID = "add-to-briefcase-" + id;
		var liID = swfID + "-container";
		li.id = liID;
		list.appendChild( li );
		
		var so = new SWFObject( "/flash/add_to_briefcase.swf", swfID, 113, 16, 8 );
		so.addParam( "menu", "false" );
		so.addParam( "wmode", "transparent" );
		so.addVariable( "id", id );
		so.addVariable( "type",  encodeURIComponent( type  ) );
		so.addVariable( "title", encodeURIComponent( title ) );
		so.addVariable( "url",   encodeURIComponent( url   ) );
		so.addVariable( "file_size",   encodeURIComponent( file_size   ) );
	        so.addVariable( "localized_add_to_briefcase",  encodeURIComponent( localized_add_to_briefcase ) );
		so.addVariable( "pageID", pageID);
		so.write( liID );
	});
}


function getFileSize(url)
{
    var xmlhttp;

    xmlhttp=null;
    if (window.XMLHttpRequest)
    {
	xmlhttp = new XMLHttpRequest();
    }
    else if(window.ActiveXObject)
    {
	xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    if (xmlhttp!=null)
    {
	xmlhttp.open("GET",'/app/getFileSizeXML.php?url='+url, false);
	xmlhttp.send(null);
	return xmlhttp.responseText;
    }
}

function state_Change()
{
if (xmlhttp.readyState==4)
    {
	if (xmlhttp.status==200)
	{


	}
        else
	{
	    alert("Problem retrieving XML data");
	} 
    }
}



function writeSpotlight()
{
	if( !$$( "#spotlight a" ).length ) return;
	
	var so = new SWFObject( "/flash/spotlight.swf", "spotlightSWF", "375", "180", "8" );
	if( !flashVersionIsValid( so ) ) return;
	
	so.addParam( "wmode", "transparent" );
	so.addParam( "menu",  "false" );
	so.addVariable( "localized_in_the_spotlight", encodeURIComponent( localized_in_the_spotlight ) );
	
	var banners = "";
	$$( "#spotlight a" ).each( function( a, index )
	{
		if( index > 0 ) banners += ",";
		var img = a.down( "img" );
		
		banners += encodeURIComponent
		(
			encodeURIComponent( cleanse( a.title ) ) + "," +
			encodeURIComponent( img.src ) + "," +
			encodeURIComponent( a.href )
		);
	});
	so.addVariable( "_banners", encodeURIComponent( banners ) );
	
	so.write( "spotlight" );
}



function preloadImages()
{
	imagesToPreload.each( function( imageSrc )
	{
		new Image().src = imageSrc;
	});
}



function checkKeywordsOnSearchSubmit()
{
	$( "search-form" ).onsubmit = function()
	{
		return validateSearchForm();
	}
}

function overrideSearchAction()
{
	$( "search-form" ).action = "/utility_scripts/postvars.php";
}

function trackKeyContactsEmail()
{
	$$( ".key-contacts li" ).each( function( kc )
	{
		var bioLink = kc.down( "h4 a" );
		if( bioLink )
		{
			var name = cleanse( bioLink.firstChild.nodeValue );
			bioLink.name = name;
			bioLink.onclick = function()
			{
				track( "KC/BDP/" + this.name );
			}
		}
		else
		{
			var name = cleanse( kc.down( "h4" ).firstChild.nodeValue );
		}
		
		var emailLink = kc.down( "span.email a" );
		if( emailLink )
		{
			emailLink.name = name;
			emailLink.onclick = function()
			{
				track( "KC/E/" + this.name );
			}
		}
	});
}





/*************************************************************
                      DOM LOAD HANDLER
 *************************************************************/



var domLoadTriggered;

var domLoadFunctions =
[
	writeFlashFonts,
	addVirtualBriefcaseSWFs,
	searchOverlabel,
	writeSpotlight,
	checkKeywordsOnSearchSubmit,
	trackKeyContactsEmail
	//overrideSearchAction
];

var windowLoadFunctions =
[
	preloadImages
];

function onDomLoad()
{
	domLoadTriggered = true;
	domLoadFunctions.each( function( f ){ f() } );
}

Event.observe( window, "dom:loaded", onDomLoad );
Event.observe( window, "load", function()
{
	if( !domLoadTriggered ) onDomLoad();
	windowLoadFunctions.each( function( f ){ f() } );
});



/*************************************************************
                        FLASH FUNCTIONS
 *************************************************************/
 


function log( msg )
{
	//console.log( msg );
}

function track( _pageName )
{
	if( _PAGE_NAME ) var pageName = _PAGE_NAME;
	else var pageName = PAGE_NAME;
	pageName += ( "/" + cleanse( _pageName ) );
	
	var contentCategory = CONTENT_CATEGORY;
	if( _CONTENT_CATEGORY_SUFFIX ) contentCategory += ( "/" + _CONTENT_CATEGORY_SUFFIX );
	
	_hbPageView( pageName, contentCategory );
}


// JavaScript Document
