/*—~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ M A I N.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

mainHandler = new Class({

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ I N I T.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ VARIABLES.
	formNotificationDuration: 1500,

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ INITIALIZE.
	initialize: function() {
		//this.googleAnalyticsInit();
		this.menuTokenRemove();
		this.mainRolloverImage();
		this.mainRolloverFormImage();
		this.ieHackFixs();
		this.languageSwitch();
		var myMenu = new MenuMatic({
			id: "headerMenuList",
			subMenusContainerId: "headerMenuSubContainer",
			duration: "long"
		});
		this.gameInit();
		this.formInit();
		//this.googleAnalyticsInit();
	},

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GOOGLE ANALYTICS.
	googleAnalyticsInit: function() {
		var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
		new Asset.javascript(gaJsHost + "google-analytics.com/ga.js", {
			onload: function() {
				var pageTracker = _gat._getTracker("UA-2001926-6");
				pageTracker._initData();
				pageTracker._trackPageview();
			}
		});
	},

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MAIN FRAME HEIGHT.
	mainFrameHeight: function() {
		var windowSize = window.getSize();
		if ($chk($('footerFrame'))) {
			var footerPosition = $('footerFrame').getPosition();
			//alert(windowSize.y +"-"+ mainSize.y +"-"+ footerSize.y );
			if (footerPosition.y < windowSize.y)
				$('mainFrame').setStyles({'height': "100%"});
		}
		if ($chk($('homeFrame'))) {
			var mainSize = $('mainFrame').getScrollSize();
			if (windowSize.y >= mainSize.y)
				$('mainFrame').setStyles({'height': "100%"});
			var homeSize = $('homeFrame').getScrollSize();
			if (windowSize.y > homeSize.y)
				$('homeFrame').setStyles({'margin-top': ((windowSize.y-homeSize.y)/2)+"px"});
		}
	},

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MENU LIST TOKEN.
	menuTokenRemove: function() {
		$$('ul', 'ol').each(function(tagObj, i) {
			if (tagObj.get('id')) {
				tagObj.getFirst('li').setStyles({'margin-left': "0px", 'padding-left': "0px"});
				tagObj.getLast('li').setStyles({'margin-right': "0px", 'padding-right': "0px"});
				if (tagObj.getLast('li').getStyle('background-image').test("token", 'i'))
					tagObj.getLast('li').setStyles({'background-image': "none"});
			}
		});
	},

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ IE HACK FIXS.
	ieHackFixs: function() {
		if (Browser.Engine.trident && (Browser.Engine.version <= 5)) {
			$$('hr').each(function(tagObj, i) {
				new Element('div', {'class':tagObj.get('class')}).replaces(tagObj);
			});
			if ($chk($('headerMenuList')))
				$('headerMenuList').getElements('li').setStyles({'display': "inline"});
		}
	},



/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ R O L L — O V E R S.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~ ROLL-OVER BACKGROUND EFFECT – ADD.
	mainRolloverFxBackground: function(tagObj, colorOver) {
		if (!$chk(tagObj.colorOut))
			tagObj.colorOut = tagObj.getStyle('background-color');
		//if (!$chk(tagObj.colorOver))
		tagObj.colorOver = colorOver;	
		tagObj.fx = new Fx.Tween(tagObj, {
			property: "background-color",
			duration: "short",
			link: "cancel"
		});
		if ((tagObj.get('tag') == "input") && (tagObj.get('type') == "text")) {
			tagObj.addEvents({
				focus: function() {
					fieldOnFocus(tagObj);
					tagObj.fx.start(tagObj.colorOver);
				},
				blur: function() {
					tagObj.fx.start(tagObj.colorOut);
				}
			});
		}
		else {
			tagObj.addEvents({
				mouseenter: function() {
					tagObj.fx.start(tagObj.colorOver);
				},
				mouseleave: function() {
					if (tagObj != menuHandler.menuAccordionCurrent)
						tagObj.fx.start(tagObj.colorOut);
				}
			});
		}
	},

	//~~~~~~~~~~~~~~~~~~~~~~~~ ROLL-OVER BACKGROUND EFFECT – REMOVE.
	mainRolloverFxBackgroundRemove: function(tagObj) {
		delete tagObj.colorOut;
		delete tagObj.colorOver;
		delete tagObj.fx;
		if ((tagObj.get('tag') == "input") && (tagObj.get('type') == "text")) {
			tagObj.removeEvents('focus');
			tagObj.removeEvents('blur');
		}
		else {
			tagObj.removeEvents('mouseenter');
			tagObj.removeEvents('mouseleave');
		}
	},


	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ROLL-OVER IMAGES.
	mainRolloverImage: function() {
		$('mainFrame').getElements('img').each(function(imgObj, i) {
			imgSrc = imgObj.get('src');
			if (imgSrc.test("-out")) {
				var imgPath = imgSrc.substring(0, imgSrc.lastIndexOf('-'));
				var imgExtension  = imgSrc.substr(imgSrc.lastIndexOf('.'));
				var imgSize = imgObj.getSize();
				var linkObj = imgObj.getParent();
				linkObj.setStyles({
					position: "relative",
					display : "block"
				});
				linkObj.outObj = imgObj;
				linkObj.overObj = new Element('img', {
					src: imgPath+"-over"+imgExtension,
					title: imgObj.get('title'),
					styles: {
						'position': "absolute",
						'top': linkObj.getStyle('padding-top'),
						'left': linkObj.getStyle('padding-left'),
						'z-index': 10
					}
				}).inject(linkObj).fade('hide');
				linkObj.addEvents({
					mouseenter: function() {
						linkObj.overObj.fade('in');
						//linkObj.outObj.fade('out');
					},
					mouseleave: function() {
						linkObj.overObj.fade('out');
						//linkObj.outObj.fade('in');
					}
				});
			}
		});
	},

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ROLL-OVER FORM IMAGE INPUTS.
	mainRolloverFormImage: function() {
		$('mainFrame').getElements('input[type=image]').each(function(tagObj, i) {	
			imgSrc = tagObj.get('src');
			if (imgSrc.test('-out')) {
				tagObj.removeEvents();
				var imgPath = imgSrc.substring(0, imgSrc.lastIndexOf('-'));
				var imgExtension  = imgSrc.substr(imgSrc.lastIndexOf('.'));
				var imgFile = new Asset.image(imgPath+'-over'+imgExtension);
				tagObj.addEvents({
					mouseenter: function() {
						this.set('src', imgPath+'-over'+imgExtension);
					},
					mouseleave: function() {
						this.set('src', imgPath+'-out'+imgExtension);
					}
				});
			}
		});
	},



/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ F O N T   E M B E D D I N G.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

	fontEmbeddingCufon: function() {
		var cufonOptions = {
			fontFamily: "HelveticaNeueLTStd",
			separate: "words",
			hover: true
		};
	},

	languageSwitch: function() {
		if ($chk($('headerLanguageList'))) {
			var languageSlide = new Fx.Slide('headerLanguageList').hide();
			$('headerLanguageToggler').addEvents({
				click: function() {
					this.fade('out');
					languageSlide.toggle();
				}
			});
			$('headerLanguageCloser').addEvents({
				click: function() {
					$('headerLanguageToggler').fade('in');
					languageSlide.toggle();
				}
			});
		}
	},



/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ G A M E.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

	gameInit: function() {
		
		// Home badge.
		/*if ($chk($('introBadge'))) {
			var introBadgeBlinkLoop = new PulseFade('introBadge', {
				min: .50,
				max: 1,
				duration: 500,
				times: 100000000
			});			
			introBadgeBlinkLoop.start();
		}*/
		
		// Picture animations.
		if ($chk($('gameSenseList'))) {
			$('gameSenseList').getElements('.gameSense').each(function(liObj, i) {
				liObj.txt = liObj.getElement('table').fade('out');
				liObj.coverTop = new Element('img', {class:'coverTop', styles:{top:'-276px'}});
				liObj.coverBottom = new Element('img', {class:'coverBottom', styles:{top:'276px'}});
				liObj.coverTop.inject(liObj, 'top');
				liObj.coverBottom.inject(liObj, 'top');
				//
				var shadow = new Element('li', {class:'gameSense shadow'});
				shadow.inject(liObj.getParent('ul'), 'bottom');
				//
				liObj.addEvents({
					mouseenter: function() {
						liObj.coverTop.tw = new Fx.Tween(liObj.coverTop, {link:'cancel', property:'top', duration:300, transition:Fx.Transitions.Quart.easeOut}).start(0);
						liObj.coverBottom.tw = new Fx.Tween(liObj.coverBottom, {link:'cancel', property:'top', duration:300, transition:Fx.Transitions.Quart.easeOut, onComplete: function() {
							liObj.txt.tw = new Fx.Tween(liObj.txt, {link:'cancel', property:'opacity', duration:200}).start(1);
						}}).start(0);
					},
					mouseleave: function() {
						liObj.coverTop.tw.cancel();
						liObj.coverBottom.tw.cancel();
						liObj.txt.tw = new Fx.Tween(liObj.txt, {link:'cancel', property:'opacity', duration:200, onComplete: function() {
							liObj.coverTop.tw = new Fx.Tween(liObj.coverTop, {link:'cancel', property:'top', duration:300, transition:Fx.Transitions.Quart.easeIn}).start(-276);
							liObj.coverBottom.tw = new Fx.Tween(liObj.coverBottom, {link:'cancel', property:'top', duration:300, transition:Fx.Transitions.Quart.easeIn}).start(276);
						}}).start(0);
					}
				});
			});
		}
		
		// Legal terms toggle.
		if ($chk($('gameLegalFrame'))) {
			var legalSlide = new Fx.Slide('gameLegalFrame', {duration:1000, transition:Fx.Transitions.Quart.easeOut});
			legalSlide.hide();
			$('gameLegalLink').addEvent('click', function(e) {
				e = new Event(e);
				legalSlide.toggle();
				e.stop();
			});
		}

		// Upload file init.
		if ($chk($('gameFile'))) {
			$('gameFileInfos').fade('hide');
			inputFileObj = $('gameFile');
			inputFileValue = inputFileObj.get('value');
			var typeFilterObj = new Object();
			typeFilterObj['Image (*.jpg; *.jpeg)'] = '*.jpg; *.jpeg';
			inputFileUploader = new Swiff.Uploader({
				path: 'scripts/swiffUploaderGame.swf',
				url: 'gameForm.php',
				buttonImage: 'images/gameSenseFile-bg.png',
				width: 308,
				height: 29,
				target: inputFileObj,
				typeFilter: typeFilterObj,
				appendCookieData: true,
				mergeData: true,
				multiple: false,
				fileListMax: 1,
				fileSizeMax: 1*1024*1024,
				onButtonDown : function() {
					this.remove();
				},
				onSelectFail: function(files) {
					$('gameFileInfos').set('html', 'La taille du fichier est trop importante.').fade('in');
				},
				onSelectSuccess: function(files) {
					inputFileObj.set('value', Swiff.Uploader.formatUnit(this.size, 'b'));
					$('gameFileInfos').set('html', this.fileList[0].name + ' | ' + Swiff.Uploader.formatUnit(this.size, 'b')).fade('in');
				},
				onQueue: function() {
					if (!this.uploading) return;
					if (this.percentLoaded == 100)
						$('gameNotification').set('html', 'Sauvegarde…').fade('in');
					else
						$('gameNotification').set('html', 'Chargement de la photo : '+this.percentLoaded+'% ('+Swiff.Uploader.formatUnit(this.size, 'b')+')').fade('in');
				},
				onFileComplete: function(file) {
					console.log(file);
					$('gameForm').getElements('input[type=text], textarea').set('value','');
					$('gameNotification').set('html', file.response.text).fade('in');
					(function() {
						$('gameFileInfos').fade('out');
						$('gameNotification').fade('out');
					}).delay(2000);
				},
				onComplete: function() {
					console.log('onComplete');
				}
			});
		}		
	},




