function toggleClass (c,t) {
	
	var current = document.getElementById(c);
	var target = document.getElementById(t);
	
	if (target.className=="elementHidden") {
		target.className="elementVisible";
		current.className="elementHidden";
	}
	else if (target.className=="elementVisible") {
		current.className="elementVisible";
		target.className="elementHidden";
	}
}

function clearTabs() {
	// clear all list items that begin with tab*
	var tabMatcher = new RegExp("^tab[A-Z][A-Za-z0-9_]+$");
	var listItems = document.getElementsByTagName("li");
	for (var i=0; i<listItems.length; ++i) {
		var listItem = listItems.item(i);
		if (listItem && listItem.id && (listItem.id.search(tabMatcher) != -1)) {
			if (listItem.className.indexOf("leftTab") != -1)
				listItem.className = "leftTab";
			else
				listItem.className = "";
		}
	}
	// clear all divs that begin with body*	
	var bodyMatcher = new RegExp("^body[A-Z][A-Za-z0-9_]+$");
	var divs = document.getElementsByTagName("div");
	for (var i=0; i<divs.length; ++i) {
		var div = divs.item(i);
		if (div && div.id && (div.id.search(bodyMatcher) != -1))
			div.style.display="none";
	}
}
	
function displayTab(listItem) {
	var div = document.getElementById("body"+listItem.getAttribute('id').substring(3));
	if (div) {
		clearTabs();
		if (listItem.className.indexOf("leftTab") != -1)
				listItem.className = "leftTab current";
		else
				listItem.className = "current";
		div.style.display="block";
	}		
	return false;	
}

function correctPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])
     if ((version >= 5.5)&& (version < 7.0) && (document.body.filters)) 
   {
      for(var i=0; i<document.images.length; i++)
      {
         var img = document.images[i]
         var imgName = img.src.toUpperCase()
         if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
         {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText 
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
            img.outerHTML = strNewHTML
            i = i-1
         }
      }
   }    
}
if (window.attachEvent) //IE exclusive method for binding an event
   window.attachEvent("onload", correctPNG);

/* functions for accordion functionality */

function toggleDetails(id) {
		
	var imgUp = new Image();
	var imgDown = new Image();
		
	imgDown.src = "http://www.ocimumbio.com/lims2/wp-content/themes/arthemia/images/minus.gif";
	imgUp.src = "http://www.ocimumbio.com/lims2/wp-content/themes/arthemia/images/plus.gif";
    if (document.getElementById('row_details_' + id).style.display == "none") {
		document.getElementById('row_details_' + id).style.display = "block";
		document.getElementById('row_synopsis_' + id).style.display = "none";
		document.getElementById('row_img_' + id).src = imgDown.src;
		}
		
		else {
			document.getElementById('row_details_' + id).style.display = "none";
			document.getElementById('row_synopsis_' + id).style.display = "block";
			document.getElementById('row_img_' + id).src  = imgUp.src;
			}
}

/* functions for Top Navigation functionality */

/**
 * TimeManager
 */
TimeManager = function() {
    if ( window.__TimeManager__ ) return;
    window.__TimeManager = this;
    this.timers = [];
    this.time = 0;
    this.ids = 0;
    this.frequency = 250;
    this.timerId = setInterval( "__TimeManager__.interval()", this.frequency );
}

TimeManager.prototype.interval = function() {
    var timer;
    this.time += this.frequency;
    var curTime = this.time;
    var list = [];
    for ( var i=0;i<this.timers.length;i++ ) {
	timer = this.timers[i];
	if ( timer.endTime < curTime ) {
	    timer.obj[timer.method](timer.parameters);
	    if ( timer.type == "timeout" ) {
	        timer.dead = true;
	    }
	    else {
		timer.endTime = this.time + timer.time;
	    }
	}
	else {
	    list.push ( timer );
	}
    }
    this.timers = list;
}

TimeManager.prototype.addTimer = function ( timer ) {
    timer.startTime = this.time;
    timer.endTime = this.time + timer.time;
    timer.id = this.ids++;
    this.timers.push( timer );
    return timer.id;
}

TimeManager.prototype.kill = function( id ) {
    var list = [];
    for ( var i=0;i<this.timers.length;i++ ) {
	if ( this.timers[i].id != id ) {
	    list.push ( this.timers[i] );
	}
	else {
	    this.timers[i].dead = true;
	}
    }
    this.timers = list;
}

/**
 * Timer
 */
Timer = function () {
    if ( !window.__TimeManager__ ) {
	window.__TimeManager__ = new TimeManager();
    }
    this.type = "timeout";
    this.timerId = -1;
    this.obj = null;
    this.method = "";
    this.time = 0;
    this.parameters = [];
    this.dead = false;
}

Timer.prototype.setTimeout = function ( obj, method, time, parameters ) {
    this.obj = obj;
    this.method = method;
    this.time = time;
    this.triggerTime = this.startTime + time;
    this.parameters = parameters;
    __TimeManager__.addTimer( this );
}

