
window.addEvent('domready', function() {
	
	// iphone
	if (Browser.Platform.ipod == true) document.body.addClass('iphone');	
	// ie6
	//if (Browser.Engine.trident4 == true) alert('IE6'); //document.body.addClass('ie6');	

	
	this.nav = new ScrollNavigation();
	this.nav.activateBigBtns();
	
	var tree  = new TreeCreator();
	
	this.internlinks = new InternalLinks();
	this.internlinks.init(document.body, 'a.slidelink');
	
	this.menu = new MainMenu();

	//this.menu.translate(['Navigate','']);
	
	this.video = new VideoLauncher();
	
	this.popup = new PopupTechno();
	
	Cufon.replace('h1', { fontFamily: 'Replica-Regular'});
	Cufon.replace('h2', { fontFamily: 'Replica-Regular'});
	
	// center menu on homepage:
	var w = (818-$('linksmenu').getStyle('width').toInt())/2;
	$('linksmenu').setStyle('margin-left', w);
	
	
	//Cufon.replace('h3', { fontFamily: 'Replica-Regular'});
	
	/*Cufon.replace('h1', {
		//color: '-linear-gradient(white, black)',
		fontFamily: 'Replica-Bold'
	});
	Cufon.replace('h2', {
		fontFamily: 'Replica-Bold'
	});
	Cufon.replace('h3', {
		fontFamily: 'Replica-Bold'
	});*/

});



window.addEvent('load', function() {	
	 //window.nav.navigateTo($('_en_home'));
	 	
	 	(function(){ 
			this.menu.openMenuBox();}.bind(this)
		).delay(3000);

});


  /*********************************************************************************************/



var VideoLauncher = new Class({
	
	initialize: function(){
    }, //end constructor
	
	
	init : function(target){
		
		if (!$$('.videoplayflv')) return;
		
		this.vc = target.getElement('.videocontainer');
		if (this.vc == null) return;
		
		this.vc.fx = new Fx.Tween(this.vc, {'transition': 'quad:out', 'duration':500});
		this.vc.fx.start('opacity', 0);
		 
		this.openbtn = target.getElement('.videoplayflv');
		if (this.openbtn == null) return;
		this.openbtn.addEvent('click', function() {
	  		this.showVideo(); 
	  	}.bind(this));
	  	
	  	this.closebtn  = new Element('a').set({
		    'class': 'close',
		    'text':'Close video',
		    'href':'javascript:void(0)'
		});
		this.closebtn.inject(this.vc);
		this.closebtn.addEvent('click', function() {
	  		this.hideVideo(); 
	  	}.bind(this));

	},
	
	
	showVideo : function(target){
		this.vc.fx.start('opacity', 1);
		this.vc.setStyle('display', 'block');
	},
	
	
	hideVideo : function(target){
		this.vc.fx.start('opacity', 0);
	}  
	 	 
});// end class



  /*********************************************************************************************/