/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ N E W S L E T T E R  F O R M.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FORM – INIT.
	formInit: function() {
		//
		if ($chk($('newsletterFormEmail'))) {
			$('newsletterFormEmail').addEvents({
				focus: function() {
					if (this.get('value') == this.get('data-value'))
						this.set('value', '');
			 },
				blur: function() {
					if (isEmpty(this.get('value')))
						this.set('value', this.get('data-value'));				
				}
			});
		}
		// Submit event.
		$$('*[id$=Notification]').fade('hide');
		$$('form[id$=Form]').addEvent('submit', function(e) {
			console.log('submit');
			e.stop();
			var formObj = this;
			mainHandler.formFieldRequired(formObj);
			if (!formObj.retrieve('formError') && $chk(formObj.getElements('input[id$=Email]')) && !emailCheck(formObj.getElements('input[id$=Email]').get('value'))) {
				console.log('erreur');
				mainHandler.formNotification(formObj, formObj.get('data-invalid'), mainHandler.formNotificationDuration);
				formObj.store('formError', true);
			}
			if (!formObj.retrieve('formError')) {
				mainHandler.formNotification(formObj, formObj.get('data-loading'));
				//
				// Game Form.
				if ($chk($('gameForm'))) {
					inputFileUploader.setOptions({data: formObj.toQueryString()});
					inputFileUploader.start();
				}
				//
				// Default Form.
				else {
					formObj.set('send', {
						url: 'newsletterForm.php',
						link: 'ignore',
						onSuccess: function(responseText) {
							if (responseText == "true")
								mainHandler.formNotification(formObj, formObj.get('data-success'), mainHandler.formNotificationDuration);
							else
								mainHandler.formNotification(formObj, formObj.get('data-error'), mainHandler.formNotificationDuration);
						},
						onFailure: function() {
							mainHandler.formNotification(formObj, formObj.get('data-error'), mainHandler.formNotificationDuration);
						}
					}).send();
				}
			}
		});
	},

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FORM – REQUIRED FIELDS.
	formFieldRequired: function(formObj) {
		formObj.store('formError', false);
		formObj.getElements('input, textarea').some(function(inputObj, i) {
			if (inputObj.getPrevious('label').get('text').match(/\*/g) && isEmpty(inputObj.get('value'))) {
				mainHandler.formNotification(formObj, formObj.get('data-required').replace(/\*/g, "“"+stringTrim(inputObj.getPrevious('label').get('text').replace(/[:*]+/g,""))+"”"), mainHandler.formNotificationDuration);
				formObj.store('formError', true);
				return false;
			}
		});
	},

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FORM – NOTIFICATION HIGHLIGHT.
	formNotification: function(formObj, str, time) {
		formObj.getElements('*[id$=Notification]').set('text', str).fade('in');
		if (time) {
			(function() {
				formObj.getElements('*[id$=Notification]').fade('out');
			}).delay(time);
		}
	}

});



