/**
 * @class GE_Main
 * @author ed.hicks@frogdesign.com
 */
GE_Main = new function() {

	this.initFns = [];
	this.mappedFns = {};

	this.debugEl = null;
	this.debugTxt = "DEBUG BOT v1.3x9b\n";
	this.debug = function(txt) {
		if (this.debugEl == null) {
			this.debugEl = document.body.appendChild( Builder.node("textarea", {id:"debugLog"}) ).setOpacity(.75);
		}

		this.debugTxt += txt + "\n";
		this.debugEl.value = this.debugTxt;

	}

	this.onInit = function() {
		for (var i=0; i<this.initFns.length; i++) {
			this.initFns[i]();
		}
		this.bindFns(document);

		//fixes sIFR hasLayout bug
		if (/MSIE/i.test(navigator.userAgent)) {
			if ($('ge_content')) {
				new Insertion.Bottom('ge_content','<div style="clear:both;color:#fff;height:10px;margin:0;padding:0">&nbsp;</div>');
			} else {
				new Insertion.Bottom('content','<div style="clear:both;color:#fff;height:10px;margin:0;padding:0">&nbsp;</div>');
			}
		}


	}

	this.addInitFn = function(fn) {
		this.initFns.push(fn)
	}

	this.bindFns = function(el) {
		var mFns = this.mappedFns;
		var all = el.getElementsByTagName('*');
		var len = all.length;
		var actions = new Array();
		for (var i=0;i<len;i++) {
			var el = all[i];
			var cns = el.className.split(" ");
			var j = cns.length;
			while(j--) {
				var fn = mFns[ cns[j] ];
				if (fn != null) {
					actions.push({_fn:fn,_el:el});
				}
			}
		}
		len = actions.length;
		for (var i=0;i<len;i++) {
			var obj = actions[i];
			new obj._fn(obj._el);
		}
	}
	
	this.mapCSSToFn = function(cssClass, fn) {
		if (this.mappedFns[cssClass]) {
			throw new Error( "GE_mapFnToCSS has already been called for css class '" + cssClass + "'.")
		}
		this.mappedFns[cssClass] = fn;
	}
	//TODO: get rid of all instances of mapFnToCSS across site js (argument order is wrong);
	this.mapFnToCSS = this.mapCSSToFn;


	//to prevent image flicker in IE/6
	try {
		document.execCommand('BackgroundImageCache', false, true);
	} catch(e) {}


	(function() {
	  /* Support for the DOMContentLoaded event is based on work by Dan Webb,
	     Matthias Miller, Dean Edwards and John Resig. */

	  var timer, fired = false;

	  function fireContentLoadedEvent() {
	    if (fired) return;
	    if (timer) window.clearInterval(timer);
		//if the next 2 lines are switched, Safari 2.0.4 crashes
	    fired = true;
		GE_Main.onInit.apply(GE_Main);
	  }

	  if (document.addEventListener) {
	    if (Prototype.Browser.WebKit) {
	      timer = window.setInterval(function() {
	        if (/loaded|complete/.test(document.readyState))
	          fireContentLoadedEvent();
	      }, 0);

	      Event.observe(window, "load", fireContentLoadedEvent);

	    } else {
	      document.addEventListener("DOMContentLoaded",
	        fireContentLoadedEvent, false);
	    }

	  } else {
	    document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");
	    $("__onDOMContentLoaded").onreadystatechange = function() {
	      if (this.readyState == "complete") {
	        this.onreadystatechange = null;
	        fireContentLoadedEvent();
	      }
	    };
	  }
	})();

}

function GE_containsElement(el1, el2) {
	if (el2==null) return false;
	var pel = el2.parentNode;
	while(pel != null) {
		if (el1==pel) return true;
		pel = pel.parentNode;
	}
	return false;
}
function GE_detectMouseLeave( srcEl, e ) {
	// relTarg is "where the mouse goes to"
	if (!e) var e = window.event;
	var relTarg = e.relatedTarget || e.toElement;

	return ( !GE_containsElement(srcEl, relTarg) );
}
function GE_detectMouseEnter( srcEl, e ) {

	// relTarg is "where the mouse comes from"
	if (!e) var e = window.event;
	var relTarg = e.relatedTarget || e.fromElement;

	return ( !GE_containsElement(srcEl, relTarg) );
}

