var Keyboard = new KeyBoard();

Shadowbox.init({ overlayOpacity: 0.8 });


// Vars
var debug = false;
var pics = [];
var intro_pics = [];
window['next'] = false;
window['previous'] = false;


function uniq() {
	typeof(window['__ids__'])=='undefined' ? window['__ids__'] = 0 : window['__ids__'] += 1;
	return window['__ids__'];
}
function toggle_menu () {
	new Effect.toggle('menu', "blind", {duration: 0.4});
}
function start_show_menu (delay) {
	Event.stopObserving($('menu'), 'mouseover', clear_menu_timer, false);
	Event.stopObserving($('menu'), 'mouseout', init_menu_timer, false);
	toggle_menu();
	window['menu_timer'] = setTimeout("menu_hide()", delay);
}
function clear_menu_timer (e) {
	if (e) e.stop();
	clearTimeout(window['menu_timer']);
  	window['menu_timer'] = null;
}
function init_menu_timer (e) {
	if (e) e.stop();
	window['menu_timer'] = setTimeout("menu_hide()", 1500);
}
function logo_out (evt) {
	evt.stop();
	init_menu_timer();
}
function logo_over (evt) {
	evt.stop();
	clear_menu_timer();
	if(window['menu_timer'] != null && window['menu_timer'] != 0)
		null;
	else {
		new Effect.BlindDown('menu', {
			duration: 0.4,
			afterFinish: function(){
				Event.observe($('logo'), 'mouseout', logo_out, false);
			},
			queue: {
				scope: 'menu_animation',
				position: 'end'
			}
		});      
	}
}
function menu_hide() {
  	clear_menu_timer();
	new Effect.BlindUp('menu', {
		duration: 0.4,
		beforeStart: function() {
    		Event.stopObserving($('menu'), 'mouseover', clear_menu_timer, false);
    		Event.stopObserving($('menu'), 'mouseout', init_menu_timer, false);
		},
		afterFinish: function(){
			Event.observe($('menu'), 'mouseover', clear_menu_timer, false);
    		Event.observe($('menu'), 'mouseout', init_menu_timer, false);
		},
		queue: {
			scope: 'menu_animation',
			position: 'end'
		}
	});      
}
function build_menu (id, galleries, popups) {
	var menu = Builder.node('div', {className: "galleries"});
	$H(galleries).each(function(category){
		if(category[0]=='__intro')
			intro_pics = category[1];
		else
		{
      		$(menu).insert(Builder.node('h1', {className: "menu_item accordion_toggle"}, category[0]));
			var content = Builder.node('div', {className: "accordion_content", style: "display:none"});
			$H(category[1]).each(function(subcat){
				var my_subcat = Builder.node('h2', {className:'menu_item'}, subcat[0]);
      			Object.extend(my_subcat, {pics: subcat[1], start_index: pics.length});
				var extended_pics = [];
				subcat[1].each(function(el){
					extended_pics.push(Object.extend(new String(el), {cat: category[0], subcat: my_subcat}));
				});
				if(extended_pics[0])
					debug ? console.log(extended_pics[0].subcat) : null;
				pics = pics.concat(extended_pics);
				if(my_subcat.pics.length>0)
					$(my_subcat).observe('click', function(evt){
						if(window['intro'])
						{
							window['intro'] = false;
							new Effect.BlindDown('home_link', {duration: 0.4});
							showAlternateSlideShow();
						}  
        				if ($('pictures').slideShow.automaticSlide())
							$('pictures').slideShow.resetAutomaticSlide({start: true, id: $(my_subcat).start_index});
						else
							$('pictures').slideShow.startAutomaticSlide({start: true, id: $(my_subcat).start_index});
						menu_hide();
						closePopups_action();
        				deselectItemAccordion();
						Event.element(evt).addClassName('selected');
					});
				$(content).insert(my_subcat);
			});
			menu.insert(content);
		}
	}); 
	if (videos.length > 0)
	{
		videos.each(function(menuvideo) {
			if (menuvideo['items'].length > 0)
			{
				menu.insert(Builder.node("h1", {className:"menu_item accordion_toggle"}, menuvideo['name']));
				var videos_content = Builder.node('div', {className: "accordion_content", style: "display:none"});
				menuvideo['items'].each(function(video) {
					if (video['url'].match(/vimeo\.com/gi))
					{
						var vlink = Builder.node('a', {href:'http://vimeo.com/moogaloop.swf'}, video['name']);
						$(videos_content).insert(Builder.node('h2', {className:'menu_item'}, vlink));
						var vnumber = video['url'].match(/(\d+)/gi);
						vnumber = vnumber[0];
						Shadowbox.setup(vlink, { width:900, height:560, flashVars: { clip_id: vnumber.toString(), autoplay: "1" } });
					}
					else
					{
						var vlink = Builder.node('a', {href:video['url'], target:'_blank'}, video['name']);
						$(videos_content).insert(Builder.node('h2', {className:'menu_item'}, vlink));
					}
				});
				menu.insert(videos_content); 
			}
		});
	}
	
	var popups_links = Builder.node('div', {className:"popups"});
	popups.each(function(popup) {
		$(popups_links).insert(Builder.node("h1", {id:popup['url_var']+"_popup_link", className:"menu_item2"}, popup['name']));
	});
	
	$('menu').insert({top: popups_links});
  	if(!Browser.isIE()) $('menu').insert({top: Builder.node('hr')});
	$('menu').insert({top: menu});
  	if(!Browser.isIE()) $('menu').insert({top: Builder.node('hr')});
	var accueil = Builder.node('h1', {className: 'menu_item2' }, 'Accueil');
	$('menu').insert({top: Builder.node('div', {id: 'home_link'}, [accueil])});
	$('home_link').hide();
	      
	$(accueil).observe('click', function(evt) {
		if(!window['intro'])
		{
			window['intro'] = true;
			showAlternateSlideShow();
			new Effect.BlindUp('home_link', {
  			duration: 0.4
  		});
			$('pictures').slideShow.automaticSlide() ? $('pictures').slideShow.stopAutomaticSlide() : null;
			$('pictures').slideShow.startAutomaticSlide({start: true});
			$('controls').fade();
			deselectItemAccordion();
      $('menu').accordion_object.closeActive();
		}
	}, false);
}

