var lng = function(sf, se) {
	return (Site.lngId == 'f') ? sf : se;
}

var log = function(s) {
	if(!Site.dev) return null;
	if(!$dev) $dev = new Dev();
	$dev.log(s);
}

var logError = function(s) {
	log('<strong class="error">' + s + '</strong>');
}

var objInspect = function(o) {
	o = o || {};
	return '{ ' + Object.keys(o).map(function(k) { return k + ':' + o[k] }).join(', ') + ' }';
}

var $dev;

var Dev = Class.create({
	initialize: function() {
		this.elements = {
			dev: $E('div', 'dev'),
			log: $E('ul', 'log'),
			conteneur: $('conteneur'),
		};

		this.init = false;
	},
	
	initInterface: function() {
		this.elements.conteneur.wrap($E('div', 'conteneur-wrap'));
		document.body.insert({ top: this.elements.dev });
		this.elements.dev.insert(this.elements.log);
		document.body.addClassName('dev');
		this.init = true;
	},
	
	log: function(s) {
		if(!this.init) this.initInterface();
	
		this.elements.log.insert({
			top: $E('li').update(this.elements.log.childElements().size() + ': ' + s)
		});
	},
});

var $E = function(tag, idName, attr) {
	attr = attr || {};
	if(idName) attr['id'] = idName;
	return new Element(tag, attr);
}

var $e = function(tag, attr) {
	return new Element(tag, attr);
}

var $LINK = function(href, idName, attr) {
	attr = attr || {};
	attr.href = href || '#';
	if(idName) attr['id'] = idName;
	return new Element('a', attr);
}

var $link = function(href, attr) {
	attr = attr || {};
	attr.href = href || '#';
	return new Element('a', attr);
}

var clearDiv = function() {
	return $e('div', { 'class': 'clear' });
}

var makeSelectFunc = function(container) {
	return container ? $(container).select.bind($(container)) : $$;
}

var zero2 = function(n) {
	var s = n.toString();
	if(s.length == 0) return '00'
	else if(s.length == 1) return '0' + s
	else return s;
}

var $popup;