Timer.prototype.setInterval = function ( obj, method, time, parameters ) {
    this.obj = obj;
    this.type = "interval";
    this.method = method;
    this.time = time;
    this.triggerTime = this.startTime + time;
    this.parameters = parameters;
    __TimeManager__.addTimer( this );
}

Timer.prototype.kill = function () {
    __TimeManager__.kill( this.id );
}




/**
 * main application container
 */
var OBS = (OBS)?(OBS):({});

/**
 * Logger
 * Utility class to handle debug / log information
 * 
 */
Logger = function( level ) { 
    /**
     * log level, 
     * 0 - no logging
     * 1 - basic logging
     * 2 - verbose logging
     */
    this.logLevel = level;
}
Logger.prototype.log = function( msg ) {
    if ( window.console && window.console.log && this.logLevel >= 1 ) console.log("LOG: "+msg);
}
Logger.prototype.verbose = function( msg ) {
    if ( window.console && window.console.log && this.logLevel >= 2 ) console.log("INFO: "+msg);
}
Logger.prototype.alert = function ( msg ) {
    alert ( msg );
}

OBS.Logger = new Logger(0);



/**
 * TabComponent
 * represents the logic and funcntionality that encapsulate one grouping 
 * of a primary nav button and its associated drop down menu
 *
 * @param num - number index / id
 * @param name - string name
 * @param expandDuration - number time it takes to go from hidden to revealed
 *
 */
TabComponent = function( num, name, openDuration, closeDuration ) {
    this.num = num;
    this.name = (name)?(name):(" -- ");

    this.openDuration = (openDuration)?(openDuration):(.5); // seconds
    this.closeDuration = (closeDuration)?(closeDuration):(.5); // econds

    this.navSuffix = "NavA";
    this.menuSuffix = "Menu";
    this.overClass = "hover";
    this.simple = false;
    
    // element references, adding to them a reference back to the owener tabcomponent(this)
    this.button = $( name + this.navSuffix );
    if ( this.button ) this.button.owner = this;
    if ( this.button ) this.button.onmouseover = function() {
	OBS.TabGroup.onNavOver( this.owner );
    }
    if ( this.button ) this.button.onmouseout = function() {
	OBS.TabGroup.onNavOut( this.owner );
    }

    this.menu = $( name + this.menuSuffix );		
    if ( this.menu ) this.menu.owner = this;
    
    // state management
    this.isOpen = false;
    
    // basic menu props
    var dim;
    if ( this.menu ) {
	dim = this.menu.getDimensions();
	this.width = dim.width;
	this.height = dim.height;
	this.openDuration *= ( this.height / 403 );
	this.left = parseInt(this.menu.getStyle("left"));
	this.top = parseInt(this.menu.getStyle("top"));
    } 
    else {
	this.width = 0;
	this.height = 0;
	this.left = 0;
	this.top = 0;
    }
}

TabComponent.prototype.isOverMenu = function( mousex, mousey ) {
	var width;
	if (self.innerWidth)	{
		width = self.innerWidth;
	}
	else if (document.documentElement && document.documentElement.clientWidth)	{
		width = document.documentElement.clientWidth;
	}
	else if (document.body)	{
		width = document.body.clientWidth;
	}

	var offset = (width - 10000)/2;
	offset = (offset>0)?(offset):(0);

        l = this.left + offset;
	t = this.top;
	w = this.width;
	h = this.height;

	if ( mousex < l || mousex > l+w || mousey>t+h || mousey < t ) {
	   return false;
	}
	else {
	   return true;
 	}
}

TabComponent.prototype.highlight = function() {
    if ( this.button ) {
	this.button.addClassName( this.overClass );
    }
}

TabComponent.prototype.dehighlight = function() {
    if ( this.button && !this.isOpen ) {
	this.button.removeClassName( this.overClass );
    }
}

TabComponent.prototype.close = function( force ) {
    if ( this.num == 0 ) return;

    clearInterval( this.timerId );
    this.isOpen = false;

    if ( !this.button || !this.menu ) return;

    var e = new Effect.BlindUp( this.menu, { duration: this.closeDuration, 
				     afterUpdate:function(e) { 
					if ( !($("IFrameHack")) ) return;
					var left = (parseInt(e.element.getStyle("left"))+2)+"px";
				 	var width = (parseInt(e.element.getStyle("width"))-5)+"px";
					var height = (parseInt(e.element.getStyle("height"))-5)+"px";
					$("IFrameHack").setStyle( {left:left,height:height,width:width} );
			     	     },
				     afterFinish:function(e) {
				 	e.element.setStyle({visibility:"hidden"});
					e.element.owner.dehighlight();
					e.element.owner.cleanup();
					OBS.TabGroup.onMenuClose();
				 	if ( $("IFrameHack") ) $("IFrameHack").setStyle( { left:"-9999px" } );
				     }
    } );
}

