var menuHilight = {
init: 	function(){	
			var menuItems = ['about','prod','app','ind','ir'];
			
			var url = document.location.href;				
			var subdirs = [];
			url.scan(/[A-Za-z0-9_-]+/, function(m){ subdirs.push(m[0]); } );  //seperate url at each word
	
			$('nav').getElementsBySelector('a').each( function(e){
								var page = e.href.substring( e.href.lastIndexOf('/') + 1 );
																
								subdirs.each( function(dir){
									if(dir == page)
									{								
										e.setStyle( {backgroundColor:'#f3ba21'} );
										
										var partClass = e.className.split(' ');
										partClass 	  = partClass[0];
										
										if( menuItems.indexOf(partClass) != -1 )
										{ // if class name exists in menuItems array, replace image											
											e.setStyle( {background: 'url(/img/nav/' + partClass +'_o.gif) top left no-repeat'} );
										}
									}
								});
								}
							);
	}
};

/**
* Workaround for target="_blank"
*/ 
var TargetBlank = Class.create();
TargetBlank.prototype = {
	initialize: function()
	{
		$$('a[rel="external"]').each(function(e){e.target='_blank';});
	}
}

var IndexScroller = Class.create();
IndexScroller.prototype = {
	initialize: function()
	{
		if( null == $('ticker') ) { return; }
		$('ticker').setStyle({display:'none'});
		Effect.Appear('ticker2',3);
	}
}

/**
*	Go back one page
*/
var HistoryBack = Class.create();
HistoryBack.prototype = {
	initialize: function()
	{
		if( null == $('back') ) { return; }
		
		Event.observe('back','click', function(e){
						history.back(-1);												   
						Event.stop(e);
											   }
					 );
		
		Event.observe('print','click', function(e){
						window.print();												   
						Event.stop(e);
											   }
					 );		
	}
}



/**
*	hide/show descriptions for search results
*/
var SearchDescriptions = Class.create();
SearchDescriptions.prototype = {
	initialize: function()
	{
		$('shdesc').observe('click', this.toggleDesc.bindAsEventListener(this));
	},
	
	toggleDesc: function()
	{
		$$('ul#searchres li p.desc').invoke('toggle');
		$$('ul#searchres li b').invoke('toggle');
	}
}

/**
* Hides addresses in location.php. Makes them visible when header is clicked
* var hideitems: CSS selector of items which should be hidden
* var clickitems: CSS selector or items which should show hidden items on click
* var showItem: container to make visible again after a click
*/
var HideItems = Class.create();
HideItems.prototype = {
	initialize: function(hideitems, clickitems) 
	{
    	this.hideitems 		= hideitems;
		this.clickitems 	= clickitems;
		this.itemsToHide  	= $$(this.hideitems);
	    this.itemsToClick 	= $$(this.clickitems);
		this.showItem		= this.show.bindAsEventListener(this);
		this.moverItem		= this.mover.bindAsEventListener(this);
		this.moutItem		= this.mout.bindAsEventListener(this);
		this.FontColor		= '';
		
		this.itemsToHide.invoke('hide');  	
		this.itemsToClick.each(function(e){ 
				this.FontColor = e.getStyle('color');
				e.observe('click', this.showItem);
				e.observe('mouseover', this.moverItem );
				e.observe('mouseout', this.moutItem);
				e.setStyle( {textDecoration:'underline',cursor:'pointer'} );
		}.bind(this)
		);
	
	},

	mover: function(e) 
	{
		Event.element(e).setStyle( {color:'#f3ba21'} );
	},
	
	mout: function(e) 
	{
		Event.element(e).setStyle( {color:this.FontColor} );
	},	

	show: function(e) 
	{
		Event.element(e).next().toggle();
	}  
};

/**
* Alternate colors for rows in tables
*/
var AlternateRows = Class.create();
AlternateRows.prototype = {
	initialize: function(cssclass){
		this.cssclass = cssclass;
		$$('table.' + this.cssclass + ' tbody tr:nth-child(even)').invoke('addClassName','even');
	}
};