/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ O N   D O M   R E A D Y.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
window.addEvent('domready', function() {
	mainHandler = new mainHandler();
});


//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ EXTEND – FADE BLINK.


var PulseFade = new Class({
			
	//implements
	Implements: [Options,Events],

	//options
	options: {
		min: 0,
		max: 1,
		duration: 200,
		times: 5
	},
	
	//initialization
	initialize: function(el,options) {
		//set options
		this.setOptions(options);
		this.element = $(el);
		this.times = 0;
	},
	
	//starts the pulse fade
	start: function(times) {
		if(!times) times = this.options.times * 2;
		this.running = 1;
		this.fireEvent('start').run(times -1);
	},
	
	//stops the pulse fade
	stop: function() {
		this.running = 0;
		this.fireEvent('stop');
	},
	
	//runs the shizzle
	run: function(times) {
		//make it happen
		var self = this;
		var to = self.element.get('opacity') == self.options.min ? self.options.max : self.options.min;
		self.fx = new Fx.Tween(self.element,{
			duration: self.options.duration / 2,
			onComplete: function() {
				self.fireEvent('tick');
				if(self.running && times)
				{
					self.run(times-1);
				}
				else
				{
					self.fireEvent('complete');
				}
			}
		}).start('opacity',to);
	}
});

