// ===========================================================
// Advanced Link Photonics home.js v1.0.1
// ===========================================================

// ===========================================================
// initializing
// framework: prototype/scriptaculous
// ===========================================================
document.observe("dom:loaded", function() {
    // init
    $$('noscript').invoke('hide');
    initMenu();
	StartSlideShow();
	initTicker();
	slideMenu.build('sm',321,3,3);
	iniToolTip();
});

// ===========================================================
// Drop Down Navigation Menu
// framework: prototype/scriptaculous
// ===========================================================
var Menu = Class.create();
Menu.prototype = {

    initialize: function(idOrElement, name, customConfigFunction) {

        this.name = name;
        this.type = "menu";
        this.closeDelayTimer = null;
        this.closingMenuItem = null;

        this.config();
        if (typeof customConfigFunction == "function") {
            this.customConfig = customConfigFunction;
            this.customConfig();
        }
        this.rootContainer = new MenuContainer(idOrElement, this);
    },

    config: function() {
      this.collapseBorders = true;
      this.quickCollapse = true;
      this.closeDelayTime = 500;
    }

}

var MenuContainer = Class.create();
MenuContainer.prototype = {
    initialize: function(idOrElement, parent) {
        this.type = "menuContainer";
          this.menuItems = [];
        this.init(idOrElement, parent);
    },

    init: function(idOrElement, parent) {
      this.element = $(idOrElement);
      this.parent = parent;
      this.parentMenu = (this.type == "menuContainer") ? ((parent) ? parent.parent : null) : parent;
      this.root = parent instanceof Menu ? parent : parent.root;
      this.id = this.element.id;

      if (this.type == "menuContainer") {
          if (this.element.hasClassName("level1")) this.menuType = "horizontal";
        else if (this.element.hasClassName("level2")) this.menuType = "dropdown";
        else this.menuType = "flyout";

        if (this.menuType == "flyout" || this.menuType == "dropdown") {
          this.isOpen = false;
          Element.setStyle(this.element,{
              position: "absolute",
              top: "0px",
              left: "0px",
              visibility: "hidden"});
        } else {
          this.isOpen = true;
        }
      } else {
        this.isOpen = this.parentMenu.isOpen;
      }

      var childNodes = this.element.childNodes;
      if (childNodes == null) return;

      for (var i = 0; i < childNodes.length; i++) {
        var node = childNodes[i];
        if (node.nodeType == 1) {
          if (this.type == "menuContainer") {
            if (node.tagName.toLowerCase() == "li") {
              this.menuItems.push(new MenuItem(node, this));
            }
          } else {
            if (node.tagName.toLowerCase() == "ul") {
              this.subMenu = new MenuContainer(node, this);
            }
          }
        }
      }
    },

    getBorders: function(element) {
      var ltrb = ["Left","Top","Right","Bottom"];
      var result = {};
      for (var i = 0; i < ltrb.length; ++i) {
        if (this.element.currentStyle)
          var value = parseInt(this.element.currentStyle["border"+ltrb[i]+"Width"]);
        else if (window.getComputedStyle)
          var value = parseInt(window.getComputedStyle(this.element, "").getPropertyValue("border-"+ltrb[i].toLowerCase()+"-width"));
        else
          var value = parseInt(this.element.style["border"+ltrb[i]]);
        result[ltrb[i].toLowerCase()] = isNaN(value) ? 0 : value;
      }
      return result;
    },

    open: function() {
      if (this.root.closeDelayTimer) window.clearTimeout(this.root.closeDelayTimer);
      this.parentMenu.closeAll(this);
      this.isOpen = true;
      if (this.menuType == "dropdown") {
        Element.setStyle(this.element,{
            left: (Position.positionedOffset(this.parent.element)[0]) + "px",
            top: (Position.positionedOffset(this.parent.element)[1] + Element.getHeight(this.parent.element)) + "px"
        });

      } else if (this.menuType == "flyout") {
        var parentMenuBorders = this.parentMenu ? this.parentMenu.getBorders() : new Object();
        var thisBorders = this.getBorders();
        if (
          (Position.positionedOffset(this.parentMenu.element)[0] + this.parentMenu.element.offsetWidth + this.element.offsetWidth + 20) >
          (window.innerWidth ? window.innerWidth : document.body.offsetWidth)
        ) {
            Element.setStyle(this.element,{
                  left: (- this.element.offsetWidth - (this.root.collapseBorders ?  0 : parentMenuBorders["left"])) + "px"
            });
        } else {
            Element.setStyle(this.element,{
                left: (this.parentMenu.element.offsetWidth - parentMenuBorders["left"] - (this.root.collapseBorders ?  Math.min(parentMenuBorders["right"], thisBorders["left"]) : 0)) + "px"
            });
        }
        Element.setStyle(this.element,{
            top: (this.parent.element.offsetTop - parentMenuBorders["top"] - this.menuItems[0].element.offsetTop) + "px"
        });
      }
      Element.setStyle(this.element,{visibility: "visible"});
    },

    close: function() {
        Element.setStyle(this.element,{visibility: "hidden"});
        this.isOpen = false;
        this.closeAll();
    },

    closeAll: function(trigger) {
        for (var i = 0; i < this.menuItems.length; ++i) {
            this.menuItems[i].closeItem(trigger);
        }
    }

}