/**
*	JS for Z Probe order form
*/ 
var ZprobeOrder = Class.create();
ZprobeOrder.prototype = {
	initialize: function(){		
		new Form.Element.Observer('Probe_Type',0.7, this.typeChange );
		new Form.Element.Observer('slimset',0.3, this.tempChange ); 
	},
	
	typeChange: function(el, value){
		$A(document.getElementsByClassName('zpinfo')).invoke('hide');
		this.value = value;
		
		switch(this.value){
			case '|Z|Probe':
				$('ptzp').setStyle({display:'block'});
				break;
			case 'Dual |Z| Probe':
				$('ptdp').setStyle({display:'block'});
				break;
			case '|Z|Probe PCB':
				$('ptpc').setStyle({display:'block'});
				break;
			default:
				console.log('NOTHING');
				break;
		};
	},
	
	tempChange: function(el, value){
			$('standard').toggle();
			$('standard').next(0).toggle();
	}
};


var c4npFaq = {

init: function(){
			$$('#main ul.faq p').invoke('setStyle',{display:'none'});		
			$$('#main ul.faq a').invoke('observe','click', c4npFaq.show );
		},

show: function(e){
			$$('#main ul.faq p').invoke('setStyle',{display:'none'});
			el = Event.element(e);
			el.setStyle({fontWeight:'bold'});
			el.siblings().each( function(e){ 
									e.setStyle( {display:'block',padding:'3px'} );
									new Effect.ScrollTo(e);
									new Effect.Highlight(e, {startcolor:'#ffffff',
														 	endcolor:'#f3ba21',
															restorecolor:'#f3ba21',
															duration:2});
									} 
								);
		}
}

var jsWin = {
	
init: function(){
		  if($('compchart')){
			  Event.observe('compchart', 'click', jsWin.initC4NPchart);
		  }
		  
		  if($('flow')){
			  Event.observe('flow', 'click', jsWin.initC4NPflow);
		  }
		  
		  if($('mft')){
			  Event.observe('mft', 'click', jsWin.initC4NPmft);
		  }

		  if($('mit')){
			  Event.observe('mit', 'click', jsWin.initC4NPmit);
		  }
		  
		  if($('ubm')){
			  Event.observe('ubm', 'click', jsWin.initC4NPubm);
		  }	
		  
		  if($('sb6e')){
			  Event.observe('sb6e', 'click', jsWin.initSb6train);
		  }	
		  
		  if($('memsproc')){
			  Event.observe('memsproc', 'click', jsWin.initMemsproc);
		  }
          
          if($('mapvaih')){
              Event.observe('mapvaih', 'click', jsWin.initMapvaih);
          }
          
          if($('mapgar')){
              Event.observe('mapgar', 'click', jsWin.initMapgar);
          }
          
          if($('mapsac')){
              Event.observe('mapsac', 'click', jsWin.initMapsac);
          }            
          
          if($('mapwat')){
              Event.observe('mapwat', 'click', jsWin.initMapwat);
          }            
},

initMapwat: function(){
        jsWin.url         = '/about_suss/map_waterbury';
        jsWin.width     = 650;
        jsWin.height     = 530;
        jsWin.okLabel    = 'Close';
        jsWin.dialog();
},                                                    

initMapsac: function(){
        jsWin.url         = '/about_suss/map_sacka';
        jsWin.width     = 650;
        jsWin.height     = 530;
        jsWin.okLabel    = 'Close';
        jsWin.dialog();
},

initMapgar: function(){
        jsWin.url         = '/about_suss/map_garching';
        jsWin.width     = 650;
        jsWin.height     = 530;
        jsWin.okLabel    = 'Close';
        jsWin.dialog();
},

initMapvaih: function(){
        jsWin.url         = '/about_suss/map_vaihingen';
        jsWin.width     = 650;
        jsWin.height     = 530;
        jsWin.okLabel    = 'Close';
        jsWin.dialog();
},

initSb6train: function(){
		jsWin.url 		= '/products/training/sb6e_course_description';
		jsWin.width 	= 650;
		jsWin.height 	= 420;
		jsWin.okLabel	= 'Close';
		jsWin.dialog();
},

initMemsproc: function(){
		jsWin.url 		= '/industries/mems/mems_process';
		jsWin.width 	= 650;
		jsWin.height 	= 420;
		jsWin.okLabel	= 'Close';
		jsWin.dialog();
},

initC4NPubm: function(){
		jsWin.url 		= '/products/c4np/c4np_ubm.php';
		jsWin.width 	= 350;
		jsWin.height 	= 380;
		jsWin.okLabel	= 'Close';
		jsWin.dialog();
},

initC4NPmit: function(){
		jsWin.url 		= '/products/c4np/c4np_mit.php';
		jsWin.width 	= 530;
		jsWin.height 	= 520;
		jsWin.okLabel	= 'Close';
		jsWin.dialog();
},

initC4NPmft: function(){
		jsWin.url 		= '/products/c4np/c4np_mft.php';
		jsWin.width 	= 530;
		jsWin.height 	= 520;
		jsWin.okLabel	= 'Close';
		jsWin.dialog();
},

initC4NPflow: function(){
		jsWin.url 		= '/products/c4np/c4np_flow_chart.php';
		jsWin.width 	= 500;
		jsWin.height 	= 600;
		jsWin.okLabel	= 'Close';
		jsWin.dialog();
},

initC4NPchart: function(){
		jsWin.url 		= '/products/c4np/c4np_comparison_chart.php';
		jsWin.width 	= 620;
		jsWin.height 	= 450;
		jsWin.okLabel	= 'Close';
		jsWin.dialog();
},

initELANCB8flash: function(){
		jsWin.url 		= '/products/wafer_bonder/semi_automated_wafer_bonders/ELAN_CB8_flash.php';
		jsWin.width 	= 320;
		jsWin.height 	= 260;
		jsWin.okLabel	= 'Close';
		jsWin.dialog();
},

dialog: function(){
		Dialog.alert({url: jsWin.url, 
					  options: {method: 'post'}
					  }, 
					  {windowParameters: {className: "alphacube",
										  width: jsWin.width,
										  height: jsWin.height}, 
     									  okLabel: jsWin.okLabel}
					 );
	}
}

