// *****************************************************
// from: http://ajaxcookbook.org/
// for safely handling event handlers
var __eventListeners = [];

function addEventListener(instance, eventName, listener) {
    var listenerFn = listener;
    if (instance.addEventListener) {
        instance.addEventListener(eventName, listenerFn, false);
    } else if (instance.attachEvent) {
        listenerFn = function() {
            listener(window.event);
        }
        instance.attachEvent("on" + eventName, listenerFn);
    } else {
//        throw new Error("Event registration not supported");
    }
    var event = {
        instance: instance,
        name: eventName,
        listener: listenerFn
    };
    __eventListeners.push(event);
    return event;
}

function removeEventListener(event) {
    var instance = event.instance;
	if (instance.removeEventListener) {
		instance.removeEventListener(event.name, event.listener, false);
	} else if (instance.detachEvent) {
		instance.detachEvent("on" + event.name, event.listener);
	}
    for (var i = 0; i < __eventListeners.length; i++) {
        if (__eventListeners[i] == event) {
            __eventListeners.splice(i, 1);
            break;
        }
    }
}

function unregisterAllEvents() {
    while (__eventListeners.length > 0) {
        removeEventListener(__eventListeners[0]);
    }
}

function stopEvent(e) {
    if (!e) e = window.event;
    if (e.stopPropagation) {
        e.stopPropagation();
    } else {
        e.cancelBubble = true;
    }
}

function cancelEvent(e) {
    if (!e) e = window.event;
    if (e.preventDefault) {
        e.preventDefault();
    } else {
        e.returnValue = false;
    }
}
// *****************************************************
// for preloading images and rollovers
// Stewart Smith - WGBH Interactive
// http://interactive.wgbh.org/
var aryLoadImg = new Array();
var ncImgOver = '_over';
var ncClsRoll = 'roll';
var ncClsDblRoll = 'dbl_roll'; // name of class for double rollover
var ncClsEnlarge = 'img_enlarge';
// for main image map
var imgNavMapId = 'img_nav'; // id of the image using the nav map
var navMapId = 'nav_map'; // id of the nav map
var navMapAreaActive = ''; // id of the current active area
var ncClsAreaActive = 'active'

function loadImg(imgFile, imgType){
	var i = aryLoadImg.length;
	aryLoadImg[i] = new Image();
	aryLoadImg[i].src = imgFile + '.' + imgType;
	return i;
}

function swapImg(imgId, imgSrc){ if(document.images){ document.images[imgId].src = imgSrc; } }
function swapImgObj(imgObj, imgSrc){ imgObj.src = imgSrc; }

function initImages() {
	if (!document.getElementsByTagName) return;
	var aryImages = document.getElementsByTagName('img');
	var regex_roll = new RegExp('\\b'+ncClsRoll+'\\b');
	for (var i = 0; i < aryImages.length; i++) {
		var thisImg = aryImages[i];
		// this is used for single image roll overs
		if(thisImg.className.match(regex_roll)){
			var imgFile = thisImg.src.substr(0, thisImg.src.length-4);
			var imgType = thisImg.src.substr(thisImg.src.length-3, thisImg.src.length);
			thisImg.roll_idx = loadImg(imgFile+ncImgOver, imgType);
			thisImg.onmouseover = function(){
				try {
					if(this.className.match('\\b'+ncClsRoll+'\\b')){
						swapImgObj( this, aryLoadImg[this.roll_idx].src );
					}
				} catch(e) { /*alert(e);*/ }
			};
			thisImg.onmouseout = function(){
				try {
					if(this.className.match('\\b'+ncClsRoll+'\\b')){
						var regex_ncImgOver = new RegExp(ncImgOver+'\.');
						swapImgObj( this, this.src.replace(regex_ncImgOver, '.') );
					}
				} catch(e) { /*alert(e);*/ }
			};
		}
	}
	// also check for images used as form input
}

// utility function for safe class name managment
function manClsNames( action, obj, cls1, cls2 ){
	switch (action){
	case 'swap':
		obj.className = !manClsNames('check', obj, cls1) ? obj.className.replace( cls2, cls1 ) : obj.className.replace( cls1, cls2 );
		break;
	case 'add':
		if( !manClsNames('check', obj, cls1) ){ obj.className += obj.className ? ' '+cls1 : cls1; }
		break;
	case 'remove':
		var rep = obj.className.match(' '+cls1) ? ' '+cls1 : cls1;
		obj.className = obj.className.replace( rep, '' );
		break;
	case 'check':
		return new RegExp('\\b'+cls1+'\\b').test(obj.className)
		break;
	}
	return true;
}