var Gallery = new Class({
	
	initialize: function(target){

        if (!$$('.gallery')) return;
        
        target = $(target);
        this.gallery = target.getElement('.gallery');
        if (this.gallery == null) return;
        this.nav = this.gallery.getElement('.nav');
        
        this.bigimages = target.getElements('.bigimages img');
        
        this.cleanEmptyImages();
        
        this.bigimages.each(function(img) {
			img.index = this.bigimages.indexOf(img);	
			img.fx = new Fx.Tween(img, {'transition': 'quad:out', 'duration':500});	
		}.bind(this));
		
		if (this.bigimages.length < 2) {
			if (this.nav) {
				this.nav.destroy();
			}
			return; //////
		}
		this.actualindex = this.bigimages.length -1;
	    
		this.prev = target.getElement('.nav a.prev');
		this.next = target.getElement('.nav a.next');
	
		this.prev.fx = new Fx.Tween(this.prev, {'transition': 'quad:out', 'duration':1000});
		this.next.fx = new Fx.Tween(this.next, {'transition': 'quad:out', 'duration':1000});
				
		this.prev.addEvent('mouseenter', function() {	this.prev.fx.cancel();this.prev.fx.start('opacity', 0.6);  }.bind(this));
		this.prev.addEvent('mouseleave', function() {	this.prev.fx.cancel();this.prev.fx.start('opacity', 0.01);  }.bind(this));
		this.prev.addEvent('click', function() {  		this.showPrev(); }.bind(this));
		
		this.next.addEvent('mouseenter', function() {	this.next.fx.cancel();this.next.fx.start('opacity', 0.6);  }.bind(this));
		this.next.addEvent('mouseleave', function() {	this.next.fx.cancel();this.next.fx.start('opacity', 0.01);  }.bind(this));
		this.next.addEvent('click', function() {  		this.showNext(); }.bind(this));
		
		(function(){ 
			this.hightlightArrows();}.bind(this)
		).delay(3500);

		
    }, //end constructor
	
	hightlightArrows : function(){
		this.prev.fx.start('opacity', 1, 0.01);
		this.next.fx.start('opacity', 1, 0.01);

	},

	 
	cleanEmptyImages : function(){
		this.bigimages.each(function(img, i) {
			if (img.get('src') == null){
				this.bigimages[i].destroy();	
				this.bigimages[i] = null;
			}
		}.bind(this));
		this.bigimages = this.bigimages.clean();
	},

	 
	/*showBtns : function(){
		this.nav.fx.start('opacity', 0.3);
	},
	
	
	hideBtns : function(){
		this.nav.fx.start('opacity', 0); 
	},*/
	
	
	showFirstImage : function(){
		
		this.actualindex = this.bigimages.length -1;
		this.showImage(this.actualindex);
	},
	
	showNext : function(){	
		if (this.actualindex == 0){
			this.actualindex = this.bigimages.length -1;
		}else{
			this.actualindex--;
		}
		this.showImage(this.actualindex);
	},
	
	showPrev : function(){	
		if (this.actualindex >= this.bigimages.length -1){
			this.actualindex = 0;
		}else{
			this.actualindex++;
		}
		this.showImage(this.actualindex);
	},
	
	showImage : function(myindex){	
		this.bigimages.each(function(img) {
			img.fx.cancel();
			if (img.index == myindex){
				img.fx.start('opacity', 1);
			}else {
				img.fx.start('opacity', 0);
			}	
		}.bind(this)); 
	}	 	 
	
	 
	 	 
});// end class