function menuInit() {
	var uls = document.getElementsByTagName('ul');
    for (var u = 0; u < uls.length; u++) {
        if (uls[u].className.search(/\bslidingmenu\b/) == -1) {continue}
		var lis = uls[u].getElementsByTagName('li');
	    for (var i = 0; i < lis.length; i++) {
	      var node = lis[i];
	      if (node.nodeName.toLowerCase() == 'li' &&
	          node.getElementsByTagName('ul').length > 0) {
	        Event.observe(node, 'mouseover', getMoverFor(node));
	        Event.observe(node, 'mouseout', getMoutFor(node));
	        node.getElementsBySelector('a').first().className += ' subheader';
	      }
	    }
  }
}

function getMoverFor(node) {
  return function(e) { mover(e, node); };
}

function getMoutFor(node) {
  return function(e) { mout(e, node); };
}

function mover(e, targetElement) {
  var el = window.event ? targetElement : e ? e.currentTarget : null;
  if (!el){ return }
  clearTimeout(el.outTimeout);
  for (var i = 0; i < el.childNodes.length; i++) {
    var node = el.childNodes[i];
	if (node.nodeName.toLowerCase() == 'ul') {
	      node.style.display = 'block';
    }
  }
}

function mout(e, targetElement) {
  var el = window.event ? targetElement : e ? e.currentTarget : null;
  if (!el) {return}
  el.outTimeout = setTimeout(function() { mout2(el); }, 400);	/*Menu Delay Time*/
}

function mout2(el) {
  for (var i = 0; i < el.childNodes.length; i++) {
    var node = el.childNodes[i];
    if (node.nodeName.toLowerCase() == 'ul') {
      node.style.display = 'none';
    }
  }
}

/*
Enhanced Image Replacement
http://www.clagnut.com/blog/1451/
*/
function checkImages() {
	if ( '250' != $('imgrep').offsetWidth ) {
      $$('a').invoke('setStyle',{textIndent:"0"} );
    }
}