var MenuItem = Class.create();

Object.extend(Object.extend(MenuItem.prototype, MenuContainer.prototype), {
    initialize: function(idOrElement, parent) {
        var menuItem = this;
        this.type = "menuItem";
        this.subMenu;
        this.init(idOrElement, parent);
        if (this.subMenu) {
            this.element.onmouseover = function() {
                menuItem.subMenu.open();
            }
        } else {
        if (this.root.quickCollapse) {
          this.element.onmouseover = function() {
            menuItem.parentMenu.closeAll();
          }
        }
          }
          var linkTag = this.element.getElementsByTagName("A")[0];
          if (linkTag) {
         linkTag.onfocus = this.element.onmouseover;
         this.link = linkTag;
         this.text = linkTag.text;
          }
          if (this.subMenu) {
        this.element.onmouseout = function() {
          if (menuItem.root.openDelayTimer) window.clearTimeout(menuItem.root.openDelayTimer);
          if (menuItem.root.closeDelayTimer) window.clearTimeout(menuItem.root.closeDelayTimer);
          eval(menuItem.root.name + ".closingMenuItem = menuItem");
          menuItem.root.closeDelayTimer = window.setTimeout(menuItem.root.name + ".closingMenuItem.subMenu.close()", menuItem.root.closeDelayTime);
        }
          }
    },

    openItem: function() {
      this.isOpen = true;
      if (this.subMenu) { this.subMenu.open(); }
    },

    closeItem: function(trigger) {
      this.isOpen = false;
      if (this.subMenu) {
        if (this.subMenu != trigger) this.subMenu.close();
      }
    }
});


var menu;


function configMenu() {
  this.closeDelayTime = 300;
}

function initMenu() {
  menu = new Menu('root', 'menu', configMenu);
}
// ===========================================================
// Display Date
// framework: javascript
// ===========================================================
function displayDate() {
    var mydate=new Date();
    var year=mydate.getYear();
    if (year < 1000) {
        year+=1900;
    }
    var day=mydate.getDay();
    var month=mydate.getMonth();
    var daym=mydate.getDate();
    if (daym<10) {
        daym="0"+daym;
    }
    var dayarray=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
    var montharray=new Array("January","February","March","April","May","June","July","August","September","October","November","December");
    document.write(""+dayarray[day]+", "+montharray[month]+" "+daym+", "+year+"");
}
// ===========================================================
// Slideshow
// framework: prototype/scriptaculous
// ===========================================================
// set the starting image.
var i = 0;			

// The array of div names which will hold the images.
var image_slide = new Array('image-1', 'image-2');

// The number of images in the array.
var NumOfImages = image_slide.length;