function deselectItemAccordion () {
  var selected_elt = $('menu').down('.selected');
  if(selected_elt) selected_elt.removeClassName('selected');
}

function showAlternateSlideShow () {
	$('pictures').slideShow.stop();
  	$('pictures').slideShow.hideCurrent();
	$('pictures').slideShow.current = -1;
	var tmp = $('pictures').slideShow;
	$('pictures').slideShow = null;
	$('pictures').slideShow = window['alternate_slide'];
	window['alternate_slide'] = tmp;
	return $('pictures').slideShow;
}
function previous_button_action(evt){
  window['previous'] = true;
  if(window['next']==false)
	  $('pictures').slideShow.stopAutomaticSlide().previous();
}
function next_button_action(evt){
  window['next'] = true;
	if(window['previous']==false)
	  $('pictures').slideShow.stopAutomaticSlide().next();
}
function playPause_action(evt) 
{
  $('pictures').slideShow.toggleAutomaticSlide({start: true, queue: false });
}
function closePopups_action(evt) 
{
	$$('.popup_container').each(function(item){
		item.fade({duration:0.3});
	});
}
function detectKey(evt) 
{
	var key = Keyboard.keyCode(evt);
	debug ? console.log(key) : null;
	switch (true)
	{
		case key == KEY_ESCAPE:
			closePopups_action(evt);
			break;
		
		case key == KEY_LEFT && !window['intro']:
		case key == KEY_BOTTOM && !window['intro']:
		case key == KEY_LESS && !window['intro']:
			previous_button_action(evt);
			break;
			
		case key == KEY_RIGHT && !window['intro']:
		case key == KEY_TOP && !window['intro']:
		case key == KEY_MORE && !window['intro']:
			next_button_action(evt);
			break;
	}
}