function initLinks() {
	if (!document.getElementsByTagName) return;
	var thisLinks = document.getElementsByTagName("a");
	for (var i=0; i<thisLinks.length; i++) {
		var regex_roll = new RegExp('\\b'+ncClsRoll+'\\b');
		var regex_roll2 = new RegExp('\\b'+ncClsDblRoll+'\\b');
		var thisLink = thisLinks[i];
		if (thisLink.href){
			switch(thisLink.rel){
				case "external":
					thisLink.target = "_blank";
					break;
			}
			// open send to friend links in popup
			if(manClsNames('check', thisLink, 'sendtofriend')){
				thisLink.onclick = function(){ return popWithSize(this.href, 'sendtofriend', 605, 380); };
			}
			// this is used to open a popup for a promo video
			if(manClsNames('check', thisLink, 'pop_query')){
				thisLink.onclick = function(){ return popWithSize(this.href, 'promo', 600, 420); };
			}
			// single image rollovers
   			if(thisLink.className.match(regex_roll)){
 				var thisImg = thisLink.firstChild;
				var imgFile = thisImg.src.substr(0, thisImg.src.length-4);
				var imgType = thisImg.src.substr(thisImg.src.length-3, thisImg.src.length);
				var roll_idx = loadImg(imgFile+ncImgOver, imgType);
				thisImg.roll_idx = roll_idx;
				thisLink.onmouseover = function(){
					try {
						swapImg( this.firstChild.id, aryLoadImg[this.firstChild.roll_idx].src );
					} catch(e) { 
						debug(e);
					}
				};
				thisLink.onmouseout = function(){
					try {
						var regex_ncImgOver = new RegExp(ncImgOver+'\.');
						swapImg( this.firstChild.id, this.firstChild.src.replace(regex_ncImgOver, '.') );
					} catch(e) { 
						debug(e);
					}
				};
			}// end single image rollovers
			// double image rollovers
			if(thisLink.className.match(regex_roll2)){
				var thisImg = thisLink.firstChild;
				var imgFile = thisImg.src.substr(0, thisImg.src.length-4);
				var imgType = thisImg.src.substr(thisImg.src.length-3, thisImg.src.length);
				var roll_idx = loadImg(imgFile+ncImgOver, imgType);
				var h_src1 = thisImg.src.substr(0, thisImg.src.length-5)+'1'+ncImgOver+thisImg.src.substr(thisImg.src.length-4, thisImg.src.length);
				var h_src2 = thisImg.src.substr(0, thisImg.src.length-5)+'2'+ncImgOver+thisImg.src.substr(thisImg.src.length-4, thisImg.src.length);
				thisImg.roll_idx = roll_idx;
				thisImg.h_src1 = h_src1;
				thisImg.h_src2 = h_src2;
				thisLink.onmouseover = function(){
					try {
						swapImg( this.firstChild.id.substr(0, this.firstChild.id.length-1)+'1', this.firstChild.h_src1 );
						swapImg( this.firstChild.id.substr(0, this.firstChild.id.length-1)+'2', this.firstChild.h_src2 );
					}catch(e){ if(typeof debug=='function'){ debug(e); } }
				};
				thisLink.onmouseout = function(){
					try {
						var regex_ncImgOver = new RegExp(ncImgOver+'\.');
						this.firstChild.src = this.firstChild.src.replace(regex_ncImgOver, '.');
						swapImg( this.firstChild.id.substr(0, this.firstChild.id.length-1)+'1', this.firstChild.h_src1.replace(regex_ncImgOver, '.') );
						swapImg( this.firstChild.id.substr(0, this.firstChild.id.length-1)+'2', this.firstChild.h_src2.replace(regex_ncImgOver, '.') );
					}catch(e){ if(typeof debug=='function'){ debug(e); } }
				};
			}// end double image rollovers
		}
	}
}



function initDivs() {
	// add code to look for rel="external" to launch in a new window
	// any special glossary, pop_query links etc.etc.
	if (!document.getElementsByTagName) return;

	// special img_enlarge feature
	var aryDivs = document.getElementsByTagName('div');
	var regex_enlarge = new RegExp('\\b'+ncClsEnlarge+'\\b');
	for (var i = 0; i < aryDivs.length; i++) {
		if(aryDivs[i].className.match(regex_enlarge)){
			initEnlargeImg(aryDivs[i]);
		}
	}

	

}

function initEnlargeImg(objDiv){
	if (!document.getElementsByTagName) return;
	var aryAs = objDiv.getElementsByTagName('a');
	for (var i = 0; i < aryAs.length; i++) {
		if(aryAs[i].href.match('\\benlarged')){
//			addEventListener(aryAs[i], 'click', openEnlarged);
			aryAs[i].onclick = function() { return popWithSize(this.href, 'amex_enlarged', 620, 550); };
		}
	}
}