// The time to wait before moving to the next image. Set to 3 seconds by default.
var wait = 8000;

// The Fade Function
function SwapImage(x,y) {		
	$(image_slide[x]).appear({ duration: 1.5 });
	$(image_slide[y]).fade({duration: 1.5});
}

// the onload event handler that starts the fading.
function StartSlideShow() {
	play = setInterval('Play()',wait);
	//$('PlayButton').hide();
	//$('PauseButton').appear({ duration: 0});
								
}

function Play() {
	var imageShow, imageHide;

	imageShow = i+1;
	imageHide = i;
	
	if (imageShow == NumOfImages) {
		SwapImage(0,imageHide);	
		i = 0;					
	} else {
		SwapImage(imageShow,imageHide);			
		i++;
	}
}
/*
function Stop () {
	clearInterval(play);				
	$('PlayButton').appear({ duration: 0});
	$('PauseButton').hide();
}

function GoNext() {
	clearInterval(play);
	$('PlayButton').appear({ duration: 0});
	$('PauseButton').hide();
	
	var imageShow, imageHide;

	imageShow = i+1;
	imageHide = i;
	
	if (imageShow == NumOfImages) {
		SwapImage(0,imageHide);	
		i = 0;					
	} else {
		SwapImage(imageShow,imageHide);			
		i++;
	}
}

function GoPrevious() {
	clearInterval(play);
	$('PlayButton').appear({ duration: 0});
	$('PauseButton').hide();

	var imageShow, imageHide;
				
	imageShow = i-1;
	imageHide = i;
	
	if (i == 0) {
		SwapImage(NumOfImages-1,imageHide);	
		i = NumOfImages-1;		
		
		//alert(NumOfImages-1 + ' and ' + imageHide + ' i=' + i)
					
	} else {
		SwapImage(imageShow,imageHide);			
		i--;
		
		//alert(imageShow + ' and ' + imageHide)
	}
}*/
// ===========================================================
// News ticker
// framework: prototype/scriptaculous
// ===========================================================
// Create namespace
if (at == undefined) var at = {};
if (at.bartelme == undefined) at.bartelme = {};

// Newsticker Class
at.bartelme.newsticker = Class.create();
at.bartelme.newsticker.prototype = {
	initialize: function()
	{
		// Get elements
		this.interval = 10000;
		this.container = $("headlines");
		this.messages  = $A(this.container.getElementsByTagName("li"));
		this.number_of_messages = this.messages.length;
		if (this.number_of_messages == 0)
		{
			this.showError();
			return false;
		}
		this.current_message = 0;
		this.previous_message = null;
		/*
		// Create toggle button
		this.toggle_button = document.createElement("a");
		this.toggle_button.href = "#";
		this.toggle_button.id = "togglenewsticker";
		this.toggle_button.innerHTML = "Toggle";
		Event.observe(this.toggle_button, "click", this.toggle.bindAsEventListener(this), false);
		this.container.appendChild(this.toggle_button);
		this.hideMessages();
		this.showMessage();
		*/
		// Install timer
		this.timer = setInterval(this.showMessage.bind(this), this.interval);
  	},
	showMessage: function()
	{
		Effect.Appear(this.messages[this.current_message]);
		setTimeout(this.fadeMessage.bind(this), this.interval-2000);
		if (this.current_message < this.number_of_messages-1)
		{
			this.previous_message = this.current_message;
			this.current_message = this.current_message + 1;
		} else {
			this.current_message = 0;
			this.previous_message = this.number_of_messages - 1;
		}
	},
	fadeMessage: function()
	{
		Effect.Fade(this.messages[this.previous_message]);
	},
	hideMessages: function()
	{
		this.messages.each(function(message)
		{
			Element.hide(message);
		})
	},
	/*
	toggle: function()
	{
		Effect.BlindUp(this.container, 1000);
	},
	*/
	showError: function()
	{
		if (this.container.getElementsByTagName("ul").length == 0)
		{
			this.list = document.createElement("ul");
			this.container.appendChild(this.list);
		} else {
			this.list = this.container.getElementsByTagName("ul")[0];
		}
		this.errorMessage = document.createElement("li");
		this.errorMessage.className = "error";
		this.errorMessage.innerHTML = "Could not retrieve data";
		this.list.appendChild(this.errorMessage);
	}
}