/*******************************************************************************************************************************************/

 
var MainMenu = new Class({
	
	initialize: function(){
        
		if (!$('menu')) return;
		
		this.menu = $('menu');
		this.menu.fx = new Fx.Tween(this.menu, {'transition': 'quad:out', 'duration':400});
		this.menu.fx.set('opacity', 0);
		
		/* ul spacings */
		var ululs = $('menu').getElements('ul ul');
		ululs.each(function(ul) {
			var w = ul.getParent('ul').getStyle('width').toInt() + 30;
			ul.setStyle('margin-left', w);
		});
		
		
		this.menuisopen = false;
		
		this.menubox = $('navigation');
		this.menubox.set('opacity',1);
		this.menubox.fx = new Fx.Morph(this.menubox, {'transition': 'quad:out', 'duration':1100});
		this.menubox.fx.set({'margin-top': this.menubox.p0});
		
		this.menubox.addEvent('mouseenter', function() {
			this.menubox.fx.cancel();
			this.setMaxHeight();
			this.openMenuBox();
			
		}.bind(this));	
		this.menubox.addEvent('mouseleave', function() {
			this.menubox.fx.cancel();
			this.closeMenuBox();
			
		}.bind(this));
		
		this.togglebtn  = new Element('a').set({
		    'class': 'togglemenu',
		    'id': 'menubtn',
		    'text':'',
		    'href':'javascript:void(0)'
		});
		
		
		/*this.togglebtn.addEvent('click', function() {
			this.toggleMenuBox();
		}.bind(this));*/
		
		this.togglebtn.inject(this.menubox, 'top');
		
		this.actualbtn = null; 
		
		//this.maxulheights = [];
		this.ulheight0 =  $('menu').getElement('ul.level0').getStyle('height').toInt();
		this.maxheight = this.ulheight0;
		this.menubox.fx.set({'margin-top': - this.maxheight +20, 'height' : this.maxheight+15});
		
		this.togglebtn.setStyle('margin-top', this.ulheight0-22);
		
		this.btns = $('menu').getElements('a');
		this.btns.each(function(btn) {
		
			btn.slashhref = btn.get('href');
			btn.newhref = this._convertHref(btn.slashhref);	
			btn.set('href','javascript:void(0)');
			btn.targetdiv = $(btn.newhref);
	
			btn.ul = btn.getNext();
			if (btn.ul != null) {
				//btn.ul.hide();
				btn.fx = new Fx.Tween(btn.ul, {'transition': 'quad:out', 'duration':400});
				btn.fx.set('opacity', 0);
				
				btn.ul.height = btn.ul.getStyle('height').toInt();	
			}
			
			btn.addEvent('click', function(event) {
				// scroll:
				event = new Event(event).stop();
				window.nav.navigateTo(btn.targetdiv);
				// open menu:
				/*if (btn.ul != null) {	
					this.setMaxUlHeight(btn.ul.height);
				}*/
				//var mh = this.getMaxUlHeight();
				//this.menubox.fx.set({'margin-top':0, 'height' : mh});
					
				this.showSubMenu(btn); 
				this.actualbtn = btn;
				this.hideOpenMenus();
				this.setMaxHeight();
				if (this.menuisopen == true){
					this.menubox.fx.start({'height' : this.maxheight+15});
				}
					
			}.bind(this));

		}.bind(this));  
		
    }, //end constructor
    
	 
	 

	setMaxHeight : function(){		
		this.maxheight = this.ulheight0;
		var menusopen = $('menu').getElements('a.open');
		menusopen.each(function(btn){
			if (btn.ul == null) return;
			if (btn.ul.height>this.maxheight) this.maxheight = btn.ul.height;	
		}.bind(this));		
	},
	
	
	
	highlightMenu : function(id){
		// method used in InternalLinks Class:
		this.btns.each(function(btn) {
			if (btn.newhref == id){
				this.showSubMenu(btn); 
				this.setMaxHeight();
				this.actualbtn = btn;
				this.hideOpenMenus();
				this.setMaxHeight();
				btn.getParents('ul').each(function(ul){
					var _btn = ul.getPrevious();
					if (_btn == null) return;
					_btn.addClass('open');
					this.showSubMenu(_btn);
				}.bind(this));
			}
		}.bind(this));
	},



	translate : function(translations){
		this.togglebtn.menu_txt = translations[0];
		this.togglebtn.close_txt = translations[1];	
		this.togglebtn.set('text', this.togglebtn.menu_txt);
	},


	toggleMenuBox : function(){
		this.menubox.fx.cancel();
		if (this.menuisopen == false) {
			this.openMenuBox();
		}else {
			this.closeMenuBox();
		}
	}, 

	 
	openMenuBox : function(){
		this.menubox.fx.start({'margin-top':0, 'height' : this.maxheight +15}); /*.chain(function(){window.nav.navigateToActualElement();});*/	
		this.menuisopen = true;
		this.togglebtn.set('text', this.togglebtn.close_txt);
		
		this.menu.fx.cancel();
		this.menu.fx.start('opacity', 1);
		this.togglebtn.hide();
	},


	closeMenuBox : function(){
		this.menubox.fx.start({'margin-top': -this.ulheight0+20, 'height' : this.ulheight0+15}) /*.chain(function({window.nav.navigateToActualElement();});*/
		this.menuisopen = false;
		this.togglebtn.set('text', this.togglebtn.menu_txt);
		
		this.menu.fx.cancel();
		this.menu.fx.start('opacity', 0);
		this.togglebtn.show();
	},

	
	hideOpenMenus : function(){
	 	
		var menusopen = $('menu').getElements('a.open');
		menusopen.each(function(btn){
			if (btn.getParent().hasChild(this.actualbtn)==false) this.hideSubMenu(btn);
		}.bind(this));
				
	},
	
	
	_convertHref : function(_href){
		// trim protocol and domain
		if (_href.indexOf('//') > -1){
			_href = _href.slice(_href.indexOf('//')+2);
			_href = _href.slice(_href.indexOf('/'));
		}
		// replace any "/" by a "_"
		while(_href.indexOf('/') > -1){
			_href = _href.replace('/','_') ;
		}
		if (_href.length === 1){
			_href = _href + "en";
		}
		// if "_" then replace by "_en"
		return _href;
	},

	
	 showSubMenu : function(btn){
	 	btn.addClass('open');
		if (btn.fx!=undefined) btn.fx.start('opacity', 1);
	},

	
	 hideSubMenu : function(btn){
	 	btn.removeClass('open');
		if (btn.fx!=undefined) btn.fx.start('opacity', 0);
	}
	 

});// end class



