// contreforme v2.0 js
// © s.rossetti / contreforme sàrl / info@contreforme.ch
// this scripts makes extensive use of mootools javascript library http://www.mootools.net
// -------------------------------------------- //
// addLoadEvent function from DOM Scripting, Web Design with JavaScript and the Document Object Model
// by Jeremy Keith (may his name be blessed :) )
// edited by Friend's Of Ed
// isbn-13	: 978-1-59059-533-6
// isbn 	: 1-59059-533-5
// http://www.friendsofed.com
// http://domscripting.com
function addLoadEvent(func){
	var oldonload = window.onload;
	if(typeof window.onload != 'function'){
		window.onload = func;
	}else{
		window.onload = function(){
			oldonload();
			func();
		}
	}
}
// end of Jeremy Keith's addLoadEvent function
// -------------------------------------------- //
// getElemetnsByClassName function by Stuart Colville
// http://muffinresearch.co.uk/archives/2006/04/29/getelementsbyclassname-deluxe-edition/
// check his website at http://muffinresearch.co.uk/
function getElementsByClassName(strClass, strTag, objContElm) {
	strTag = strTag || "*";
	objContElm = objContElm || document;
	var objColl = objContElm.getElementsByTagName(strTag);
	if (!objColl.length &&  strTag == "*" &&  objContElm.all) objColl = objContElm.all;
	var arr = [];
	var delim = strClass.indexOf('|') != -1  ? '|' : ' ';
	var arrClass = strClass.split(delim);
	for (var i = 0, j = objColl.length; i < j; i++) {
		var arrObjClass = objColl[i].className.split(' ');
		if (delim == ' ' && arrClass.length > arrObjClass.length) continue;
		var c = 0;
		comparisonLoop:
		for (var k = 0, l = arrObjClass.length; k < l; k++) {
			for (var m = 0, n = arrClass.length; m < n; m++) {
				if (arrClass[m] == arrObjClass[k]) c++;
				if (( delim == '|' && c == 1) || (delim == ' ' && c == arrClass.length)) {
					arr.push(objColl[i]);
					break comparisonLoop;
				}
			}
		}
	}
	return arr;
}
// To cover IE 5.0's lack of the push method
Array.prototype.push = function(value) {
  this[this.length] = value;
}
// end of Stuart Colville's getElemetnsByClassName function
// -------------------------------------------- //
// check browser stuff
function check_browser_support(){
	if(!document.getElementById) return false;
	if(!document.createElement) return false;
	if(!document.createTextNode) return false;
	if(!document.getElementsByTagName) return false;
	var version = navigator.appVersion;
	if (version.toLowerCase().indexOf("win")!=-1){
		_mac = false;	
	}else{
		_mac = true;
	}
	return true;
}
// initialisation
function init(){
	if(!check_browser_support()) return false;
	browser_detection();
	var_init();		// get list childnodes & populate fx array
	nav_init();		// this is where the real thing happens
	links_init();	// make external links open in a new window
	tips_init();	// tips over project's small squares
}
// here's the real thing
function browser_detection(){
	var version=0;
	if (navigator.appVersion.indexOf("MSIE")!=-1){
		var temp = navigator.appVersion.split("MSIE");
		version = parseFloat(temp[1]);
	}

	(version>5 && version < 7) ? _IE  = true : _IE = false;
}
// populate list variable
function var_init(){
	if($('list')){							// if we are on the project page
		list	= $('list').getChildren();	// get the whole list children
	}
}
// set external links to open in new window
function links_init(){
	$each($$('a'),function(e){
		if (e.getProperty('href') && e.getProperty('rel') == 'external') e.setProperty('target','_blank');
	});
}
// creates scroll and assign elements behaviour
// if a project is passed in scrolls and opens it
function nav_init(){
	if($('list')){																						// if we are on the project page
		if(_IE){																						// assign scrolling fx
			smooth = new Fx.Scroll($('list').getParent(),{duration:500,transition:Fx.Transitions.Circ.easeInOut});
		}else{
			smooth = new Fx.Scroll(window,{duration:500,transition:Fx.Transitions.Circ.easeInOut});
		}
		
		// assign behaviour for each list's element
		$each(list,function(el,index){																					// for each element
			fx[index]	= new Fx.Styles(el.getFirst().getFirst(),{duration:500});	// create fx on img element
			el.num		= index;																							// set inner var num == element index
			el.addEvent('click',function(evt){													// click event
				if(this.getFirst().getFirst().getStyle('width') == '75px' && _opening == false){	// element is not open && no element is being opened
					_opening = !_opening;															// 1st of all prevent another click
					openproject(this);																// open element
				}
			});
		});
		// open project if page is called from clients' list
		if(String(location).contains('/project/')){					// if project section
			var loc,client,i;
			loc = String(location);
			//client = loc.substring(loc.lastIndexOf('/project/')+1,loc.length-1);	// get client number if any
			client = loc.substring(loc.lastIndexOf('/project/')+9,loc.length);		// get project name and number
			if(client.substr(-1)=='/') client = client.substr(0,client.length-1);	// get rid of last / if any
			var n = client.match(/\d+/g);											// get all number by group in a array
			if(n!=null){															// if number array is not empty
				client = n[n.length-1];												// get the last number group and assign it to client
				if(client>=0 && $("proj"+client)){										// if client is defined and client exists
					_opening = !_opening;											// 1st of all prevent another click
					openproject($("proj"+client));											// open target project
					smooth.scrollTo(0,$("proj"+client).getTop()-150);						// scroll to target project
				}
			}
		}
	}
	if($('partners')){
		if(!_IE){
			var togglers = getElementsByClassName('toggler');							// collect all togglers
			var stretchers = getElementsByClassName('stretcher');						// collect all stretchers
			
			// syntax : new Fx.Accordion(toggler, stretcher, {options});
			var myaccordion = new Fx.Accordion(togglers,stretchers,{					// create the accordion
				show: 'none',															// no object is displayed by default
				alwaysHide: true,														// it is possible to close all elements
				start: 'all-closed',													// start with all elements closed
				transition: Fx.Transitions.Sine.easeInOut,								// transition fx
				onActive: function(tog, el){											// change margin bottom when active and revert it on closing
					el.setStyle('margin-bottom','15px');
				},
				onBackground: function(tog, el){
					el.setStyle('margin-bottom','5px');
				}
			});
		}
		loadmap();																	// load googlemap
	}
}
function loadmap(){
	if(GBrowserIsCompatible()){
		var map = new GMap2(document.getElementById("gmap"),{mapTypes:[G_HYBRID_TYPE,G_NORMAL_MAP]});	// load googlemap into gmap div with two map types
		map.addControl(new GSmallMapControl());														// small buttons zoom/pan
		map.addControl(new GMapTypeControl());															// type control
		var point = new GLatLng(46.998940,6.939600);													// get point from contreforme
		map.setCenter(point,14);																		// assign it to map
		var icon = new GIcon();																		// create icon
		icon.image = "/images/static/cf_gm.png";														// front img
		icon.shadow = "/images/static/cf_gm_shadow.png";												// shadow
		icon.iconSize = new GSize(49,43);																// front size
		icon.shadowSize = new GSize(49,43);																// shadow size
		icon.iconAnchor = new GPoint(0,38);																// image baseline offset
		map.addOverlay(new GMarker(point,icon));														// add icon to map through GMarker object
	}
}
// open a project and close active project if any
function openproject(el){
	var rel,size,act;															// declare stuff
	act = _active;																// prevent _active value to be lost during this function
	el.setStyle('cursor','default');											// remove pointer from element
	// get some stuff
	rel = el.getFirst().getNext().getFirst().getFirst().getProperty('rel');	// get name infos ex. 'filename.jpg/430:280'
	rel = rel.split('/');														// split 'filename.jpg' / '430:280'
	size = rel[1].split(':');													// split '430' : '280'
	
	// launch effects
	fx[el.num].start({'opacity':0}).chain(function(){							// opacity
		el.getFirst().getFirst().setProperty('src','images/'+rel[0]);			// change src and...
		this.start({'width':size[0],'height':size[1]});						// resize
		el.getLast().setStyle('margin-left',13);									// change margin-left to stick to the image's width for text
	}).chain(function(){
		this.start.delay(500,this,{'opacity':1});											// opacity
		// prepare clickable squares and image changes
		var desc		= el.getLast().getChildren();								// get descriptions as an array
		var squares		= el.getFirst().getNext().getChildren();					// get small squares as an array
		
		//**************************************************************************//
		// attention ! the first description (index 0) is the project's description //
		// but the first square (index 0 as well) is the first image				//
		// when we change from image to image the description index 0 stay displayed//
		// that's why we display the first 2 descriptions :							//
		// index 0 => project AND index 1 => image 1								//
		//**************************************************************************//
		
		desc[desc.length-1].setStyle('display','block');							// show links (always the last element of description)
		desc[0].setStyle('display','block');										// show project's description
		
		_img = 1;																	// the first opened image index is 1 so we set the _img var to 1
		desc[_img].setStyle('display','block');										// show 1st image description
		// but the square for image index 1 is index 0
		squares[0].setStyle('background-color','#666');								// change 1st small square bg-color
		// add event for each square
		$each(squares,function(e,i){
			e.index = i+1;	// remember the squares/images index trick ? ;)
			e.addEvent('mouseover',function(){
				if(this.index!=_img) this.setStyle('background-color','#666');
			});
			e.addEvent('mouseout',function(){
				if(this.index!=_img) this.setStyle('background-color','#e6e6e6');
			});
			e.addEvent('click',function(){									// on clicking this square
				if(this.index!=_img){											// if the associated project isn't already open
					var num,rel,size;											// var stuff...
					num		= this.getParent().getParent().num;				// get project index (variable scope is to be solved here)
					rel		= this.getFirst().getProperty('rel');				// get this image infos stored in the name attribute
					rel		= rel.split('/');									// split --> rel[0] == project file / rel[1] == width:height
					size	= rel[1].split(':');								// split --> size[0] == width && size[1] == height
					
					squares[_img-1].setStyle('background-color','#e6e6e6'); 	// revert former active square color back
					desc[_img].setStyle('display','none');						// hide former active image description
					this.setStyle('background-color','#666');					// set this bg-color
					desc[this.index].setStyle('display','block');				// display this desccription
					
					fx[num].start({
						'opacity':0												// opacity
					}).chain(function(){										// then...
						// change image source
						e.getParent().getPrevious().getFirst().setProperty('src','images/'+rel[0]);	// set image src to target
						// change size
						fx[num].start({																	// change size according to image
							'width':size[0],															// in w
							'height':size[1]															// in h
						});
					}).chain(function(){																// then...
						fx[num].start({
							'opacity':1																	// set opacity back to 1
						});
					});
					_img = this.index;											// set this as active square
				}
			});
		});
	});
	
	// close active element if needed
	if(act != null &&  act != el.num){											// if a project is already opened
		var src	= list[act].getFirst().getFirst().getProperty('name');				// get open project's thumb src and...
		fx[act].start({'opacity':0}).chain(function(){							// hide image
			list[act].getFirst().getFirst().setProperty('src','images/'+src);		// set src back
			list[act].getLast().getChildren().each(function(e){					// hide all descriptions & links
				e.setStyle('display','none');
			});
			list[act].getLast().setStyle('margin-left',480);						// change margin-left back to default for text
			list[act].getFirst().getNext().getChildren().each(function(e){
				e.setStyle('background-color','#e6e6e6');							// revert small squares bg-color
				e.removeEvents();													// remove mouseover, mouseout and click event
			});
			this.start({'width':75,'height':75});									// get size back to 75/75
			list[act].setStyle('cursor','pointer');									// get pointer back
		}).chain(function(){
			this.start.delay(500,this,{'opacity':1})								// show image (delay is to let the resizing finish before starting opacity for slow browser)
			smooth.scrollTo(0,el.getTop()-150);										// scroll window to newly opened element
			
		});
	}else{
		smooth.scrollTo(0,el.getTop()-150);									// scroll window to target element
	}
	
	_opening	= !_opening;												// and we allow for another click
	_active		= el.num;													// we may now set active to clicked element
}
function tips_init(){
	var tips = getElementsByClassName('tips');								// get all tips elements
	
	var mytips = new Tips(tips,{											// make a new tips object
		maxTitleChars: 250,													// huge limit for tip text content...
		initialize:function(){												// Fx for fade-in/fade-out
			this.fx = new Fx.Style(this.toolTip, 'opacity', {duration: 500, wait: false}).set(0);
		},
		onShow: function(toolTip){											// ... as its name implies ...
			this.fx.start(0.8);
		},
		onHide: function(toolTip){											// ... as its name implies ...
			this.fx.start(0);
		}
	});
}
// -------------------------------------------- //
// main vars
// list,scroller,_IE<=6
var list,smooth,_IE;
// fx container
var fx			= [];
// at first no project is open
var _active		= null;
// no project is being opened
var _opening	= false;
// project starts at 1
//used to store displayed image
var _img		= 1;
// -------------------------------------------- //
// showtime!
addLoadEvent(init);