var Popup = Class.create({
	initialize: function() {
		this.CLOSE_BTN = $link('#').update('&#xd7;');
		this.WAIT_CONTENU = '<div class="un-instant">' + lng('Un instant…', 'One moment…') + '</div>';
		this.WAIT_TITRE = lng('Un instant…', 'One moment…');
	
		this.popup = $E('div', 'popup');
		document.body.insert(this.popup);
		this.popup.hide();
		
		this.elements = {
			header: $E('div', 'popup-header'),
			btn: $E('div', 'popup-btn'),
			titre: $E('div', 'popup-titre'),
			navTab: $E('div', 'popup-nav-tab'),
			contenu: $E('div', 'popup-contenu'),
		};
		
		this.elements.header.insert(this.elements.btn);
		this.elements.btn.update(this.CLOSE_BTN);
		this.elements.header.insert(this.elements.titre);
		this.elements.header.insert(clearDiv());
		this.popup.insert(this.elements.header);
		this.popup.insert(this.elements.navTab);
		this.popup.insert(this.elements.contenu);

		this.sombre = $E('div', 'sombre');
		document.body.insert(this.sombre);
		
		this.width = null;
	},
	
	fetchLayouts: function() {
		this.viewportDim = document.viewport.getDimensions();
		this.layout = this.popup.getLayout();
		this.contenuLayout = this.elements.contenu.getLayout();
		return this;
	},
	
	center: function() {
		this.fetchLayouts();
	
		this.popup.setStyle({
			'left': ((this.viewportDim.width - this.layout.get('margin-box-width')) / 2) + 'px',
			'top': ((this.viewportDim.height - this.layout.get('margin-box-height')) / 2) + 'px',
		});
		
		return this;
	},

	redim: function() {
		if(this.popup.hasClassName('redim')) return this;
	
		if(this.popup.down('.popup-guide')) {
			this.redimFromGuide();
			return this;
		}
		
		if(this.width) {
			this.elements.contenu.setStyle({ 'width': this.width + 'px' });
		} else {
			this.elements.contenu.setStyle({ 'width': '' });
		}

		this.fetchLayouts();
		this.elements.contenu.setStyle({ 'height': '' });
		var totalHeight = this.layout.get('margin-box-height');

		if(totalHeight > this.viewportDim.height) {
			var extraHeight = totalHeight - this.contenuLayout.get('height');
			this.elements.contenu.setStyle({ 'height': (this.viewportDim.height - extraHeight - 50) + 'px' });
		}
		
		if(this.contenuLayout.get('height') > 500) {
			this.elements.contenu.setStyle({ 'height': '500px' });
		}
		
		this.popup.addClassName('redim');
		this.center();
		return this;
	},

	redimFromGuide: function() {
		var loadTimer;
		
		var waitForLoad = function() {
			log('waitForLoad');
		
			if(this.guide.complete) {
				log('complete!');
				this.guide.setOpacity(1);
			
				this.fetchLayouts();
				this.elements.contenu.setStyle({ 'height': '' });
				var totalHeight = this.layout.get('margin-box-height');
				
				if(totalHeight > this.viewportDim.height) {
					var extraHeight = totalHeight - this.guide.height;
					var newGuideHeight = this.viewportDim.height - extraHeight;
					var newGuideWidth = this.guide.width / this.guide.height * newGuideHeight;
					this.guide.setStyle({ 'height': newGuideHeight + 'px' });
					this.elements.contenu.setStyle({ 'width': newGuideWidth + 'px' });
					
				} else {
					this.elements.contenu.setStyle({ 'width': this.guide.width + 'px' });
				}
				
				var totalWidth = this.layout.get('margin-box-width');
				
				if(totalWidth > this.viewportDim.width) {
					var extraWidth = totalWidth - this.guide.width;
					var newGuideWidth = this.viewportDim.width - extraWidth;
					var newGuideHeight = this.guide.height / this.guide.width * newGuideWidth;
					this.guide.setStyle({ 'width': newGuideWidth + 'px' });
					this.guide.setStyle({ 'height': newGuideHeight + 'px' });
					this.elements.contenu.setStyle({ 'width': newGuideWidth + 'px' });
				}
		
				this.popup.addClassName('redim');
				this.center();
	
			} else {
				loadTimer = setTimeout(waitForLoad, 100);
			}
		}.bind(this);
	
		this.guide = this.popup.down('.popup-guide');
		this.guide.setOpacity(0);
		if(this.guide) waitForLoad();
		return this;
	},

	update: function(newElements) {
		this.elements.navTab.update(newElements.navTab || '');
		this.elements.titre.update(newElements.titre || '');
		this.popup.removeClassName('redim');
		this.elements.contenu.update(newElements.contenu);
		setupDocument(this.popup);
		return this;
	},
	
	wait: function() {
		this.update({
			contenu: this.WAIT_CONTENU, 
			titre: this.WAIT_TITRE, 
			navTab: (this.isPopupNavTabLink ? this.elements.navTab.innerHTML : ''),
		});
		
		return this;
	},

	bodyClick: function(event) {
		var e = event.element();
	
		if((!e.match('#popup') && !e.up('#popup')) || (e.match('#popup-btn') || e.up('#popup-btn'))) {
			this.popup.hide();
			document.body.removeClassName('sombre');
			document.body.stopObserving('click', this.bodyClick.bind(this));
			
			if(e.match('#popup-btn') || e.up('#popup-btn')) {
				event.stop();
			}
		}
	},
	
	show: function() {
		this.popup.setOpacity(0);
		this.popup.show();
		this.redim();
		this.popup.setOpacity(1);
		return this;
	},

	open: function() {
		if(this.inverse) {
			this.popup.addClassName('inverse');
			document.body.addClassName('sombre');
		} else {
			this.popup.removeClassName('inverse');
		}
	
		this.show();
		document.body.stopObserving('click', this.bodyClick.bind(this));
		document.body.observe('click', this.bodyClick.bind(this));
		return this;
	},

	getAjaxResponse: function(url, options, formParameters) {
		this.width = options.width || 0;
		this.inverse = options.inverse;
		this.isPopupNavTabLink = options.isPopupNavTabLink;
		var fixUrl = (options.fixUrl !== false);
		var defaultBody = options.defaultBody || '#corps';
		if(fixUrl) url = Popup.fixAjaxUrl(url);
		
		new Ajax.Request(url, {
			method: 'post',
			parameters: formParameters,
			
			onCreate: function(transport) {
				this.wait();
				this.open();
			}.bind(this),
		
			onSuccess: function(transport) {
				var response = transport.responseText || '<div id="corps">Erreur</div>';
				response = response.replace(/\n/g, ' ');
				response = response.replace(/\[base\]/g, Site.baseUrl);
				var html = $e('div').update(response);
				var responseCorps = '';
	
				if(html.down(defaultBody)) {
					responseCorps = html.down(defaultBody).innerHTML;
				} else {
					responseCorps = html.innerHTML;
				}
	
				var responseTitre = html.down('h1') ? html.down('h1').innerHTML : '';
				var responseNavTab = (html.down('#nav-tab') && !inverse) ? html.down('#nav-tab').innerHTML : '';
				delete html;
				
				this.update({
					contenu: responseCorps, 
					titre: responseTitre, 
					navTab: responseNavTab
				});
				
				this.open();
				if(options.successFunc) options.successFunc();
			}.bind(this)
		});

		return this;
	},
});