/*********************************************************************************************/


 
var InternalLinks = new Class({
	
	initialize: function(){			
    }, //end constructor
	 
	 
	 
	init : function(target, targetclass){
		
		this.loc = "http://www.confreriehorlogere.ch/"; 
		//this.loc = location.href;
		//alert("this.loc: "+this.loc);
		
		this.lnks = target.getElements(targetclass);
			
		this.lnks.each(function(lnk) {
		
			lnk.slashhref = lnk.get('href');		
			lnk.newhref = this.convertHref(lnk.slashhref);	
			lnk.set('href','javascript:void(0)');
			lnk.targetdiv = $(lnk.newhref);

			lnk.addEvent('click', function(event) {
				//event = new Event(event).stop(); 
				window.nav.navigateTo(lnk.targetdiv);
				window.menu.highlightMenu(lnk.targetdiv.id);
				if (lnk.hasClass('closepopup')) window.popup._togglePopup();
			});  
			
		}.bind(this));  
	},
	
 
	
	convertHref : function(_href){	
		
		if (_href.contains(this.loc)){	
			_href = _href.replace(this.loc,''); // does it works?
		}
		if (_href.contains('?')){
			var endchain = _href.substr(_href.lastIndexOf('?'))
			_href = _href.replace(endchain,'') ;
		}
		while(_href.indexOf('/') > -1){
			_href = _href.replace('/','_') ;	
		}
		_href =  '_'+_href;
		var regex = /_*/;
		_href = _href.replace(regex, '_');
		return _href;
	},
	
	generateBreadCrumb : function(target){	
		
		var targetstring = target.get('id');
		var tempstrings = targetstring.split('_');
		
		var path = target.getElement('.path');
		var h = target.getStyle('height').toInt()-93;
		path.setStyle('margin-top', h);
		
		var lnk = '';
		
		tempstrings.each(function(str, i) {
			
			if( (i >=1) && (i<tempstrings.length-1) ){
					lnk += '_'+tempstrings[i];
					var targetdiv = $(lnk);
					var btn = new Element('a', {
					    'href': 'javascript:void(0)',
					    'class': 'slidelink',
					    'text' : tempstrings[i]
					});
					if (i==1) btn.set('text', 'home');
					btn.inject(path);
					btn.addEvent('click', function(event) {						
						window.nav.navigateTo(targetdiv);
						window.menu.highlightMenu(targetdiv.id);
					});  
			}
		});
		
		
		
		
	}

	 
});// end class



  /*********************************************************************************************/