function openEnlarged(){
	return popWithSize(this.href, 'amex_enlarged', 625, 550);
}

function initHome() {
	if ( !document.getElementsByTagName ) return;
	// homepage highlights
	if(!document.getElementById('cnt_highlights') || !document.childNodes) return;
	var highlights = document.getElementById('cnt_highlights').getElementsByTagName('div');
	for (var i = 0; i < highlights.length; i++) {
		var hl = highlights[i];
		if ( manClsNames('check', hl, 'highlight') && hl.childNodes.length > 0){
			for(var j = 0; j< hl.childNodes.length; j++){
				if(hl.childNodes[j].nodeName.toUpperCase() == 'A'){
					hl.href = hl.childNodes[j].href;
					hl.onmouseover = function(){ try{ manClsNames('swap', this, 'highlight', 'highlight_over'); } catch(e) { /* catch exceptions */ } };
					hl.onmouseout = function(){ try{ manClsNames('swap', this, 'highlight', 'highlight_over'); } catch(e) { /* catch exceptions */ } };
					hl.onclick = function(){ try{ window.location = this.href; return false; } catch(e) { /* catch exceptions */ return true; } };
				}
			}
		}
	}
}

function initAckGallery(){
	if (!document.getElementsByTagName || !document.getElementById('cnt_img_a') ) return;
	var aryAs = document.getElementById('cnt_img_a').getElementsByTagName('a');
	for (var i = 0; i < aryAs.length; i++) {
		if( manClsNames('check', aryAs[i], 'show_img_a') ){
			aryAs[i].onmouseover = function(){ try{ manClsNames('swap', this.parentNode.previousSibling.previousSibling, 'hide', 'show'); } catch(e) { /* catch exceptions */ } };
			aryAs[i].onmouseout = function(){ try{ manClsNames('swap', this.parentNode.previousSibling.previousSibling, 'show', 'hide'); } catch(e) { /* catch exceptions */ } };
		}
	}
}

function initMiniGallery(){
	// miniGallery
	prevBtn = document.getElementById('mini_gal_prev');
	nextBtn = document.getElementById('mini_gal_next');

	switch (window.location.search.substr(1, 5)){// starting at char 1 strips '?'
	case 'pic=2':
		updateMiniGal('2');
		break;
	case 'pic=3':
		updateMiniGal('3');
		break;
	default:
		updateMiniGal('1');
	}

	manClsNames('swap', document.getElementById('mini_gal_nav'), 'hide', 'show');
}

function updateMiniGal(strId){
	document.getElementById('image1').className = 'hide';
	document.getElementById('image2').className = 'hide';
	document.getElementById('image3').className = 'hide';

	switch(strId){
	case '1':
		prevBtn.src = '../subimages/arrow-prev_off.gif';
		manClsNames('remove', prevBtn, 'roll');
		prevBtn.onclick = function () { return false; }
		
		nextBtn.nav_to = '2';
		nextBtn.onclick = function () { updateMiniGal(this.nav_to) }
		
		document.getElementById('image1').className = 'show';
		break;
	case '2':
		prevBtn.src = '../subimages/arrow-prev.gif';
		manClsNames('add', prevBtn, 'roll');
		prevBtn.nav_to = '1';
		prevBtn.onclick = function () { updateMiniGal(this.nav_to) }

		nextBtn.src = '../subimages/arrow-next.gif';
		manClsNames('add', nextBtn, 'roll');
		nextBtn.nav_to = '3';
		nextBtn.onclick = function () { updateMiniGal(this.nav_to) }

		document.getElementById('image2').className = 'show';
		break;
	case '3':
		prevBtn.nav_to = '2';
		prevBtn.onclick = function () { updateMiniGal(this.nav_to) }
		
		nextBtn.src = '../subimages/arrow-next_off.gif';
		manClsNames('remove', nextBtn, 'roll');
		nextBtn.onclick = function () { return false; }
		
		document.getElementById('image3').className = 'show';
		break;
	}
	
	document.getElementById('img_num').innerHTML = strId;
	updateVideoChoose(strId);
}

function updateVideoChoose(strId){
	if (!document.getElementsByTagName || !document.getElementById('cnt_video_choose') ) return;
	var aryAs = document.getElementById('cnt_video_choose').getElementsByTagName('a');
	for (var i = 0; i < 4; i++) { //hardcoded :[
		aryAs[i].onclick = function(){ try{ window.location = this.href + '?pic=' + strId; return false; } catch(e) { return true; } };
	}
}

