// Temp - debugging
var echo = function(msg) {
	if($('outMsg') == null) {
		var out = new Element('div',{'id': 'outMsg','style': 'position:absolute; z-index:99999; padding:0 4px; background:#FFF; color:#000;'});
		out.inject($('headerWrapper'),'top');
	}
	$('outMsg').appendText(msg);
	var br = new Element('br');
	$('outMsg').grab(br);
};


function initList() {
	var lists = $$('.content .list');
	lists.each(function(item,index) {
		var link = item.getElement('.image a'); //.getProperty('href');
		if(link) {
			item.addEvent('mouseenter', function(e) {
				item.addClass('list-over');
			});
			item.addEvent('mouseleave', function(e) {
				item.removeClass('list-over');
			});
			item.addEvent('click', function(e) {
				if(link.getProperty('target') == '_blank') {
					window.open(link.getProperty('href'));
				} else {
					location.href = link.getProperty('href');
				}
			});
		}
	});
}
function initImgs() {
	var imgs = $$('.content .img a');
	var marginEl = null;
	imgs.each(function(item,index) {
		var div = new Element('div', {'class':'img-in'});
		div.wraps(item);
		if(index == 0) {
			marginEl = div;
		}
		//var link = item.getElement('.image a').getProperty('href');
		/*
		item.addEvent('mouseenter', function(e) {
			item.addClass('list-over');
		});
		item.addEvent('mouseleave', function(e) {
			item.removeClass('list-over');
		});
		item.addEvent('click', function(e) {
			location.href=link;
		});
		*/
	});
	if(marginEl != null) {
		var height = marginEl.getSize().y.toInt();
		var fx = new Fx.Tween(marginEl, {'duration':400,'property':'margin-top'}).set(0);
		var currentImg = 0;
		var lastIndex = 0;
		var arrayImgs = new Array();
		var navImgs = $$('.content .nav img');
		if(navImgs.length == 1) {
			navImgs[0].addClass('hidden');
		} else {
			navImgs.each(function(item,index) {
				if(index==0) {
					item.addClass('selected');
				}
				item.addEvent('mouseenter', function(e) {
					item.addClass('selected');
				});
				item.addEvent('mouseleave', function(e) {
					if(index!=currentImg) {
						item.removeClass('selected');
					}
				});
				item.addEvent('click', function(e) {
					$$('.content .nav img').each(function(i) {
						i.removeClass('selected');
					});
					item.addClass('selected');
					currentImg = index;
					fx.start(height*index*-1);
				});
				arrayImgs.include(item);
			});
		}
		// Key event
		Event.Keys.each(function(item,index) {
			echo(Event.Keys.keyOf(item)+' '+item);
		});
		var divContent = $(document.body).getElement('.content');
		if(divContent) {
			$(document).addEvent('keydown', function(event){
				if(event.key == "up") {
					echo('uuuuup');
				}
				if(event.key == "down") {
					echo('doooown');
				}
			});
		}
	}
}
var imagesNavigation = new Class({
	initialize: function() {
		var imgs = $$('.content .img a');
		var marginEl = null;
		imgs.each(function(item,index) {
			var div = new Element('div', {'class':'img-in'});
			div.wraps(item);
			if(index == 0) {
				marginEl = div;
			}
			var link = item.getProperty('href');
			var newlink = this.parseLink(link);
			//echo(link);
			item.setProperty('href',newlink);
			if(newlink != link) {
				linkrel = item.getProperty('rel');
				linkrel = linkrel + ';height=500;width=900';
				item.setProperty('rel', linkrel);
			}
			/*
			item.addEvent('mouseenter', function(e) {
				item.addClass('list-over');
			});
			item.addEvent('mouseleave', function(e) {
				item.removeClass('list-over');
			});
			item.addEvent('click', function(e) {
				location.href=link;
			});
			*/
		}.bind(this));
		if(marginEl != null) {
			this.height = marginEl.getSize().y.toInt();
			this.fx = new Fx.Tween(marginEl, {'duration':400,'property':'margin-top'}).set(0);
			this.currentIndex = 0;
			this.lastIndex = 0;
			this.arrayImages = new Array();
			this.arrayImages = $$('.content .nav img');
			if(this.arrayImages.length == 1) {
				this.arrayImages[0].addClass('hidden');
			} else {
				this.arrayImages.each(function(item,index) {
					if(index==0) {
						item.addClass('selected');
					}
					item.addEvent('mouseenter', function(e) {
						item.addClass('selected');
					}.bind(this));
					item.addEvent('mouseleave', function(e) {
						if(index!=this.currentIndex) {
							item.removeClass('selected');
						}
					}.bind(this));
					item.addEvent('click', function(e) {
						this.selectImage(index);
					}.bind(this));
					this.lastIndex = index;
				}.bind(this));
			}
			// Key event
			var content = $(document.body).getElement('.content .nav .contentEl');
			var contentScroll = new Fx.Scroll(content);
			/*content.addEvent('scroll',function(e) {
				echo('test');
				e.preventDefault();
			});*/
			var toEl = null;
			$(document).addEvent('keydown', function(event){
				if(event.key == "up") {
					toEl = this.selectImage(this.currentIndex-1);
					contentScroll.toElement(toEl);
				}
				if(event.key == "down") {
					toEl = this.selectImage(this.currentIndex+1);
					contentScroll.toElement(toEl);
				}
			}.bind(this));
		}
	},
	selectImage: function(index) {
		if(index>=0 && index<=this.lastIndex && index!=this.currentIndex) {
			this.arrayImages.each(function(item) {
				item.removeClass('selected');
			});
			this.arrayImages[index].addClass('selected');
			this.currentIndex = index;
			this.fx.cancel();
			this.fx.start(this.height*index*-1);
		}
		return this.arrayImages[this.currentIndex];
	},
	parseLink: function(url) {
		//http://vimeo.com/10791034
		//http://player.vimeo.com/video/10791034?autoplay=1
		
		//http://www.youtube.com/watch?v=LGmWxBsE6q4&feature=player_embedded
		//http://www.youtube.com/v/LGmWxBsE6q4?autoplay=1
		var newLink = '';
		var uid = '';
		if(url.test('^http\:\/\/www\.youtube\.com\/', 'i')) {
			res = url.match(/^.*((v\/)|(embed\/)|(watch\?))\??v?=?([^\&\?]*).*/);
			uid = res[5];
			/*pos = url.indexOf('&');
			if(pos==-1) {
				pos = url.length;
			}
			uid = url.substring(31, pos);
			*/
			if(uid.length > 0) {
				newLink = newLink+'http://www.youtube.com/v/'+uid+'?autoplay=1';
			} else {
				newLink = url;
			}
		} else if(url.test('^http\:\/\/vimeo\.com\/', 'i')) {
			pos = url.indexOf('&');
			if(pos==-1) {
				pos = url.indexOf('?');
			}
			if(pos==-1) {
				pos = url.indexOf('/',18);
			}
			if(pos==-1) {
				pos = url.length;
			}
			uid = url.substring(17, pos);
			newLink = newLink+'http://player.vimeo.com/video/'+uid+'?autoplay=1';
		}
		if(newLink.length == 0) {
			newLink = url;
		}
		return newLink;
	}
});
var lettersNavigation = new Class({
	initialize: function() {
		this.letters = $$('.content .textBig div');
		this.arrayLetters = $$('.content .nav .letter a');
		if(this.arrayLetters.length > 0) {
			this.arrayLetters.each(function(item,index) {
				var anchor = item.getProperty('href');
				if(anchor.contains('#')) {
					anchor = anchor.substr(anchor.indexOf('#')+1);
					item.addEvent('mouseenter', function(e) {
						item.addClass('selected');
					}.bind(this));
					item.addEvent('mouseleave', function(e) {
						item.removeClass('selected');
					}.bind(this));
					item.addEvent('click', function(e) {
						e.preventDefault();
						this.goTo(anchor);
					}.bind(this));
				}
			}.bind(this));
			// Key event
			var content = $(document.body).getElement('.content .textBig .contentEl');
			this.scroll = new Fx.Scroll(content);
		}
	},
	goTo: function(anchor) {
		if(anchor!='') {
			this.letters.each(function(item) {
				var id = item.getProperty('id');
				if(id==anchor) {
					this.scroll.toElement(item);
				}
			}.bind(this));
		}
	}
});