var ScrollNavigation = new Class({
	

	initialize: function(){
		
		this.actualelement = null;
		
       	this.bodyscroll = new Fx.Scroll(document.body, {
			wait: false,
			duration: 3000,
			wheelStops: false,
			offset: {'x': -50, 'y': -50},
			transition: Fx.Transitions.Quad.easeInOut
		});
		
		
		/*var myScroller = new Scroller(window, {
		    area: Math.round(window.getWidth() / 5)
		});
		 
		(function(){
		    this.stop();
		    this.start();
		}).periodical(1000, myScroller);
		*/
		
		/*
		this.scroll1 = new Scroller(document.body, {area: 100, velocity: 0.1});
		 
		// Drag
		$(document.body).addEvent('mousedown', function() {
			$(document.body).setStyle('cursor', 'url(/demos/Scroller/closedhand.cur), move');
			////// //console.log("sart");
			this.bodyscroll.start();
		}.bind(this));
		$(document.body).addEvent('mouseup', function() {

		}.bind(this));
		 */


    }, // end constructor
	 
 
	 navigateTo : function(target){
			
	 	//center horizontal offset item:
	 	this.bodyscroll.options.offset.x = -(document.window.getSize().x - target.getSize().x)/2;
		
		// adapt vertical offset if menu box is open:
		var menupos = $('navigation').getStyle('margin-top').toInt();
		this.bodyscroll.options.offset.y = -130 - menupos;

		//then scroll:
		this.bodyscroll.toElement(target);
		this.openItem(target);
		
	},
	
	
	 _reconvertHref : function(_href){
		while(_href.indexOf('_') > -1){
			_href = _href.replace('_','/') ;
		}	
		return _href;
	},
	
	
	navigateToActualElement : function(){
		this.navigateTo(this.actualelement);
	},

	
	activateBigBtns : function(){
		
		var nodes = $$('.nodeContent');
	 	nodes.each(function(node) {
	 		this.createBigBtn(node);
	 	}.bind(this));
	},
	
	createBigBtn : function(node){
		
			//if (node.btn != null) return;
			
			node.btn = new Element('a', {
			    'href': 'javascript:void(0)',
			    'class': 'bigbtn'
			});
			//node.btn = node.getElement('a.bigbtn');
			
			node.btn.inject(node, 'top');
	 		node.btn.newhref = node.get('id');
			node.btn.slashhref = this._reconvertHref(node.btn.newhref);
			
	 		node.btn.dim = $(node).getSize();
	 		
	 		node.btn.setStyles({
	 			'width'  : node.btn.dim.x,
	 			'height' : node.btn.dim.y-4
	 		});
	 		
	 		// alert("node.btn.dim :"+node.btn.dim);
	 		
	 		node.btn.fx = new Fx.Tween(node.btn, {'transition': 'quad:out', 'duration':500});
			node.btn.fx.set('opacity', 0.75);
	 		
	 		node.btn.addEvent('click', function(event) {
				this.navigateTo(node);
				window.menu.highlightMenu(node.btn.newhref);
			}.bind(this)); 
			
			node.name = node.get('name');
	},
	
	openItem : function(target){
		
		if ($(this.actualelement)!=null){
			this.actualelement.btn.fx.start('opacity' , 0.75);
			if ($(this.actualelement.gallery)!=undefined){
				this.actualelement.gallery.showFirstImage();
			}
		}
		this.actualelement = target;
		// delay:
		(function(){ 
			this.actualelement.btn.fx.start('opacity' ,0);
		}.bind(this)).delay(3000);

		/* checks if this target needs to load live content */
		function liveContent () {
			return $(target).hasClass('Watch') 
			|| $(target).hasClass('Person') 
			|| $(target).hasClass('Article') 
			|| $(target).hasClass('Category') 
			|| $(target).hasClass('Mechanism'); // || $(target).hasClass('Article');
		}
		if (target.hasClass('loaded')== true) return;

		// ajax request:
		if (liveContent()) {
			var req = new Request.HTML({
	            method: 'get',
	            url: 'ajax/',
	            data: { 'pathID' : target.name },
	            onRequest: function() { 
	            	////// //console.log('Request made. Please wait...'); 
	            },
	            update: $(target), //.getElement('ajaxtarget'),
	            onComplete: function(response) { 
						
					target.addClass('loaded');
					
	            	Cufon.replace('h2', {fontFamily: 'Replica-Regular'});
	            	window.nav.createBigBtn(target);

	            	target.gallery  = new Gallery(target.get('id'));
	            	
	            	
	            	window.internlinks.init(target, 'a.slidelink');
	            	window.internlinks.generateBreadCrumb(target);
	            	
	            	window.popup.init(target);
	            	
	            	window.video.init(target);

	            }
	        }).send();
	        
		}else{
		
			/* no ajax request but delete void images */
			target.gallery  = new Gallery(target.get('id'));
			
		}
        
	}

});// end class





  /*********************************************************************************************/