TabComponent.prototype.open = function() {	
    if ( !this.button || !this.menu ) return;

    this.highlight();
    this.isOpen = true;

    var e = new Effect.BlindUp( this.menu, { duration:0, 
					     afterFinish:function(e) { 
							 e.element.setStyle({visibility:"visible"});
							 var ef = new Effect.BlindDown( e.element, { duration:e.element.owner.openDuration,
								afterUpdate:function(e) { 
							 		if ( !($("IFrameHack")) ) return;
									var left = (parseInt(e.element.getStyle("left"))+2)+"px";
									var width = (parseInt(e.element.getStyle("width"))-5)+"px";
									var height = (parseInt(e.element.getStyle("height"))-5)+"px";
									$("IFrameHack").setStyle( {left:left,height:height,width:width} ); }
												   } );
						     }
    } );
}

TabComponent.prototype.cleanup = function() {
    if ( this.menu ) {
	this.menu.setStyle( { visibility:"hidden", height:""+this.height+"px" } );
    }
}



/**
 * Tab Group Controller
 * handles the on/off state of the primary nav, as well 
 * as revealing and hiding the dropdown menu
 */
OBS.TabGroup = 
{
    openDelay : 400, // miliseconds
    closeDelay : 750, // milliseconds
    openDuration : 350, // milliseconds
    closeDuration : 300, // milliseconds

    nextTab : null,
    overTab : null,

    openTab : null,
    
    isOpening:false,
    isClosing:false,
    
    wait : false,
    isOverDropDown : false,

    timerId : null,
    tabNames : ["", "services","databases","apps"],
    tabs : [],
    useFrameHack : false,

    /**
     *
     */
    init:function() {
	Event.observe(document.body, 'mousemove', function(e) { OBS.TabGroup.onMouseMove(e); } );

	// if IE 6, create the IFrame that will be used to cover combo boxes
	var browser=navigator.appName;	
	var b_version=navigator.appVersion;
        b_version = b_version.substr( b_version.indexOf("MSIE")+5 );
	b_version = parseInt(b_version.substr( 0, b_version.indexOf(";") ));
	var isIE6 = ( browser.toLowerCase().indexOf("microsoft") != -1 && b_version <= 6 );
	var hasSelects = ( ( document.getElementsByTagName("select") ).length > 0 );
	if ( isIE6 && hasSelects ) {
	    new Insertion.Before('servicesMenu', '<iframe id="IFrameHack" frameborder="0" scrolling="no"></iframe>');	
	    $("IFrameHack").setStyle( { border:"0px solid white", left:"-9999px",position:"absolute",top:"100px",overflow:"hidden"} );
	}
	
	// setup starting values
	this.timerId = 0;
	
	// set up each menu props
	var tab;
	for ( var i=0;i<this.tabNames.length;i++ ) {
	    tab = new TabComponent( i, this.tabNames[i], (this.openDuration/1000), (this.closeDuration/1000) );
	    tab.useFrameHack = this.useFrameHack;
	    this.tabs[i] = tab;
	}

	this.overTab = this.tabs[0];
    },

    onNavOver:function( tab ) {	
	this.overTab = tab;
	tab.highlight();
	clearTimeout( this.timerId );
	this.timerId = setTimeout( "OBS.TabGroup.openMenu()", this.openDelay );
    },

    onNavOut:function( tab ) {	
	this.overTab = null;
	tab.dehighlight();
    },

    openMenu:function() {
	// no need to re-open the same, already open tab
	if ( this.overTab == this.openTab ) return;

	// if there is one open, close it, otherwise
	if ( this.openTab ) {
	  // close current tab first
	  this.openTab.close();
	}
	else {
	  // no tab open, so open new tab
	  this.openTab = this.overTab;
	  this.openTab.open();
	}
    },

    onMenuOpen:function( tab ) {
    },

    onMenuClose:function() {
	this.openTab = null;
	this.isClosing = false;
  	if ( this.overTab ) {
	    this.openTab = this.overTab;
	    this.openTab.open();
	}
    },

    onMouseMove:function(event) {
	this.mousex = event.clientX;
	this.mousey = event.clientY;

	if ( this.openTab && !this.overTab ) {
	    if ( !this.openTab.isOverMenu( this.mousex, this.mousey ) ) {
		if ( !this.isClosing ) {
		    this.isClosing = true;
		    this.timerId = setTimeout( "OBS.TabGroup.close()", this.closeDelay );
		}
	    }
	    else {
	        clearTimeout( this.timerId );
	    }
	}
    },

    close:function() {
	if (this.openTab) this.openTab.close();
    }
}

Event.observe(window, 'load', function() {
    OBS.TabGroup.init();
});


/* obsolete functions */
function initTopNav() {};
function setActiveTab(iTab) {};