// *****************************************************
// from: http://dean.edwards.name/weblog/2006/06/again/
// Dean Edwards/Matthias Miller/John Resig

function init() {
    // quit if this function has already been called
    if (arguments.callee.done) return;

    // flag this function so we don't do the same thing twice
    arguments.callee.done = true;

    // kill the timer
    if (_timer) clearInterval(_timer);

    // do stuff
	initLinks();
	initImages();
	initDivs();

//	initAmexNav();
yadm();

	// conditionally run scripts
	if(document.getElementById('cnt_highlights') && document.childNodes){
		initHome(); // home page highlights
	}

	if(document.getElementById('cnt_img_a') ){
		initAckGallery(); // program/a.html
	}

	if(document.getElementById('cnt_mini_gal') ){
		initMiniGallery(); // lobotomist/stories
	}

};

/* for Mozilla/Opera9 */
if (document.addEventListener) {
    document.addEventListener("DOMContentLoaded", init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
    document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
    var script = document.getElementById("__ie_onload");
    script.onreadystatechange = function() {
        if (this.readyState == "complete") {
            init(); // call the onload handler
        }
    };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
    var _timer = setInterval(function() {
        if (/loaded|complete/.test(document.readyState)) {
            init(); // call the onload handler
        }
    }, 10);
}

/* for other browsers */
window.onload = init;
// *****************************************************

window.onunload = function(){
	unregisterAllEvents();
};



/* popup functionality */

/* browser vars for popups */
var ng = navigator;
var ua = ng.userAgent;
var nav = (ng.appName == 'Netscape');
var saf = (ng.appVersion.indexOf('Safari') != -1);
var ie = (ng.appVersion.indexOf('MSIE') != -1);
var mac = (ua.indexOf('Mac') != -1);
var aol = (ua.indexOf('AOL') != -1);

window.name = 'amex';

function popWithSize(openURL, winName, w, h){
    w = browserWidth(w);
	h = browserHeight(h);
    // position //x=aol?40:25; //y=aol?12:37;
    otherOptions = 'toolbar=0,location=0,status=1,menubar=0,scrollbars=1,resizable=1,';//+',screenx='+x+',screeny='+y+',left='+x+',top='+y);
    thisWin = window.open(openURL, winName, otherOptions+'width='+w+',height='+h);
try{	
	if ( thisWin.closed ) { return true; }
	if( thisWin.focus ){ thisWin.focus(); }
}catch(e){

}
//	var strOut = 'w:' + w + 'px h:' + h + 'px';
//	alert(strOut);
	return false;
}

function popQuery(popURL, w, h){ // for watch the promo links
	// original width=419,height=480
    w = browserWidth(w);
	h = browserHeight(h);
    // position //x=aol?40:25; //y=aol?12:37;
    var otherOptions = 'toolbar=0,location=0,status=0,menubar=0,scrollbars=0,resizable=0,';
    Watch_the_Promo = window.open(popURL,'Watch_the_Promo',otherOptions+'width='+w+',height='+h);//+',screenx='+x+',screeny='+y+',left='+x+',top='+y);
//    window.open('promos/pop_query.html?name=Reagan&url=reagan','Watch_the_Promo','');
	if ( !Watch_the_Promo ) { return true; }
	if( Watch_the_Promo.focus ){ Watch_the_Promo.focus(); }
	return false;
}

function browserWidth(w){
	if( mac ){
		if( !nav && ie ){
			w-=16;
		}
		if( nav && saf ){
			w+=2;
		}
		/*if( nav && !ie && !saf ){
			w+=0;
		}*/
	}else{
		if( ie ){
			w+=13;
		}else{
			//w+=1;
		}
	}
	return w;
}

function browserHeight(h){
	if( mac ){
		if( !nav && ie ){
			h-=12;
		}
		if( nav && saf ){
			h+=17;
		}
		if( nav && !ie && !saf ){
			h+=5;
		}
	}else{
		if( ie ){
			//h-=4;
		}else{
			//h-=3;
		}
	}
	return h;
}

function debug(){ return; }




/*
	YADM - Yet another dynamic menu
	written by Chris Heilmann (http://icant.co.uk)
	Please refer to the yadm homepage for updates: http://www.onlinetools.org/tools/yadm/
	Free for non-commercial use. Changes welcome, but no distribution without 
	the consent of the author.
*/
function yadm(){

// Variables, change these in case you need to set other class names (mmhide_ for 
// contribute users for example)
	var parentClass='isParent';				//gets applied when the LI has a nested UL
	var activeParentClass='isActive';		//gets applied when the nested UL is visible
	var preventHoverClass='nohover';		//denotes a navigation that should not get any hover effects
	var indicateJSClass='dhtml';			//gets applied to the main navigation when Javascript is available
	var toHideClass='hiddenChild';			//gets applied to hide the nested UL
	var toShowClass='shownChild';			//gets applied to show the nested UL
	var currentClass='current';				//denotes the current active sub element and prevents collapsing
	var d=document.getElementById('amexnav');	//denotes the navigation element 

// if DOM is not available stop right here.
	if(!document.getElementById && !document.createTextNode){return;}

// if the navigation element is available, apply the class denoting DHTML capabilities
	if(d)
	{
		d.className+=d.className==''?indicateJSClass:' '+indicateJSClass;
// stew added dhtml class to body
manClsNames( 'add', document.body, indicateJSClass);

		var lis,i,firstUL,j,apply;

// loop through all LIs and check which ones have a nested UL
		lis=d.getElementsByTagName('li');
		for(i=0;i<lis.length;i++)
		{
			firstUL=lis[i].getElementsByTagName('ul')[0]
// if there is a nested UL, deactivate the first nested link and apply the class to show 
// there is a nested list
			if(firstUL)
			{
// start stew edit
//				lis[i].childNodes[0].onclick=function(){return false;}
//end stew edit
				lis[i].className+=lis[i].className==''?parentClass:' '+parentClass;

// check if there is a "current" element 
				apply=true;
				if(new RegExp('\\b'+currentClass+'\\b').test(lis[i].className)){apply=false;}
				if(apply)
				{
					for(j=0;j<firstUL.getElementsByTagName('li').length;j++)
					{
						if(new RegExp('\\b'+currentClass+'\\b').test(firstUL.getElementsByTagName('li')[j].className)){apply=false;break}
					}
				}
// if there is no current element, apply the class to hide the nested list
				if(apply)
				{
					firstUL.className+=firstUL.className==''?toHideClass:' '+toHideClass;
// check if there is a class to prevent hover effects and only apply the function
// onclick if that is the case, otherwise apply it onclick and onhover
					if(new RegExp('\\b'+preventHoverClass+'\\b').test(d.className))
					{
						lis[i].onclick=function(){doyadm(this);}
					} else {
// stew comment out						lis[i].onclick=function(){doyadm(this);}
						lis[i].onmouseover=function(){doyadm(this);}
						lis[i].onmouseout=function(){doyadm(null);}
					}
// if there is a current element, define the list as being kept open and apply the 
// classes to show the nested list and define the parent LI as an active one
				} else {
					lis[i].keepopen=1;
					firstUL.className+=firstUL.className==''?toShowClass:' '+toShowClass;
					lis[i].className=lis[i].className.replace(parentClass,activeParentClass);
				}
			}
		}
	}
// function to show and hide the nested lists and add the classes to the parent LIs
	function doyadm(o)
	{
		var childUL,isobj,swap;

// loop through all LIs of the navigation		
		lis=d.getElementsByTagName('li');
		for(i=0;i<lis.length;i++)
		{
			isobj=lis[i]==o;
// function to exchange class names in an object
			swap=function(tmpobj,tmporg,tmprep)
			{
				tmpobj.className=tmpobj.className.replace(tmporg,tmprep)		
			}
// if the current LI does not have an indicator to be kept visible
			if(!lis[i].keepopen)
			{
				childUL=lis[i].getElementsByTagName('ul')[0];
// check if there is a nested UL and if the current LI is not the one clicked on
// and exchange the classes accordingly (ie. hide all other nested lists and 
// make the LIs parent rather than active.
				if(childUL)	
				{	
					if(new RegExp('\\b'+preventHoverClass+'\\b').test(d.className))
					{
						if(new RegExp('\\b'+activeParentClass+'\\b').test(lis[i].className))
						{
							swap(childUL,isobj?toShowClass:toHideClass,isobj?toHideClass:toShowClass);		
							swap(lis[i],isobj?activeParentClass:parentClass,isobj?parentClass:activeParentClass);		
						} else {
	
							swap(childUL,isobj?toHideClass:toShowClass,isobj?toShowClass:toHideClass);		
							swap(lis[i],isobj?parentClass:activeParentClass,isobj?activeParentClass:parentClass);		
						}
					} else {
							swap(childUL,isobj?toHideClass:toShowClass,isobj?toShowClass:toHideClass);		
							swap(lis[i],isobj?parentClass:activeParentClass,isobj?activeParentClass:parentClass);		
					}
				} 
			}
		}
	}
}