//Flash related functions ----
function GE_pop(url, name, w, h) {
   window.open(url, name,'height='+h+'px,width='+w+'px,menubar=0,scrollbars=0,titlebar=0,resizable=0,toolbar=0,location=0,status=0,directories=0');
}

//----

// sIFR
// COMMENTING SIFR OUT 9/5/2007 FOR TESTING

//sIFR.delayCSS  = true;
var GE_Inspira_Medium = { src: GE_baselink + 'html_view/flash/GE_Inspira_Medium.swf' };
var GE_Inspira = { src: GE_baselink + 'html_view/flash/GE_Inspira.swf' };
var GE_Inspira_Medium_refactor = { src: GE_baselink + 'html_view/flash/GE_Inspira_Medium_refactor.swf' };
var GE_Inspira_refactor = { src: GE_baselink + 'html_view/flash/GE_Inspira_refactor.swf' };
sIFR.activate(GE_Inspira_Medium, GE_Inspira);

GE_Main.addInitFn(
	function() {
		sIFR.initialize();

		//flash replace for all other pages
		sIFR.replace(GE_Inspira_Medium, { selector: 'h2', wmode: 'transparent', css: {'.sIFR-root': {'color': '#333333','leading':'-1','font-size':'24px'} } });
		sIFR.replace(GE_Inspira, { selector: '#splash_content p', wmode: 'transparent', css: {'.sIFR-root': {'color': '#505060','leading':'8','font-size':'17px'} } });
		sIFR.replace(GE_Inspira, { selector: '.template_library .splash p', wmode: 'transparent', css: {'.sIFR-root': {'color': '#505060','leading':'8','font-size':'17px'} } });

		//flash replace for all other pages --- refactor
		sIFR.replace(GE_Inspira_Medium_refactor, { selector: '.splash_content .page_title', wmode: 'transparent', css: {'.sIFR-root': {'color': '#333333','leading':'-1','font-size':'24px'} } });
		sIFR.replace(GE_Inspira_refactor, { selector: '.splash_content p', wmode: 'transparent', css: {'.sIFR-root': {'color': '#505060','leading':'8','font-size':'17px'} } });

	}
);


//print links
GE_Main.mapCSSToFn('bhv_print',
	function(el) {
      Event.observe(el,"click", function() {
         window.print();
      })
	}
);
function GE_makeExternalLink(link) {
	link.setAttribute("target", "ge_external_link");
	if (link.readAttribute('title')) {
		if ( link.readAttribute('title').indexOf('(opens in new window)') < 0 ) { 
			link.setAttribute('title',link.readAttribute('title')+' (opens in new window)');
		}
	}	
}
//open external links in new window 90% of the size of current window
GE_Main.mapCSSToFn('bhv_external', GE_makeExternalLink);