var ajaxEngine = new Class({
	Implements: Options,
	options: {
		baseUrl: 'http://srvws01/ludo/oi/',
		urlSuffix: 'type=90',
		container: 'content',
		contentContainer: 'main',
		contentLinksSelector: 'a',
		mainMenu: 'menu',
		menuLinksSelector: 'ul li a',
		menuActiveClass: 'act',
		menuParentSelector: 'ul.level2',
		urlSeparator: '#/'
	},
	initialize: function(options) {
		this.setOptions(options);
		
		// Set default variables
		this.currentUrl = '';
		
		// Set the containers
		this.container = $(this.options.container);
		this.contentContainer = $(this.options.contentContainer);
		this.mainMenu = $(this.options.mainMenu);
		
		// Check the containers
		if(!(this.contentContainer && this.mainMenu)) {
			return;
		}
		
		// Init the loading screen
		this.initLoadingScreen();
		
		// Find all links in menu
		this.mainMenuLinks = this.mainMenu.getElements(this.options.menuLinksSelector);
		this.mainMenuLinks.each(function(link,index) {
			var url = this.getAjaxUrl(link.getProperty('href'));
			if(url) {
				link.addEvent('click', function(event) {
					this.loadContent(url);
					event.stop();
				}.bind(this));
			}
		}.bind(this));
		
		// Check the URL
		if(this.checkUrl()) {
			echo('ok');
			this.loadContent(this.currentUrl);
		}
		echo('fini');
		// Find all links in content
		this.contentContainerLinks = this.contentContainer.getElements(this.options.contentLinksSelector);
	},
	// Gestion du contenu
	loadContent: function(url) {
		// Check if link is different of current location
		if(this.currentUrl == url) {
			// eventuellement indiquer discretement que le contenu est déjà le bon
			return;
		}
		
		// Set the current url
		this.setCurrentUrl(url);
		
		// Show the loading screen
		this.showLoadingScreen({
			'onStart':function() {
				// Start showing loading screen
				this.loadingScreenIsVisible = false;
			}.bind(this),
			'onComplete':function() {
				this.loadingScreenIsVisible = true;
				this.switchContent();
			}.bind(this)
		});
		
		// Start loading content
		this.loadHTML({
			'url':this.currentUrl,
			'onRequest': function() {
				this.switchContentNow=false;
			}.bind(this),
			'onSuccess': function(responseTree, responseElements, responseHTML, responseJS) {
				echo('success!');
				this.newContent = responseHTML;
				//echo(this.newContent);
				this.switchContentNow=true;
				this.switchContent();
			}.bind(this)
		});
		
		// On content loaded : inject new content in contentContainer
		
		// And : check all links to set active the right menu
		
		// And : hide the loading screen
		//this.hideLoadingScreen();
	},
	switchContent: function() {
		if(this.loadingScreenIsVisible && this.switchContentNow) {
			// Switch the content :
			this.contentContainer.set('html', this.newContent);
			this.switchContentNow = false;
			initContent();
			
			// Hide the loading screen
			this.hideLoadingScreen({
				'onStart':function() {
					this.loadingScreenIsVisible = false;
				}.bind(this),
				'onComplete':function() {
					this.loadingScreenIsVisible = false;
				}.bind(this)
			});
		} else {
			//echo('pas switch!');
		}
	},
	loadHTML: function(obj) {
		var url = null;
		var onRequest = null;
		var onSuccess = null;
		if(obj.url) {
			url = obj.url;
		}
		if(obj.onRequest) {
			onRequest = obj.onRequest;
		}
		if(obj.onSuccess) {
			onSuccess = obj.onSuccess;
		}
		var req = new Request.HTML({
			/*update: this.container,*/
			onRequest:onRequest,
			/*function() {
				this.setNewContent=false;
				this.showMask();
			}.bind(this),*/
			onSuccess:onSuccess,
			/*function(responseTree, responseElements, responseHTML, responseJS) {
				this.newContent = responseHTML;
				this.setNewContent=true;
				this.changeContent();
				//Slimbox.scanPage();
			}.bind(this),*/
			noCache: true
		});
		
		req.get(this.getAjaxUrlWithSuffix(url));		
	},
	checkMenu: function(url) {
		this.mainMenuLinks.each(function(link,index) {
			var linkUrl = this.getAjaxUrl(link.getProperty('href'));
			if(url==linkUrl) {
				link.addClass(this.options.menuActiveClass);
				var theParent = link.getParent(this.options.menuParentSelector);
				if(theParent!=null) {
					// lien de 2e niveau, on active le lien parent
					theParent = theParent.getPrevious('a');
					if(theParent!=null) {
						theParent.addClass(this.options.menuActiveClass);
					}
				}
			} else {
				link.removeClass(this.options.menuActiveClass);
			}
		}.bind(this));
	},
	// Gestion URL
	getAjaxUrl: function(url) {
		if(url.contains(this.options.baseUrl)) {
			url = url.substr(this.options.baseUrl.length);
		}
		if(url.test('^(http://|ftp://|https://|mailto:|#|news:|gopher://|file://|nntp://|telnet://|itunes:|rss:|feed:)','i')) {
			return false;
		}
		if(!url.test('(\.html|\.htm|\.php|[^\.]{6})$','i')) {
			return false;
		}
		return url;
	},
	getAjaxUrlWithSuffix: function(url) {
		// Check suffix
		if(url.indexOf('?') != -1) {
			url = url+'&'+this.options.urlSuffix;
		} else {
			url = url+'?'+this.options.urlSuffix;
		}
		return url;
	},
	checkUrl: function() {
		var loc = ''+window.location;
		var posSharp = loc.indexOf('#');
		var url = '';
		if(posSharp > 0) {
			url = loc.substr(posSharp+2, loc.length);
			loc = loc.substr(0, posSharp);
		}
		this.browserBaseUrl = loc;
		//this.currentUrl = url;
		var url = this.getAjaxUrl(url);
		if(url) {
			this.setCurrentUrl(url);
		}
		
		if(this.currentUrl.length > 0) {
			return true;
		} else {
			return false;
		}
	},
	setCurrentUrl: function(url) {
		this.currentUrl = url;
		window.location = this.browserBaseUrl + this.options.urlSeparator + this.currentUrl;
		this.checkMenu(url);
	},
	// Loading screen
	showLoadingScreen: function(obj) {
		var onStart = null;
		var onComplete = null;
		if(obj.onStart) {
			onStart = obj.onStart;
		}
		if(obj.onComplete) {
			onComplete = obj.onComplete;
		}
		this.loadingScreen.get('tween', {
			'property':'opacity',
			'duration':400,
			'onStart':onStart,
			'onComplete':onComplete
		}).start(1);
	},
	hideLoadingScreen: function(obj) {
		var onStart = null;
		var onComplete = null;
		if(obj.onStart) {
			onStart = obj.onStart;
		}
		if(obj.onComplete) {
			onComplete = obj.onComplete;
		}
		this.loadingScreen.get('tween', {
			'property':'opacity',
			'duration':400,
			'onStart':onStart,
			'onComplete':onComplete
		}).start(0);
	},
	initLoadingScreen: function() {
		this.loadingScreen = new Element('div', {'id':'loadingScreen'});
		this.loadingScreen.inject(this.contentContainer, 'after');
		this.loadingScreen.get('tween', {
			'property':'opacity'
		}).set(0);
	}
});