// Initialization
function init_lucky (evt) {  
	//Menu
  	build_menu('menu', galleries_tree, popups);
	Event.observe($('menu'), 'mouseover', clear_menu_timer, false);
	Event.observe($('menu'), 'mouseout', init_menu_timer, false);
  
  	// if(Browser.isIE()) initForIE();
	
	//Pop-ups
	var origin = Element.cumulativeOffset($('contents'));
	var inc = 0;
	popups.each(function(popup) {
		var popup_x = 20+(217*inc++);
		var popup_y = 20;
	    var curr_popup = new PopUp({
			title: popup['name'], 
			url_var: popup['url_var'],
			contents: popup['contents'], 
			draggable: true,
			position: { 
				x: origin[0]+popup_x, 
				y: origin[1]+popup_y 
			}
		}).toggleBind(popup['url_var']+"_popup_link");
	});
	
	if ($("register_form"))
	{
		new my_form("register_form", {
			fields_call: "#field",
			obligatories: ["name", "firstname", "mail"],
			after_initialize: function()
			{
				Event.observe("register_submit", "click", this.validate.bind(this), false);
			},
			execute_action: function()
			{
				new Ajax.Request(this.form_obj.action, { 
					method: 'post', 
					parameters: this.form_obj.serialize(), 
					evalScripts:true,
					onLoading:function() {
						var loading_img = new Image();
						this.form_obj.up(".popup_content").insert({bottom:Builder.node("div", { id: "ajaxResponse" }, " ")}).hide();
						this.form_obj.up(".popup_content").insert({bottom:Builder.node("div", { id: "loadingPane" }, " ")}).show();
					}.bind(this),
					onComplete:function(transport) {
						if (transport.responseText.match(/SUCCESS/)) { this.empty_fields(); msg_timeout = 12000; } else { msg_timeout = 4000; }
						$("loadingPane").remove();
						$("ajaxResponse").update(transport.responseText).show();
						setTimeout(function(){ $("ajaxResponse").fade({afterFinish:function(){ $("ajaxResponse").remove(); }}); }, msg_timeout);
					}.bind(this)
				});
			}
		});
	}
	if ($("unregister_form"))
	{
		new my_form("unregister_form", {
			fields_call: "#field",
			obligatories: [],
			after_initialize: function()
			{
				Event.observe("unregister_submit", "click", this.validate.bind(this), false);
			},
			execute_action: function()
			{
				new Ajax.Request(this.form_obj.action, { 
					method: 'post', 
					parameters: this.form_obj.serialize(), 
					evalScripts:true,
					onLoading:function() {
						var loading_img = new Image();
						this.form_obj.up(".popup_content").insert({bottom:Builder.node("div", { id: "ajaxResponse" }, " ")}).hide();
						this.form_obj.up(".popup_content").insert({bottom:Builder.node("div", { id: "loadingPane" }, " ")}).show();
					}.bind(this),
					onComplete:function(transport) {
						if (transport.responseText.match(/SUCCESS/)) { msg_timeout = 4000; } else { msg_timeout = 4000; }
						$("loadingPane").remove();
						$("ajaxResponse").update(transport.responseText).show();
						// var layouts = this.form_obj.up(".popup_content").getElementsBySelector(".popup_layout");
						// layouts.each(function(elt){ elt.hide(); });
						// this.form_obj.up(".popup_content").firstDescendant().show();
						setTimeout(function(){ window.location.replace("/"); }, msg_timeout);
					}.bind(this)
				});
			}
		});
	}
	
	if(Browser.isIE()) initForIE();
	else if(Browser.isFirefox({gt: 2, lt: 3})) $$('body')[0].setStyle({opacity: 0.9999});
	//Slideshow
  	var counter = [];
  	if(intro_pics.length>0)
  	{
  		window['intro'] = true;
  		counter.push([0, intro_pics.length]);
  		var intro_pos = counter.length-1;
  		var intro_preloader = new ImagePreloader(intro_pics, {
		    afterLoading: function() {
	      		$('loading_indicator').fade({afterFinish: function(){ $('loading_indicator') ? $('loading_indicator').remove() : null;}});
	        	var intro_slideshow = new SlideShow(intro_pics, {
	        		auto: true,
	        		prefix: 'intro_'
		      	});
		      	debug ? console.log('depuis le 1er') : null;
				if (open_popup != null) 
				{
					$("popup_"+open_popup).appear({duration:0.4});
					if (open_popup_layout != null)
					{
						var layouts = $("popup_"+open_popup).down(".popup_content").childElements();
						layouts.each(function(elt){ elt.hide(); });
						$("popup_"+open_popup).down(".popup_content").down("#popup_layout_"+open_popup_layout).show();
					}
				}
				intro_slideshow.run();
		    },
		    afterCheck: function() {
		      counter[intro_pos] = [intro_preloader.currCount, intro_preloader.imageList.length];
		      updateLoadingValue();
		    }
		});
	}
	else
	  window['intro'] = false;
	
	counter.push([0, pics.length]);
	var pics_pos = counter.length-1;
	var slide = null;
	var pics_preloader = new ImagePreloader(pics, {
	  afterCheck: function() {
	    counter[pics_pos] = [pics_preloader.currCount, pics_preloader.imageList.length];
	    updateLoadingValue();
	  },
	  afterLoading: function() {
	  	// $('logo').observe('mousedown', logo_over, false);
		$('logo').observe('mouseover', logo_over, false);
	  	slide = new SlideShow(pics , {
	  		auto: true,
	  		beforeEffect: function(current_id, next_id) {
	  			Event.stopObserving($('previous'), 'click', previous_button_action, false);
	  			Event.stopObserving($('next'), 'click', next_button_action, false);
	  			Event.stopObserving(window, 'keyCode', next_button_action, false);
	  			Event.stopObserving(window, 'keydown', detectKey, false);
	  			debug ? console.log('current: ' + current_id) : null;
	  		},
	  		afterEffect: function(current_id, next_id) {
	  			Event.observe($('previous'), 'click', previous_button_action, false);
	  			Event.observe($('next'), 'click', next_button_action, false);
	  			Event.observe(window, 'keyCode', next_button_action, false);
	  			Event.observe(window, 'keydown', detectKey, false);
	  			
	  			if(window['next'] == true)
	  				window['next'] = false;
	  			if(window['previous'] == true)
	  				window['previous'] = false;
	  			$('controls').appear();
	  			
	  			if(!window['intro'])
	  				if(pics[next_id].subcat.pics.length > 1) {
	  					$('control_btns').appear({from: $('control_btns').getStyle('opacity')});
	  					$('previous').setStyle({cursor: 'pointer'});
	  					$('next').setStyle({cursor: 'pointer'});
	  					$('play-pause').setStyle({cursor: 'pointer'});
	  				}
	  				else {
	  					if($('control_btns').visible()) {
	  						$('control_btns').fade({from: $('control_btns').getStyle('opacity'), to: 0.3});
	  						$('previous').setStyle({cursor: 'default'});
	  						$('next').setStyle({cursor: 'default'});
	  						$('play-pause').setStyle({cursor: 'default'});
	  					}
	  					else
	  						$('control_btns').appear({from: $('control_btns').getStyle('opacity'), to: 0.3});
	  				}
	  		}.bind(slide),
	  		_nextCalculation: function() {
	  			if(this.current==-1) return 0;
	  			if(pics[slide.current].subcat.pics.length==1)
	  				return slide.current;
	  			return pics[slide.current].subcat.start_index+(this.current - this.pics[this.current].subcat.start_index+1)%pics[slide.current].subcat.pics.length;
	  		},
	  		_previousCalculation: function() {
	  			if(this.current==-1) return 0;
	  			if(pics[slide.current].subcat.pics.length==1)
	  				return slide.current;
	  			if(pics[slide.current].subcat.start_index==slide.current)
	  				return pics[slide.current].subcat.start_index+pics[slide.current].subcat.pics.length-1;
	  			return pics[slide.current].subcat.start_index+(this.current - this.pics[this.current].subcat.start_index-1)%pics[slide.current].subcat.pics.length;
	  		}
	  	}
	  	);
	  	Object.extend(slide, {
	  		updateStatus: function() {
	  		debug ? console.debug('Entrée dans UpdateStatus') : null;
	  		var auto = this.automaticSlide();
	  		
	  		playPause_button(auto);
	  		
	  		$('category_control').innerHTML = this.pics[this.current].cat;
	  		$('subcategory_control').innerHTML = this.pics[this.current].subcat.innerHTML;
	  		$('total_pics').innerHTML = this.pics[this.current].subcat.pics.length;
	  		$('current_pic').innerHTML = this.current - this.pics[this.current].subcat.start_index+1;
	  		debug ? console.debug('Sortie de UpdateStatus') : null;
	  	}.bind(slide)
	  	});
	  	window['alternate_slide'] = slide;
	  	// updateLoadingValue();
	  }
	});
	
	function updateLoadingValue() {
		var total_pics = 0;
		var loaded_pics = 0;
		counter.each(function(el){
			total_pics += el[1];
			loaded_pics += el[0];
		});
		var value = 0;
		if(total_pics!=0)
		value = (loaded_pics / total_pics)*100; 
		debug ? console.log(loaded_pics+'/'+total_pics) : null;
		if($('loading') && $('loading').visible())
		{
			var val = Math.floor(value);
			$('loading').innerHTML = (val<10 ? "0"+val: val)+'%';
		}
		if(value==100) {
			value++;
			if($('loading_infos').getOpacity() == 1) {
				var f = function() {
					$('loading_infos').fade({duration: 0.4, queue: {scope: 'loading_end', position: 'end'}, 
					afterFinish: function() { 
						if (gallery_index == null)
						{
							start_show_menu(5000);
							$('loading_infos').innerHTML='<img class="load_end_indicator" src="images/load_end_indicator.png" />'; 
							$('loading_infos').appear({duration: 0.5, queue: {scope: 'loading_end', position: 'end'}, afterFinish: function() { setTimeout("$('loading_infos').fade({duration: 0.4})", 1500);}});
						}
					}
				});
			};
			setTimeout(f, 1500);
		}
		if(window['alternate_slide'] && gallery_index!== null && pics[gallery_index]) {
			if(window['intro'])
			{
				window['intro'] = false;
				new Effect.BlindDown('home_link', {
					duration: 0.4
				});
				showAlternateSlideShow();
				$('menu').accordion_object.openByName($('pictures').slideShow.pics[gallery_index].cat);
				$('pictures').slideShow.pics[gallery_index].subcat.addClassName('selected');
			}  
			menu_hide();
			$('pictures').slideShow.automaticSlide() ? $('pictures').slideShow.resetAutomaticSlide({start: true, id: gallery_index}) : $('pictures').slideShow.startAutomaticSlide({start: true, id: gallery_index});
			deselectItemAccordion();
		}
	}
}
	
	function playPause_button(running) {
		var button = $('play-pause');
	  var play_pause_btn_refs = Browser.isIE() ? window['btn_img_refs']._images : $('play-pause')._images;
	  var new_element = running ? play_pause_btn_refs.pause : play_pause_btn_refs.play;
	  	if(!Browser.isIE())
	  	  button.src = new_element.src;
	  	else {  //Browser.isIE()
	    var t = new_element;
	    button.replaceNode(t);
	    t.id = 'play-pause';
	    $(t).addClassName('controls_btns');
	  	}
	  	  
	  	// if(Browser.isIE(6)) IEPngHack();
	  	if(Browser.isIE()) Event.observe($('play-pause'), 'click', playPause_action, false);
	  	$('play-pause').setAttribute("title", (running ? "Pause" : "Play")+" (Espace)");
	  }
	  function detectSpaceBar(evt) 
	  {
	  	var key = Keyboard.keyCode(evt);
	  	debug ? console.log(key) : null;
	  	if(key == KEY_SPACE && !window['intro'])
	  		playPause_action(evt);
	  }
	  //Controls
	  Event.observe($('play-pause'), 'click', playPause_action, false);
	  Event.observe($('previous'), 'click', previous_button_action, false);
	  Event.observe($('next'), 'click', next_button_action, false);
	  Event.observe(window, 'keydown', detectKey, false);
	  Event.observe(window, 'keydown', detectSpaceBar, false);
	
	  new Accordion();
}

function load_images (evt) {
  var play_pause_images = new ImagePreloader(['images/controls/play.png', 'images/controls/pause.png']).getImages();
  if(Browser.isIE()){
    window['btn_img_refs'] = {};
    var play_pause_btn = window['btn_img_refs'];
  }
  else
    var play_pause_btn = $('play-pause');
  var t = Object.extend(play_pause_btn, {_images: {play: play_pause_images[0], pause: play_pause_images[1]}});
  if(Browser.isIE()) window['btn_img_refs'] = t;
}

function initForIE () {
  $('previous').innerHTML='-';
  IECssBeforePropertyHack('#menu h1.menu_item', {tag:'span', contents: '+', className: 'menu_item_before'});
  CssSelectorHackForIE('#menu > div', 'ie_class');
  CssSelectorHackForIE('#menu > div.galleries', 'ie_class');
  CssSelectorHackForIE('#menu > div.popups', 'ie_class');
  CssSelectorHackForIE('#home_link > h1', 'ie_class');
  // IEPngHack();
  // IEPngBackgroundHack();
}


Event.observe(window, Browser.isIE() ? 'load' : 'dom:loaded', function(e){ if (init) load_images() }, false);
Event.observe(window, 'load', function(e){ if (init) init_lucky() }, false);