Popup.fixAjaxUrl = function(url) {
	return url + ((url.match(/\?/)) ? '&' : '?') + 'ajax=1';
}

Popup.attach = function(link) {
	if(link.hasClassName('popup')) return false;
	
	link.addClassName('popup');
	var inverse = link.hasClassName('video') || link.hasClassName('photo');
	var wMatch = link.href.match(/&w=(\d+)/);
	var width = wMatch ? wMatch[1] : 0;

	link.observe('popup:click', function(event) {
		event.stop();
		var isPopupNavTabLink = link.up('#popup-nav-tab');

		if(isPopupNavTabLink) {
			var newSel = link.up('li');
			newSel.addClassName('here');
			newSel.adjacent('li.here').invoke('removeClassName', 'here');
		}
		
		$popup = $popup || new Popup();
		
		$popup.getAjaxResponse(link.href, {
			width: width, 
			inverse: inverse, 
			isPopupNavTabLink: isPopupNavTabLink,
			defaultBody: '#contenu',
		});
	});
	
	if(link.tagName == 'A') {
		link.observe('click', function(event) {
			link.fire('popup:click');
			event.stop();
		});
	}
}

Popup.detach = function(link) {
	link.removeClassName('popup');
	link.stopObserving('click');
}

var $tip;

var Tip = Class.create({
	initialize: function() {
		this.DEFAULT_POSITION = 'left';
		this.PTR_WIDTH = 9;
		this.PTR_OFFSET = 10;
	
		this.tip = $E('div', 'tip').hide();
		this.elements = {};
		this.build();
		this.position = this.DEFAULT_POSITION;
	},
	
	build: function() {
		this.elements.contenu = $E('div', 'tip-contenu');
		this.elements.ptr = $E('div', 'tip-ptr');
		this.tip.update(this.elements.ptr);
		this.tip.insert(this.elements.contenu);
		document.body.insert(this.tip);
		return this;
	},

	calcTop: function(options) {
		if(options.attache) {
			return options.attache.cumulativeOffset().top + options.attache.measure('border-box-height');
		} else if(options.event) {
			return options.event.pointerY();
		}
		
		return 0;
	},
	
	calcLeft: function(options) {
		var ptrOffset = this.PTR_OFFSET + (this.PTR_WIDTH / 2);

		if(options.attache) {
			var attacheWidth = options.attache.measure('border-box-width');
			var attacheLeft = options.attache.cumulativeOffset().left;
			var tipWidth = this.tip.measure('border-box-width');
		
			if(options.position == 'left') {
				return attacheLeft + (attacheWidth / 2) - ptrOffset;
			} else if(options.position == 'right') {
				return attacheLeft + (attacheWidth / 2) - tipWidth + ptrOffset;
			}

		} else if(options.event) {
			if(options.position == 'left') {
				return options.event.pointerX() - ptrOffset;
			} else if(options.position == 'right') {
				return options.event.pointerX() - this.tip.measure('border-box-width') + ptrOffset;
			}
		}
		
		return 0;
	},
	
	show: function(texte, options) {
		options = options || {};
		options.position = options.position || this.DEFAULT_POSITION;
		this.elements.contenu.update(texte);

		this.tip.setStyle({
			'top': this.calcTop(options) + 'px',
			'left': this.calcLeft(options) + 'px',
		});
		
		if(this.specialClass) {
			this.tip.removeClassName(this.specialClass);
			this.specialClass = null;
		}
		
		this.tip.removeClassName('position-' + this.position);
		this.position = options.position;
		this.tip.addClassName('position-' + this.position);
		
		if(options.specialClass) {
			this.specialClass = options.specialClass;
			this.tip.addClassName(this.specialClass);
		}
		
		this.tip.show();
		return this;
	},
	
	hide: function() {
		this.tip.hide();
		return this;
	},
});