// (ryan.rowe@frogdesign.com) class the appropriate external links with the bhv_external class for the function above
GE_Main.addInitFn( function() {

	//if (document.location.href.match("https://")) return;

	var exclude_list = new Array();
	//add to the exclude list below by pushing new strings onto the array
	exclude_list.push("://www.genewscenter.com/");
	exclude_list.push("://ir.10kwizard.com");
	exclude_list.push("://genewscenter.com/");
	exclude_list.push("://www.ge.com/");
	exclude_list.push("://video.google.com/");

	//also part of the exclude list: download links for videos, audio and pdfs
	//exclude_list.push(".pdf");
	exclude_list.push(".m4v");
	exclude_list.push(".flv");
	exclude_list.push(".mp3");
	var elen = exclude_list.length;
	
	var exception_list = new Array();
	//List to add those cases that we want external inside of the exclude list elements
	exception_list.push(".pdf");
	exception_list.push("ar2007/");
	exception_list.push("ecoreport/");
	exception_list.push("fusion.google.com");
	exception_list.push("add.my.yahoo.com");
	exception_list.push("bloglines.com");
	exception_list.push("citizenship/");
	var exlen = exception_list.length;

	var links = document.links;
	var i = links.length;
	while(i--) {
		var link = $(links[i]);

		var url = link.readAttribute("href");
		if( url.match("://") ){ //only if we match the http(s):// absolute link indicator
			var externalFlag = true; //guilty until proven innocent

			var j = elen;
			var k = exlen;
			while(j--) {// Loop looking for excluded links
				if(url.match(exclude_list[j])) {
					var externalFlag = false; //innocent!
					break;
				}

			}

			while(k--) {// Loop looking for exceptions
				if(url.match(exception_list[k])) {
					if (exception_list[k]=="citizenship/") {
							if (url.match(".jsp")){
								var externalFlag = true; //guilty!
								break;
							}
						}
					else {
					var externalFlag = true; //guilty!
					break;
					}
				}
			}
			
			if(externalFlag) {
				GE_makeExternalLink(link);
			}
		}
		else
			{
				if(url.match(".pdf") || url.match("ar2007/"))
					{
					GE_makeExternalLink(link);
					}
				if (url.match("citizenship/")) {
						if (url.match(".jsp")){
							GE_makeExternalLink(link);
						}
					}				
			}
	}
});



GE_dropdown = function(containerEl,values) {

   //public properties
   this.selectedIndex=-1;
   this.selectedValue=null;
   this.items = null;


   var html='<strong class="selected"></strong><ul>';
   for(var i=0;i<values.length;i++){
      html += '<li><a href="javascript:void(0)" onclick="return false;">'+values[i]+'</a></li>';
   }
   html += '</ul>';
	new Insertion.Top(containerEl,html);

	this.containerEl = $(containerEl);
	this.titleEl = this.containerEl.down();
	this.ulEl = this.titleEl.next("UL");
	this.items = this.ulEl.immediateDescendants();
	// this.titleLi = this.items.shift(0);
	// this.titleSpan = this.titleLi.down("SPAN");
	this.isOpen = false;
	this.mouseOn = false;

   //dropdown event listeners
   Event.observe(this.containerEl,"click", function() {
      this.toggleSelect();
   }.bind(this));
   Event.observe(this.containerEl,"mouseover", function() {
      this.mouseOn = true;
   }.bind(this));
   Event.observe(this.containerEl,"mouseout", function() {
      this.mouseOn = false;
   }.bind(this));
   Event.observe(document.body,"click", function() {
      if(!this.mouseOn && this.isOpen){
         this.close();
      }
   }.bind(this));

   for(var i=0;i<this.items.length;i++){
      var el = this.items[i];
      el.observe("click", function() {
         this.dd.select( this.idx );
      }.bind( { dd:this, idx:i } ));
   }

   this.select(0);
   this.close();
}

GE_dropdown.prototype.toggleSelect = function() {
   this.isOpen ? this.close() : this.open();
}

GE_dropdown.prototype.close = function() {
   for(var i=0;i<this.items.length;i++){
      this.ulEl.hide();
   }
   this.isOpen = false;
}

GE_dropdown.prototype.open = function() {
   for(var i=0;i<this.items.length;i++){
      this.ulEl.show();
   }
   this.isOpen = true;
}

GE_dropdown.prototype.select = function(idx) {
   this.selectedIndex = idx;
   this.selectedValue = this.items[idx].firstChild.innerHTML;
   this.titleEl.update(this.selectedValue);
   this.onSelect(this);
}
GE_dropdown.prototype.onSelect = function(dd) { };

// GE_Main.addInitFn( function() { var imgEl = $('footer').nextSiblings().each( function(el) { el.hide() }) });

document.write('<script type="text/javascript" src="'+GE_baselink+'html_view/scripts/ge_nav.js"></script>');
document.write('<script type="text/javascript" src="'+GE_baselink+'html_view/scripts/ge_overlay.js"></script>');
document.write('<script type="text/javascript" src="'+GE_baselink+'html_view/scripts/ge_audioPlayer.js"></script>');
document.write('<script type="text/javascript" src="'+GE_baselink+'html_view/scripts/search_results.js"></script>');