/* Image Scroller */
var cF = {
	init: function(){
		if(typeof(objJSON) !== 'undefined')
		{
			Event.observe('next','click', cF.updatePic);
			Event.observe('prev','click', cF.updatePic);
			var quote = $('replace').getElementsBySelector('p')[0];
			/*quote.setStyle({height:'260px'});
			if(quote != ''){
				quote.setStyle({height:'auto'});
			}*/
		}
		
		if($('replace')){
			initLightbox();
		}
},

	updatePic: function(e) {
		var url = $('cfimg').src;
		var d 	= 0;		// change image file path no/yes

		// checks if current url is not english version
		if ( -1 !== document.URL.indexOf('/de/') ||
			-1 !== document.URL.indexOf('/cn/') ||
			-1 !== document.URL.indexOf('/tw/') ||
			-1 !== document.URL.indexOf('/jp/')
			) 
		{	
				var d = 1;	
		}

		var i = url.substring(url.lastIndexOf('/') + 1 ,url.length - 4); // find name of image and remove ". jpg"
		var f = Event.element(e).parentNode.id; // "next" or "prev" click
		var ind = 0; // index of JSON object
		var p = ''; //name of next pic to show
		var t = ''; //title of next pic to show
		var l = 0;  // number of pictures
		var q = ''; //quote

			
			
		objJSON.pictures.each(function(e,ind)
		{
			if(e.name == i)
			{
				switch(f)
				{
					case 'next':
						ind++;
						if(ind > objJSON.pictures.length - 1){
							ind = 0;
						}
						break;
					case 'prev':
						ind--;
						if(ind < 0){
							ind = objJSON.pictures.length - 1;
						}
						break;
					default:
						break;
				}//end of switch					

				p = objJSON.pictures[ind].name;
				t = escape(objJSON.pictures[ind].title); //caption of pic
				i = objJSON.pictures[ind].id;
				l = objJSON.pictures.length;			
				q = escape(objJSON.pictures[ind].quote);
				if(q === 'undefined'){q = ''}
			}//enf of if
		});

		var ajax =  new Ajax.Updater('replace','/imgscrollc.php',{
							method:'post',
							parameters: 'p=' + p + 
										'&t=' + t +
										'&i=' + i +
										'&l=' + l + 
										'&q=' + q +
										'&d=' + d,
							onComplete: cF.init
							});
	}
}

/**
* Google Analytics Download Tracker
*/
var GoogleTracker = Class.create();
GoogleTracker.prototype = {
	initialize: function()
	{
		this.clickedLinkListener = this.clickedLink.bindAsEventListener(this);
		$$('a.pdf').invoke('observe', 'click', this.clickedLinkListener);
	},
	
	clickedLink: function(el)
	{
		this.el  = Event.element(el);
		this.linkName = this.el.up(1).previous().innerHTML;
		this.finalLink = this.linkName.gsub(' ', '_');
		urchinTracker('/downloads/' + this.finalLink);
	}
};
 
FastInit.addOnLoad( menuInit,
					menuHilight.init,					
                    cF.init,
					jsWin.init,
					c4npFaq.init,
					
                    function() { new HistoryBack();
								 /*
                                 if( $('Email') && null == $('gxps')){
			    			        $('Email').focus();
								 }else if( $('sinput') ){
			    			        $('sinput').focus();
								 };
                                 */
								 if( $('db-techp') ) {new HideItems( 'div#db-techp div.hide', 'div#db-techp h2'); };
    							 if($('sidebar')) {new HideItems('ul.hide ul', 'ul.hide li em');};
        						 if($('locations')) {new HideItems('#locations div.col2 div.divhide', '#locations div.col2 em');};
								 if($('memslist')) {new HideItems('#memslist ul li div.divhide', '#memslist ul li em');};
          						 if($('c_rep')) {new HideItems('#h_rep', '#c_rep');};
								 if( document.getElementsByTagName('table').length > 0 ){new AlternateRows('altrow');};									
								 SortableTable.load();
								 if($('zprobe')){ new ZprobeOrder();};
								 if( $('shdesc') ){ new SearchDescriptions();};
								 new TargetBlank();
								 //setTimeout( function() {new IndexScroller(); },11000 );
								 if ( $('page') ) {
									$('width').value = screen.width;
									$('height').value = screen.height;
								};
					}
);

Event.observe(window, "load", 
			  function(){ 	
				checkImages();
			  }
);