Tip.attach = function(link, options) {
	options = options || {};
	var title = link.title;
	if(title == '') return false;
	
	link.removeAttribute('title');
	$tip = $tip || new Tip();

	link.observe('mouseover', function(event) {
		options.attache = link;
		$tip.show(title, options);
	});
	
	link.observe('mouseout', function(event) {
		$tip.hide();
	});
	
	return true;
}

var Itemtab = Class.create({
	initialize: function(container, options) {
		this.container = container;
		
		this.options = options || {};
		this.options.childSelector = this.options.childSelector || '>li';

		this.items = this.container.select(this.options.childSelector).map(function(item, index) {
			return {
				id: item.id || String(index),
				index: index,
				element: item,
			};
		});

		this.itemsById = (function() {
			var itemsById = {};
		
			this.items.each(function(item) {
				itemsById[item.id] = item;
			}.bind(this));
			
			return itemsById;
		}.bind(this))();
		
		this.index = (function() {
			var id = location.href.match(/#item:/) && location.href.match(/#item:(.*)/)[1];
			return (id && this.itemsById[id]) ? this.itemsById[id].index : 0;
		}.bind(this))();
		
		this.maxIndex = this.items.size() - 1;
		
		this.build();
	},
	
	build: function() {
		this.container.addClassName('itemtab');
		var nav = $e('ul', { 'class': 'itemtab-nav' });

		this.items.each(function(item, index) {
			item.element.hide();
			item.nav = $e('li');
			var image = item.element.down('img');
			var link = $link('#item:' + item.id).update(image.clone());
			
			link.observe('click', function(event) {
				this.setIndex(index);
				link.blur();
			}.bind(this));
			
			link.title = item.element.down('h2').innerHTML;
			Tip.attach(link, { specialClass: 'from-itemtab' });
			
			var waitForLoad = function() {
				if(image.width) {
					var imageClass = (image.width < image.height) ? 'vertical' : 'horizontal';
					item.nav.addClassName(imageClass);
				} else {
					setTimeout(waitForLoad, 100);
				}
			}
			
			waitForLoad();
			nav.insert(item.nav.update(link));
		}.bind(this));
		
		nav.insert(clearDiv());
		this.container.insert({ before: nav });
		this.setIndex(this.index);
		return this;
	},

	setIndex: function(newIndex) {
		this.timeout = setTimeout(function() {
			clearTimeout(this.timeout);
			
			if(this.index !== null) {
				this.items[this.index].nav.removeClassName('sel');
				this.items[this.index].element.hide();
			}
			
			this.index = newIndex;
			this.items[this.index].nav.addClassName('sel');
			this.items[this.index].element.show();
		}.bind(this), 200);

		return this;
	},
});

var Diaporama = Class.create({
	initialize: function(container, options) {
		this.DEFAULT_TIMEOUT_MSEC = 3000;
		this.TRANSITION = Effect.Transitions.Expo.easeOut;
		this.TRANSITION_DURATION = 0.6,

		this.options = options || {};
		this.options.childSelector = this.options.childSelector || '>li';
		this.options.timeoutMsec = this.options.timeoutMsec || this.DEFAULT_TIMEOUT_MSEC;
		this.options.offset = this.options.offset || 0;
		this.options.navPosition = this.options.navPosition || 'after';
		this.options.random = !!this.options.random;

		this.container = container;

		this.items = this.container.select(this.options.childSelector).map(function(item, index) {
			return {
				id: item.id || String(index),
				index: index,
				element: item
			};
		});

		this.itemsById = (function() {
			var itemsById = {};
		
			this.items.each(function(item) {
				itemsById[item.id] = item;
			}.bind(this));
			
			return itemsById;
		}.bind(this))();
		
		this.index = null;
		this.maxIndex = this.items.size() - 1;
		this.maxHeight = 0;
		this.containerWidth = this.container.measure('width');
		this.timer = null;

		this.build();
	},
	
	build: function() {
		if(this.maxIndex == 0) return this;
	
		this.container.addClassName('diaporama');
		var nav = $e('ul', { 'class': 'diaporama-nav' });
		
		this.maxHeight = this.items.inject(this.maxHeight, function(max, item) {
			item.height = item.element.measure('height');
			return (item.height > max) ? item.height : max;
		}.bind(this));
		
		this.container.setStyle({
			'position': 'relative',
			'overflow': 'hidden',
			'height': this.maxHeight + 'px',
		});
		
		this.items.each(function(item, index) {
			item.scrollLeft = index * (this.containerWidth + this.options.offset);
		
			item.element.setStyle({
				'position': 'absolute',
				'height': this.maxHeight + 'px',
				'width': this.containerWidth + 'px',
				'left': item.scrollLeft + 'px',
			});
			
			if(this.options.verticalAdjust) {
				item.element.setStyle({
					'top': ((this.maxHeight - item.height) / 2) + 'px',
				});
			}

			var link = $link('#' + item.id).observe('click', function(event) {
				this.setIndex(index);
				event.stop();
			}.bind(this));
		
			item.nav = $e('li').update(link);
			nav.insert(item.nav);
		}.bind(this));
		
		var newPosition = {};
		newPosition[this.options.navPosition] = nav.insert(clearDiv());
		this.container.insert(newPosition);
		this.initIndex().initTimer();
		return this;
	},
	
	initTimer: function() {
		clearTimeout(this.timer);
		this.timer = setTimeout(this.nextIndex.bind(this), this.options.timeoutMsec);
		return this;
	},
	
	setIndex: function(newIndex) {
		if(this.index !== null) {
			this.items[this.index].nav.removeClassName('sel');
		}
		
		this.index = newIndex;
		this.items[this.index].nav.addClassName('sel');

		if(this.index !== null) {
			new Effect.Tween(this.container, this.container.scrollLeft, this.items[this.index].scrollLeft, {
				transition: this.TRANSITION,
				duration: this.TRANSITION_DURATION,
			}, 'scrollLeft');

		} else {
			this.container.scrollLeft = this.items[this.index].scrollLeft;
		}

		this.initTimer();
		return this;
	},
	
	initIndex: function() {
		if(this.options.random) {
			this.setIndex(this.randomize());
			return this;
		}
		
		this.setIndex(0);
		return this;
	},
	
	nextIndex: function() {
		if(this.options.random) {
			if(!this.randomIndices || !this.randomIndices.length) {
				this.randomize();
			}

			this.setIndex(this.randomIndices.pop());
			return this;
		}
	
		var nextIndex = this.index + 1;
		if(nextIndex > this.maxIndex) nextIndex = 0;
		this.setIndex(nextIndex);
		return this;
	},
	
	randomize: function() {
		this.randomIndices = [];
		var temp = this.items.map(function(item, index) { return index; });

		while(temp.length) {
			this.randomIndices.push(temp.splice(Math.random() * temp.length, 1));
		}
		
		return this.randomIndices[0];
	},
});

var AccueilPage = Class.create({
	initialize: function() {
		$$('div.photo-diaporama').each(function(div) {
			new Diaporama(div.down('ul'), {
				verticalAdjust: true,
			});
		});
	},
});

AccueilPage.found = function() {
	return !!$('doc-accueil');
}

var ServicesPage = Class.create({
	initialize: function() {
		this.elements = {
			reputation: $('services-reputation'),
		};
		
		new Diaporama(this.elements.reputation.down('ul'), {
			timeoutMsec: 6000,
		});
	},
});

ServicesPage.found = function() {
	return !!$('doc-services');
}

var ClientsPage = Class.create({
	initialize: function() {
		$$('div.photo-diaporama').each(function(div) {
			new Diaporama(div.down('ul'), {
				verticalAdjust: true,
				offset: 45,
			});
		});

		new Itemtab($('clients'));
	},
});

ClientsPage.found = function() {
	return !!$('doc-clients');
}

var EquipePage = Class.create({
	initialize: function() {
		new Itemtab($('equipe'));
	},
});

EquipePage.found = function() {
	return !!$('doc-equipe');
}

var setupDocument = function(container) {
	var select = makeSelectFunc(container);

	select('a[title]').each(function(link) {
		var options = {};
		if(link.match('#secondaire-nav a')) options.position = 'right';
		Tip.attach(link, options);
	});

	select('a.comm').each(Popup.attach);
}

var setupInterne = function() {
	if(!Site.interne) return false;
	document.body.addClassName('site-interne');
}

var initSiteDomLoaded = function(event) {
	setupInterne();
	if(Site.dev && !$dev) $dev = new Dev();
	setupDocument();
}

var initSiteAllLoaded = function(event) {
	Site.allLoaded = true;
	if(AccueilPage.found()) new AccueilPage();
	if(ServicesPage.found()) new ServicesPage();
	if(ClientsPage.found()) new ClientsPage();
	if(EquipePage.found()) new EquipePage();
}

Event.observe(document, 'dom:loaded', initSiteDomLoaded, false);
Event.observe(window, 'load', initSiteAllLoaded, false);

Site.allLoaded = false;
Site.interne = location.href.match(/^http:\/\/interne\.electrocd\.com/);
Site.dev = !!Site.interne;

