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

var mainClass = {

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ VARIABLES.
	cacheImage: [],
	formNotificationDuration: 2000,
	linkFrom: false,
	slideshowObj: {},

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ INITIALIZE.
	initialize: function() {	
		// Ajax.
		$.ajaxSetup({
			url: 'frontHtml.php',
			type: 'POST',
			dataType: 'json',
			async: true,
			cache: false
		});
		this.menuTweak();
		this.projectInit();
		this.contactFormInit();
		this.googleAnalyticsInit();
	},

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GOOGLE ANALYTICS.
	googleAnalyticsInit: function() {
		var apiHost = (('https:' == document.location.protocol) ? 'https://ssl.' : 'http://www.');
		$.getScript(apiHost + 'google-analytics.com/ga.js', function() {
			var pageTracker = _gat._getTracker('UA-3114681-2');
			pageTracker._initData();
			pageTracker._trackPageview();
		});
	},

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PRELOAD IMAGES.
	preLoadImage: function() {
		var argsCount = arguments.length;
		for (var i=argsCount; i--;) {
			var imgObj = document.createElement('img');
			imgObj.src = arguments.length[i];
			mainClass.cacheImage.push(imgObj);
		}
	},

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ROLL-OVER IMAGES.
	rolloverImage: function() {
		$('img[src*=-out], input[src*=-out]').each(function(i) {
			var imgSrc = $(this).attr('src');
			var imgPath = imgSrc.substring(0, imgSrc.lastIndexOf('-'));
			var imgExtension = imgSrc.substr(imgSrc.lastIndexOf('.'));
			mainClass.preLoadImage(imgPath+'-over'+imgExtension);
			$(this).bind({
				mouseenter: function() {
					$(this).attr('src', imgPath+'-over'+imgExtension);
				},
				mouseleave: function() {
					$(this).attr('src', imgPath+'-out'+imgExtension);
				}
			});
		});
	},

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MENU LIST TOKEN.
	listTokenRemove: function() {
		$('li:last-child').each(function(i) {
			if ($(this).css('backgroundImage').search(/bullet/i) == -1)
				($(this).css('float') == 'right') ? $(this).css({paddingLeft:'0px'}) : $(this).css({paddingRight:'0px', backgroundImage:'none'});
		});
		$('li:first-child').each(function(i) {
			if ($(this).css('backgroundImage').search(/bullet/i) == -1)
				($(this).css('float') == 'right') ? $(this).css({paddingRight:'0px', backgroundImage:'none'}) : $(this).css('padding-left', '0px');
		});
	},

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ VIMEO VIDEOS.
	videoReplacement: function() {
		$('video').each(function(i) {
			var userAgent = navigator.userAgent.toLowerCase();
			var videoSrc = $(this).attr('src').replace(/\d+/g, '');
			var videoId = $(this).attr('src').replace(/\D+/g, '');
			var videoWidth = $(this).attr('width');
			var videoHeight = $(this).attr('height');
			if (userAgent.search(/ipad/i) != -1) {
				$(this).replaceWith('<video src="'+videoSrc+videoId+'" id="video'+i+'" width="'+videoWidth+'" height="'+videoHeight+'" controls="controls"></video>');
			}
			if (userAgent.search(/iphone/i) != -1)
				$(this).replaceWith('<video src="'+videoSrc+videoId+'&quality=mobile" id="video'+i+'" width="'+videoWidth+'" height="'+videoHeight+'" controls="controls"></video>');
			else {
				videoFlash = $.flash.create({
					swf: 'http://vimeo.com/moogaloop.swf',
					width: videoWidth,
					height: videoHeight,
					wmode: 'transparent',
					quality: 'high',
					menu: 'false',
					allowscriptaccess: 'always',
					allowFullScreen: true,
					flashvars: {
						clip_id: videoId,
						server: 'vimeo.com',
						show_title: '0',
						show_byline: '0',
						show_portrait: '0',
						color: 'd02142',
						fullscreen: '1',
					}
				});
				$(this).replaceWith(videoFlash);
			}
		});
	},


/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C O N T E N T   P A G E.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MENU BACKGROUND.
	menuTweak: function() {
		$('div#menu a').hover(
			function() {
				$(this).stop(true,true).animate({backgroundPosition:'-160px 0px'}, {duration:500});
			},
			function() {
				
				$(this).stop(true,true).animate({backgroundPosition:'-300px 0px'}, {duration:200, complete:function() {
					$(this).css({backgroundPosition: '0px 0px'});
				}})
			}
		);
		$('a.scrolltop').hover(
			function() {
				$(this).stop(true,true).animate({backgroundPosition:'0px -17px'}, {duration:200});
			},
			function() {
				$(this).stop(true,true).animate({backgroundPosition:'0px 0px'}, {duration:200});
			}
		);
		//
		$('.scroll').click(function(e) {
			e.preventDefault();
			mainClass.linkFrom
			mainClass.anchorScroll($(this).attr('href').replace(/#/g,''));
		});		
	},

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PROJECT THUMBS.
	projectInit: function() {
		// Thumbs.
		$('#projectList a').each(function() {	
			$(this).next('img').wrap('<div class="rollover">');
			$('<img>').addClass('circle').css({top:'136px'}).appendTo($(this).next());
			var thumbTitle = $('<table cellpadding="0" cellspacing="0" border="0">').css({top:'-'+$(this).parent().height()+'px'}).appendTo($(this).next());
			thumbTitle.html('<tr><td>'+$(this).html()+'</td></tr>');
			$(this).empty();
			$(this).hover(
				function() {
					if (!$(this).hasClass('selected')) {
						$(this).next().children('img.thumb').stop(true,true).animate({top:'-'+$(this).parent().height()+'px'}, 500, 'easeOutQuart');
						$(this).next().children('img.circle').stop(true,true).delay(300).animate({top:'-18px'}, 300, 'easeOutQuart');
						$(this).next().children('table').stop(true,true).delay(450).animate({top:'0px'}, 300, 'easeOutQuart');
					}
				},
				function() {
					if (!$(this).hasClass('selected')) {
						$(this).next().children('table').stop(true,true).animate({top:'-'+$(this).next().children('table').height()+'px'}, 200, 'easeInQuart');
						$(this).next().children('img.circle').stop(true,true).delay(150).animate({top:$(this).next().children('img.circle').height()+'px'}, 200, 'easeInQuart');
						$(this).next().children('img.thumb').stop(true,true).delay(200).animate({top:'0px'}, 350, 'easeInQuart');
					}
				}
			);		/*		
			$(this).bind({
				focus: function() {
					if ($(this).val() == $(this).data('value'))
						$(this).removeClass('empty').val('');
					if ($(this).hasClass('password')) {
						$(this).hide();
						$(this).next().show().focus();
					}
				},
				change: function() {
					if (empty($(this).val()))
						$(this).addClass('empty');
					else
						$(this).removeClass('empty');
				},
				blur: function() {
					if (empty($(this).val())) {
						$(this).addClass('empty');
						if (!$(this).is('select'))
							$(this).val($(this).data('value'));
						else
							$('option', this).first().text($(this).data('value'));
					}
				}
			});
			$(this).trigger('blur');*/
		});
		// Init project frame.
		if (!$('#projectFrame').hasClass('opened'))
			$('#projectFrame').css({height:'0px'});
		// Previous arrow.
		$('#projectFrame a.previous').live({
			mouseenter: function(e) {
				$(this).stop(true,true).animate({backgroundPosition:'-17px 0px'}, {duration:200});
			},
			mouseleave: function(e) {
				$(this).stop(true,true).animate({backgroundPosition:'0px 0px'}, {duration:200});
			},
			click: function(e) {
				e.preventDefault();
				// previous project.
				if (mainClass.slideshowObj.current() == 0) {
					thumbList = $('#projectList a');
					// go to last.
					if (thumbList.index($('a.selected')) == 0)
						thumbList.eq(thumbList.size()-1).trigger('click');
					else
						thumbList.eq(thumbList.index($('a.selected'))-1).trigger('click');
				}
				else
					mainClass.slideshowObj.prev();
			},
		});
		// Next arrow.
		$('#projectFrame a.next').live({
			mouseenter: function(e) {
				$(this).stop(true,true).animate({backgroundPosition:'0px 0px'}, {duration:200});
			},
			mouseleave: function(e) {
				$(this).stop(true,true).animate({backgroundPosition:'-17px 0px'}, {duration:200});
			},
			click: function(e) {
				e.preventDefault();
				// next project.
				//console.log(mainClass.slideshowObj.currentSlide)
				if (mainClass.slideshowObj.length() - mainClass.slideshowObj.current() == 1) {
					thumbList = $('#projectList a');
					// got to first.
					if (thumbList.size() - thumbList.index($('a.selected')) == 1)
						thumbList.eq(0).trigger('click');
					else
						thumbList.eq(thumbList.index($('a.selected'))+1).trigger('click');
				}
				else
					mainClass.slideshowObj.next();
			},
		});
		// Close cross.
		$('#projectFrame a.close').live({
			click: function(e) {
				//e.preventDefault();
				$('#projectList a.selected').removeClass('selected').trigger('mouseout');
				$('#projectFrame').removeClass('opened').animate({height:'0px', paddingTop:'0px', marginBottom:'0px'}, {duration:800, easing:'easeInOutExpo'});
				mainClass.anchorScroll('real');
				//window.location.href= '/';
			},
		});

	},

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ LINKS — DEEP LINKING.
	linkDeep: function() {
		$.address.state('/').init(function() {
			linkObj = $('#projectList a').live('click', function(e) {
				mainClass.linkFrom = $(this).attr('id');
			}).address();
		})
		.change(function(e) {
			var linkFrame = $('#projectFrame');
			var hrefPath = ($.address.state() + decodeURI(e.path)).replace(/\/\//,'/');
			//console.log($.address.state() + ' | ' + e.path + ' | ' + hrefPath);
			if (hrefPath != '/') {
				linkFrame.oneTime(2500, 'linkDelay', function() {
					linkFrame.html('Chargement…');
				});
				$.ajax({
					data: {
						xhrAct: 'getProject',
						urlrewriting: hrefPath
					},
					cache: true,
					beforeSend: function() {
					},
					success: function(jsonObj, textStatus, xhrObj) {
						document.title = jsonObj.title;
						// Thumbs.
						console.log(trim(hrefPath,'/'));
						linkObj.closest('ul').find('a.selected').removeClass('selected').trigger('mouseout');
						linkObj.closest('ul').find('a[href*="'+trim(hrefPath,'/')+'"]').trigger('mouseover').addClass('selected');
						// Frame.
						linkFrame.stopTime('linkDelay');
						linkFrame.html(jsonObj.body);
						mainClass.slideshowTweak();
						$('<a>').attr('href','').addClass('previous').appendTo(linkFrame);
						$('<a>').attr('href','').addClass('next').appendTo(linkFrame);
						$('<a>').attr('href','/').addClass('close').appendTo(linkFrame).address();
						// Open frame.
						if (!linkFrame.hasClass('opened')) {
							linkFrame.addClass('opened').animate({height:'500px', paddingTop:'30px', marginBottom:'30px'}, {duration:800, easing:'easeInOutExpo', complete:function() {
							}});
						}
						// Frame is already opened.
						else {
							linkFrame.css({paddingTop:'30px', marginBottom:'30px'});
							mainClass.slideshowTweak();
						}
						mainClass.anchorScroll('projectFrame');
					},
					error: function(xhrObj, textStatus, errorThrown) {
						linkFrame.stopTime('linkDelay');
						document.title = 'La page est introuvable';
						linkFrame.html('La page est introuvable');
					}
				});
			}
			else {
				console.log('root');
			}			
		});
	},

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SCROLL TO ANCHOR.
	anchorScroll: function(tagId) {
		var tagOffset = $('#'+tagId).offset();
		var tagTop = tagOffset.top - $('#headerlarge').height() + $('.hr').height();
		$('html, body').animate({scrollTop:tagTop}, 800, 'easeInOutExpo');
	},

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SLIDE-SHOW.
	slideshowTweak: function() {
		mainClass.slideshowObj = $('.projet').peKenburnsSlider({
			api: true
		});
	},



/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C O N T A C T   F O R M.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CONTACT FORM – EVENTS.
	/*contactFormInit: function() {
		$('label#contactFormNotification').fadeTo(0, 0);
		$('form#contactForm').bind('submit', function(e) {
			e.preventDefault();
			var tagObj = this;
			mainClass.contactFormFieldRequired(tagObj);
			if (!$(tagObj).data('formError') && !emailCheck($('input#contactFormEmail').val())) {
				mainClass.contactFormNotification($(tagObj).attr('data-invalid').replace(/\asterisme/g, '“'+stringTrim($('input#contactFormEmail').prev('label').text().replace(/[:*]+/g,''))+'”'), 1500);
				tagObj.data('formError', true);
			}
			if (!$(tagObj).data('formError')) {
				mainClass.contactFormNotification($(tagObj).attr('data-loading'));		
				$.ajax({
					url: 'contactForm.php',
					data: $(tagObj).serialize(),
					success: function(responseText) {
						if (responseText == 'true')
							mainClass.contactFormNotification($(tagObj).attr('data-success'), 1500);
						else
							mainClass.contactFormNotification($(tagObj).attr('data-error'), 1500);
					},
					error: function() {
						mainClass.contactFormNotification($(tagObj).attr('data-error'), 1500);
					}
				});
			}
		});
	},*/	

	contactFormInit: function() {
		this.formFieldLabel();
		// Submit event.
		$('*[id$="Notification"]').fadeOut(0);
		$('form[id$="Form"]').bind('submit', function(e) {
			e.preventDefault();
			var tagObj = this;
			// Form with a submit button.
			if ($('input[type="submit"]', tagObj).is('*')) {
				mainClass.formFieldRequired(tagObj);
				if (!$(tagObj).data('formError') && $('input[id$="Email"]', tagObj).is('*') && !emailCheck($('input[id$="Email"]', tagObj).val())) {
					mainClass.formNotification(tagObj, $(tagObj).data('invalid').replace(/\*/g, '“'+stringTrim($('input[id$="Email"]', tagObj).prev('label').text().replace(/[:*]+/g,''))+'”'), mainClass.formNotificationDuration);
					$(tagObj).data('formError', true);
				}
				if (!$(tagObj).data('formError')) {
					mainClass.formNotification(tagObj, $(tagObj).data('loading'));
					$.ajax({
						url: 'contactForm.php',
						data: $(tagObj).serialize(),
						success: function(responseText) {
							if (responseText == 'true')
								mainClass.formNotification(tagObj, $(tagObj).data('success'), 1500);
							else
								mainClass.formNotification(tagObj, $(tagObj).data('error'), 1500);
						},
						error: function() {
							mainClass.formNotification(tagObj, $(tagObj).data('error'), 1500);
						}
					});
				}
			}
		});
	},

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FIELDS — LABEL.
	formFieldLabel: function(inputObj) {
		var inputObj = (inputObj) ? inputObj : $(':input[data-value]');
		inputObj.each(function() {		
			$(this).bind({
				focus: function() {
					if ($(this).val() == $(this).data('value'))
						$(this).removeClass('empty').val('');
					if ($(this).hasClass('password')) {
						$(this).hide();
						$(this).next().show().focus();
					}
				},
				change: function() {
					if (empty($(this).val()))
						$(this).addClass('empty');
					else
						$(this).removeClass('empty');
				},
				blur: function() {
					if (empty($(this).val())) {
						$(this).addClass('empty');
						if (!$(this).is('select'))
							$(this).val($(this).data('value'));
						else
							$('option', this).first().text($(this).data('value'));
					}
				}
			});
			$(this).trigger('blur');
		});
	},

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FORM — REQUIRED FIELDS.
	formFieldRequired: function(tagObj) {
		$(tagObj).data('formError', false);
		$('input, textarea', tagObj).each(function(i) {
			if (($(this).prev('label').attr('data-required') == 1) && (empty($(this).val()) || ($(this).val() == $(this).data('value')))) {
				mainClass.formNotification(tagObj, $(tagObj).attr('data-required').replace(/\*/g, '“'+stringTrim( !empty($(this).prev('label').attr('data-label')) ? ($(this).prev('label').attr('data-label').replace(/[:*]+/g,'')) : ($(this).prev('label').text().replace(/[:*]+/g,'')) ) +'”'), mainClass.formNotificationDuration);
				$(tagObj).data('formError', true);
				return false;
			}
		});
	},

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FORM — NOTIFICATION HIGHLIGHT.
	formNotification: function(tagObj, str, time) {
		$('div#contactFormNotification').text(str).fadeIn('normal');
		if (time)
			$('div#contactFormNotification').delay(time).fadeOut('normal');
	}

};



/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ O N   D O M   R E A D Y.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ EVENTS — WINDOW.
jQuery(window).bind({
});

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ EVENTS — DOCUMENT.
jQuery(document).ready(function() {
	mainClass.initialize();
});

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DEEP LINKING.
mainClass.linkDeep();



/*—~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