var TreeCreator = new Class({
	
	initialize: function(){
        
        if (!$$('.children')) return;
    	  	
    	this.truncs = $$('.children');
    			
    	this.truncs.each(function(table) {
					
					table.tds = table.getChildren('td');
					
					table.tds.each(function(td) {	
						td.addClass('branch_vertical');
					});
					n_branch = table.tds.length;
					
					if (n_branch === 1){
						table.tds[0].addClass('branch_mono');
						//return;
					}else{
						table.tds.each(function(td) {	
							td.addClass('branch_middle');
						});
						table.tds[0].addClass('branch_left');
						table.tds[n_branch-1].addClass('branch_right');
					}
											
			}.bind(this));	
			
			$$('.hide_0').each(function(el){
				el.destroy();
			});
						
			// align some stuff:
			var w_ut = $('upTree').getSize().x; 
			var w_dt = $('downTree').getSize().x;
			var w = 0; 
			
			/*if (w_ut>w_dt) w = w_ut;
			else w = w_dt;*/
			
			w = w_ut;
			
			// $('trunc').setStyle('width', w);
			//$('treetrunc').setStyle('margin-left', w_dt/2);
			var bth = new Element('div').addClass('bottomtrunc').inject(document.body.getElement('.home'));
   
			// remove branch under news node
			// TODO internationalize
			var newsNode = $('_en_news').getParent();
			newsNode.getElement('.links').destroy();
			newsNode.getElement('.bottombranch').destroy();
			newsNode.getElement('.nodeChildren').destroy();
    }	 
	 	 
});// end class



  /*********************************************************************************************/


var PopupTechno = new Class({
	
	initialize: function(){
		
		this.popup = $('popup');
		
		this.popup.isclosed = true;
		this.popup.descr = this.popup.getElement(".descr");		
		
		this.popup.fx = new Fx.Tween(this.popup, {'transition': 'quad:out', 'duration':500});
		this.popup.fx.set('opacity', 0);
		//this.popup.fx.set('display', '');
		
		var bg = this.popup.getElement('.bg');
		bg.setStyle('opacity', 0.75);
	  	bg.addEvent('click', function(event) {
			this._togglePopup();
		}.bind(this)); 
			
    }, // end constructor
	
	
	init : function(target){
		
	 	var btn = target.getElement('a.popupbtn');
		if (btn) {
			btn.content = btn.getNext('div.popup');

			btn.addEvent('click', function(event) {
				this._populatePopup(btn.content);
				this._togglePopup();
			}.bind(this));  
		}
	    
	},


	 _populatePopup : function(content){
	 	this.popup.descr.grab(content);
	 	this._activateGrabbedBtn();
	},
		
		
	 _activateGrabbedBtn : function(content){
	 	var btn = this.popup.getElement('.cross');
 		btn.addEvent('click', function(event) {
				this._togglePopup();
		}.bind(this));  	 
	},
	
	
	_togglePopup : function(){
	 	if (this.popup.isclosed) {
	 		this.showPopup();
	 		this._centerPopup();
	 	}else {
	 		this.hidePopup();
	 	};
	},
	
	
	hidePopup : function(){
	 	this.popup.fx.start('opacity',0).chain(function(){this.popup.fx.set('display', 'none');}.bind(this));
	 	this.popup.isclosed = true;
	},
	
	
	showPopup : function(){
	 	this.popup.show();
	 	this.popup.fx.start('opacity',1);
	 	this.popup.isclosed = false;
	},
	
	
	_centerPopup : function(){
	 	var ml = (document.window.getSize().x - this.popup.descr.getSize().x)/2;
	 	var mt = (document.window.getSize().y - this.popup.descr.getSize().y)/2;
	 	
	 	this.popup.descr.setStyles({
	 		'margin-left' : ml,
	 		'margin-top' : mt
	 	})
	}


});// end class