function initContent() {
  var scrollcontent = new MooScroll( {
    'selector': '.scroll',
    'disabledOpacity': '0',
	'handleActiveOpacity':1,
	'smoothMooScroll': {
		'toAnchor': false,
		'toMooScrollArea':false
	}
  });

  var scrollNav = new MooScroll( {
    'selector': '.nav',
    'disabledOpacity' : '0',
	'handleActiveOpacity':1,
	'smoothMooScroll': {
		'toAnchor': false,
		'toMooScrollArea':false
	}
  });

  /*var scrollBigContent = new MooScroll( {
    'selector': '.textBig',
    'disabledOpacity': '0'
  });*/

  var divNav = $(document.body).getElement('.nav');
  if(divNav) {
	  var divContent = divNav.getElement('.contentEl');
	  if(divContent) {
		  var divNavParent = divNav.getParent();
		  var pos = divNav.getPosition(divNavParent);
		  var scrollFx = new Fx.Scroll(divContent, {'duration':1000, 'wait':false, 'transition':Fx.Transitions.linear});
		  var aScrollTop = new Element('a',{'class':'navScrollTop','href':'#'});
		  aScrollTop.inject(divNavParent);
		  aScrollTop.setStyle('left',pos.x+'px');
		  aScrollTop.addEvent('mouseenter', function(e) {
			  //scrollFx.start(30,30);
			  scrollFx.toTop();
		  });
		  aScrollTop.addEvent('mouseleave', function(e) {
			  scrollFx.cancel();
		  });
		  var aScrollBottom = new Element('a',{'class':'navScrollBottom','href':'#'});
		  aScrollBottom.inject(divNavParent);
		  aScrollBottom.setStyle('left',pos.x+'px');
		  aScrollBottom.addEvent('mouseenter', function(e) {
			  //scrollFx.start(30,30);
			  scrollFx.toBottom();
		  });
		  aScrollBottom.addEvent('mouseleave', function(e) {
			  scrollFx.cancel();
		  });
	  }
  }

  initList();
  //initImgs();
  if($(document.body).getElement('.navSpecial')) {
	  var oiLetters = new lettersNavigation();
  } else {
	var oiImages = new imagesNavigation();
  }
  
}
function initLoaded() {
  // Home
  if($('homeContainer')) {
	var homeImg = $('homeContainer').getElement('img');
	var imgSize = $(homeImg).getSize();
	
	imgResize(homeImg, imgSize.x, imgSize.y);
	
	window.addEvent('resize', function() {
		imgResize(homeImg, imgSize.x, imgSize.y);
	});
  }
}
function imgResize(img, originalWidth, originalHeight) {
	var winSize = $(window).getSize();
	var winWidth = winSize.x;
	var winHeight = winSize.y;
	
	var imgRatio = originalWidth/originalHeight;
	var winRatio = winWidth/winHeight;
	
	var newWidth = 0;
	var newHeight = 0;
	
	if(imgRatio < winRatio) {
		// On s'adapte à la largeur
		newWidth = winWidth;
		newHeight = originalHeight*(winWidth/originalWidth);
	} else {
		// On s'adapte à la hauteur
		newWidth = originalWidth*(winHeight/originalHeight);
		newHeight = winHeight;
	}
	
	// Center
	var newTop = 0;
	var newLeft = 0 - ((newWidth-winWidth)/2);
	
	img.setStyles({
		'width':newWidth+'px',
		'height':newHeight+'px',
		'top':newTop+'px',
		'left':newLeft+'px'
	});
}
function ajaxStart() {
	var ajaxOi = new ajaxEngine();
}
/*************************************************
* Init
*************************************************/
window.addEvent('domready', function() {
	initContent();
	//ajaxStart();
});
window.addEvent('load', function() {
	initLoaded();
});