var ticker;

function initTicker() {
    ticker = new at.bartelme.newsticker();
}
// ===========================================================
// Accordin
// framework: javascript
// ===========================================================
var slideMenu=function(){
	var sp,st,t,m,sa,l,w,gw,ot;
	return{
		build:function(sm,sw,mt,s,sl,h){
			sp=s; st=sw; t=mt;
			m=document.getElementById(sm);
			sa=m.getElementsByTagName('li');
			l=sa.length; w=m.offsetWidth; gw=w/l;
			ot=Math.floor((w-st)/(l-1)); var i=0;
			for(i;i<l;i++){s=sa[i]; s.style.width=gw+'px'; this.timer(s)}
			if(sl!=null){m.timer=setInterval(function(){slideMenu.slide(sa[sl-1])},t)}
		},
		timer:function(s){
			s.onmouseover=function(){clearInterval(m.htimer);clearInterval(m.timer);m.timer=setInterval(function(){slideMenu.slide(s)},t)}
			s.onmouseout=function(){clearInterval(m.timer);clearInterval(m.htimer);m.htimer=setInterval(function(){slideMenu.slide(s,true)},t)}
		},
		slide:function(s,c){
			var cw=parseInt(s.style.width);
			if((cw<st && !c) || (cw>gw && c)){
				var owt=0; var i=0;
				for(i;i<l;i++){
					if(sa[i]!=s){
						var o,ow; var oi=0; o=sa[i]; ow=parseInt(o.style.width);
						if(ow<gw && c){oi=Math.floor((gw-ow)/sp); oi=(oi>0)?oi:1; o.style.width=(ow+oi)+'px';
						}else if(ow>ot && !c){oi=Math.floor((ow-ot)/sp); oi=(oi>0)?oi:1; o.style.width=(ow-oi)+'px'}
						if(c){owt=owt+(ow+oi)}else{owt=owt+(ow-oi)}}}
				s.style.width=(w-owt)+'px';
			}else{clearInterval(m.timer);clearInterval(m.htimer)}
		}
	};
}();
// ===========================================================
// CoolTip
// framework: prototype/scriptaculous
// ===========================================================
var Tooltips = Class.create();
Tooltips.prototype = {
	initialize: function(selector, options) {
		var tooltips = $$(selector);
		tooltips.each( function(tooltip) {
			new Tooltip(tooltip, options);
		});
	}
};
// Tooltip Class
var Tooltip = Class.create();
Tooltip.prototype = {
	initialize: function(el, options) {
		this.el = $(el);
		this.initialized = false;
		this.setOptions(options);
		
		// Event handlers
		this.showEvent = this.show.bindAsEventListener(this);
		this.hideEvent = this.hide.bindAsEventListener(this);
		this.updateEvent = this.update.bindAsEventListener(this);
		Event.observe(this.el, "mouseover", this.showEvent );
		Event.observe(this.el, "mouseout", this.hideEvent );
		if (options && options['content']) {
			this.content = $(options['content']).innerHTML;
		} else {
			this.content = this.el.title.stripScripts().strip();
		}
		this.content = this.el.title.stripScripts().strip();
		this.el.title = "";
		this.el.descendants().each(function(el){
			if(Element.readAttribute(el, 'alt'))
				el.alt = "";
		});
	},
	setOptions: function(options) {
		this.options = {
			backgroundColor: '#299bfb',
			borderColor: '#10497a',
			textColor: '',
			textShadowColor: '',
			maxWidth: 400,
			align: "left",
			delay: 150,
			mouseFollow: true,
			opacity: 1.0,
			appearDuration: .1,
			hideDuration: .1
		};
		Object.extend(this.options, options || {});
	},
	show: function(e) {
		this.xCord = Event.pointerX(e);
		this.yCord = Event.pointerY(e);
		if(!this.initialized)
			this.timeout = window.setTimeout(this.appear.bind(this), this.options.delay);
	},
	hide: function(e) {
		if(this.initialized) {
			this.appearingFX.cancel();
			if(this.options.mouseFollow)
				Event.stopObserving(this.el, "mousemove", this.updateEvent);
			new Effect.Fade(this.tooltip, {duration: this.options.hideDuration, afterFinish: function() { Element.remove(this.tooltip) }.bind(this) });
		}
		this._clearTimeout(this.timeout);
		
		this.initialized = false;
	},
	update: function(e){
		this.xCord = Event.pointerX(e);
		this.yCord = Event.pointerY(e);
		this.setup();
	},
	appear: function() {
		this.tooltip = new Element("div", { className: "tooltip", style: "display: none" });
		
		var arrow = new Element("div", { className: "xarrow" }).insert('<b class="a6"></b><b class="a5"></b><b class="a4"></b><b class="a3"></b><b class="a2"></b><b class="a1"></b>');
		
		var top = new Element("div", { className: "xtop" }).insert(
			new Element("div", { className: "xb1", style: "background-color:" + this.options.borderColor + ";" })
		).insert(
			new Element("div", { className: "xb2", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";" })
		).insert(
			new Element("div", { className: "xb3", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";" })
		).insert(
			new Element("div", { className: "xb4", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";" })
		);
		
		var bottom = new Element("div", { className: "xbottom" }).insert(
			new Element("div", { className: "xb4", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";" })
		).insert(
			new Element("div", { className: "xb3", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";" })
		).insert(
			new Element("div", { className: "xb2", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";" })
		).insert(
			new Element("div", { className: "xb1", style:"background-color:" + this.options.borderColor + ";" })
		);
		
		var content = new Element("div", { className: "xboxcontent", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + 
			((this.options.textColor != '') ? "; color:" + this.options.textColor : "") + 
			((this.options.textShadowColor != '') ? "; text-shadow:2px 2px 0" + this.options.textShadowColor + ";" : "") }).update(this.content);
		this.tooltip.insert(top).insert(content).insert(bottom).insert(arrow);
		$(document.body).insert({'top':this.tooltip});
		this.tooltip.select('.xarrow b').each(function(el){
			if(!el.hasClassName('a1'))
				el.setStyle({backgroundColor: this.options.backgroundColor, borderColor: this.options.borderColor });
			else
				el.setStyle({backgroundColor: this.options.borderColor });
		}.bind(this));
		
		Element.extend(this.tooltip); 
		this.options.width = this.tooltip.getWidth() + 1;
		this.tooltip.style.width = this.options.width + 'px';
		
		this.setup();
		
		if(this.options.mouseFollow)
			Event.observe(this.el, "mousemove", this.updateEvent);
			
		this.initialized = true;
		this.appearingFX = new Effect.Appear(this.tooltip, {duration: this.options.appearDuration, to: this.options.opacity });
	},
	setup: function(){
		if(this.options.width > this.options.maxWidth) {
			this.options.width = this.options.maxWidth;
			this.tooltip.style.width = this.options.width + 'px';
		}
		if(this.xCord + this.options.width >= Element.getWidth(document.body)) {
			this.options.align = "right";
			this.xCord = this.xCord - this.options.width + 20;
			this.tooltip.down('.xarrow').setStyle({left: this.options.width - 24 + 'px'});
		} else {
			this.options.align = "left";
			this.tooltip.down('.xarrow').setStyle({left: 12 + 'px'});
		}
		
		this.tooltip.style.left = this.xCord - 7 + "px";
		this.tooltip.style.top = this.yCord - this.tooltip.getHeight() + "px";
	},
	_clearTimeout: function(timer) {
		clearTimeout(timer);
		clearInterval(timer);
		return null;
	}
};

function iniToolTip() {
     $$(".help").each( function(link) {
		new Tooltip(link, {mouseFollow: true});
	});
}
