/**
 * misc functions for site
 */

function showTab( elem ) {
    var tabLi = document.getElementById( "tab"+elem );
    tabLi.className = "homeTab current";

    var e = document.getElementById( "tab"+elem+"Content" );
    e.className = "tabVisible";
}

function hideTab( elem ) {
    var tabLi = document.getElementById( "tab"+elem );
    tabLi.className = "homeTab";

    var e = document.getElementById( "tab"+elem+"Content" );
    e.className = "tabHidden";
}

// function to hide a ShowHide div
function hideDiv(divName) {
	var theDiv = document.getElementById(divName+"ShowHide");
	if (theDiv) {
		theDiv.className="divHide";
	}
}

// function to show a ShowHide div
function showDiv(divName) {
	var theDiv = document.getElementById(divName+"ShowHide");
	if (theDiv) {
		theDiv.className="divShow";
	}
}


function rollOver(obj)
{
	obj.firstChild.src = obj.firstChild.src.substring(0,obj.firstChild.src.length-4) + "_over.gif";
}

function restore(obj)
{
	obj.firstChild.src = obj.firstChild.src.substring(0,obj.firstChild.src.length-9) + ".gif";
}


/* 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 aciron = (aciron)?(aciron):({});

/**
 * 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 );
}

aciron.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() {
	aciron.TabGroup.onNavOver( this.owner );
    }
    if ( this.button ) this.button.onmouseout = function() {
	aciron.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 - 1000)/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();
					aciron.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
 */
aciron.TabGroup =
{
    openDelay: 400, // miliseconds
    closeDelay: 4000, // milliseconds
    openDuration: 350, // milliseconds
    closeDuration: 300, // milliseconds

    nextTab: null,
    overTab: null,

    openTab: null,

    isOpening: false,
    isClosing: false,

    wait: false,
    isOverDropDown: false,

    timerId: null,
    tabNames: ["", "expertise", "clients", "careers", "aboutus", "leadership", "about"],
    tabs: [],
    useFrameHack: false,

    /**
    *
    */
    init: function() {
        Event.observe(document.body, 'mousemove', function(e) { aciron.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 ) {
        if (typeof noMenus != "undefined" && noMenus != true) {
        new Insertion.Before('expertiseMenu', '<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 < aciron.TabGroup.tabNames.length; i++) {
            tab = new TabComponent(i, aciron.TabGroup.tabNames[i], (aciron.TabGroup.openDuration / 1000), (aciron.TabGroup.closeDuration / 1000));
            tab.useFrameHack = aciron.TabGroup.useFrameHack;
            aciron.TabGroup.tabs[i] = tab;
        }
        aciron.TabGroup.overTab = aciron.TabGroup.tabs[0];
    },

    onNavOver: function(tab) {
        this.overTab = tab;
        tab.highlight();
        clearTimeout(this.timerId);
        this.timerId = setTimeout("aciron.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("aciron.TabGroup.close()", this.closeDelay);
                }
            }
            else {
                clearTimeout(this.timerId);
            }
        }
    },

    close: function() {
        if (this.openTab) this.openTab.close();
    }
}

window.onload = aciron.TabGroup.init; //Eventobserve;
function Eventobserve() {
    if (Event) {
        Event.observe(window, 'load', function() {
            aciron.TabGroup.init();
        });
    }
}

/* obsolete functions */
function initTopNav() {};
function setActiveTab(iTab) {};

