// JavaScript Document
var miniWI = 40;
var _miniWI = miniWI;
var maxWI = 130;
var baseMarge = 14;
var _totalWi = $(window).width();

var totalElements = 0;
var totalMarge = 0;

var tolerance = 2;

var _timer_errorNL = null;

var reaction = 1.3;
var A = ((miniWI - maxWI) / (maxWI * reaction));

var x = 0;
var currentX = -10;
var prevX = x;

var fleches;
//var BASE_URL;
//var INCLUDE_DIR;
//var CURRENT_PAGE;
//var PAGE_IS_BUSY = true;

function initSite() {
	PAGE_IS_BUSY = false;
	
	fleches = new flechesPrevNext();
	fleches.bind();
	if ($('#vignettes a.actif').length == 1) {
		fleches.definirLiens();
		fleches.afficher();
	}
	
	$('#menu').find('a').each(function(){
		var _thisHtml = $(this).html();
		$(this).wrapInner('<em>');
		$(this).append('<span>'+_thisHtml+'</span>');
	});
	$('#menu').find('a').bind('mouseenter',function(){
		$(this).stop();		
		if(!$(this).hasClass('actif')){
			$(this).animate({marginTop:'-13px'},300,'easeOutCirc');
		}
	});
	$('#menu').find('a').bind('mouseleave',function(){
		$(this).stop();
		//if(!$(this).hasClass('actif')){
			$(this).animate({marginTop:'0px'},200,'easeOutCirc');
		//} else {
			//$(this).css('margin-top','0px');
		//}
	});
	
	initVignettes();
	activDock();
	checkValue();
	bindLink();
	initToggleFBLikeBox();

	$(window).resize(function(){initVignettes()});
	$('body').ajaxError(function() {
		window.location = BASE_URL+'404';
	});
}
function initToggleFBLikeBox() {
	var _fullBox = $('#onglet-facebook');
	var _likeBox = _fullBox.find('.like-box-mandchou');
	var _fullHeight = _likeBox.css('height');
	var _toggleButton = _fullBox.find('a.show-like-box');
	_toggleButton.show();
	hideBox();
	_toggleButton.toggle(
		function() {
			showBox();
		},
		function() {
			hideBox();
		}
	);
	function hideBox() {
		_fullBox.removeClass('open');
		_fullBox.addClass('closed');
		_toggleButton.find('span').html('?');
		_likeBox.stop();
		_likeBox.animate(
			{height: '0px'},
			300
		);
	}
	function showBox() {
		_fullBox.removeClass('closed');
		_fullBox.addClass('open');
		_toggleButton.find('span').html('×');
		_likeBox.stop();
		_likeBox.animate(
			{height: _fullHeight},
			300
		);
	}
}

function bindLink(_idZone) {
	var _zone = '';
	if (_idZone) {
		_zone = _idZone+' ';
	}
	var temp_href = '';
	var menu = $('#menu');
	var liens_menu = menu.find('a');
	var liens_galerie = $(_zone+'a.lien-galerie');
	var liens_page = $(_zone+'a.lien-page');
	var liens_home = $(_zone+'a.lien-home');
	var liens_work = $(_zone+'a.lien-work');
	var liens_illustration = $(_zone+'a.lien-illustration');
	var liens_voir = $(_zone+'#blockBottom a');
	liens_galerie.click(function() {
		if (!PAGE_IS_BUSY) {
			temp_href = $(this).attr('href');
			if(temp_href != BASE_URL+CURRENT_PAGE) {
				liens_menu.removeClass('actif');
				$(this).addClass('actif');
				loadGalerie(temp_href, true);
			}
		}
		return false;
	});
	liens_home.click(function() {
		if (!PAGE_IS_BUSY) {
			temp_href = $(this).attr('href');
			if(temp_href != BASE_URL+CURRENT_PAGE) {
				liens_menu.removeClass('actif');
				liens_home.addClass('actif');
				loadPage(temp_href, false, true);
				loadGalerie(temp_href);
			}
		}
		return false;
	});
	liens_page.click(function() {
		if (!PAGE_IS_BUSY) {
			temp_href = $(this).attr('href');
			if(temp_href != BASE_URL+CURRENT_PAGE) {
				liens_menu.removeClass('actif');
				$(this).addClass('actif');
				loadPage(temp_href, true, true);
			}
		}
		return false;
	});
	liens_work.click(function() {
		if (!PAGE_IS_BUSY) {
			temp_href = $(this).attr('href');
			if(temp_href != BASE_URL+CURRENT_PAGE) {
				liens_work.removeClass('actif');
				$(this).addClass('actif');
				loadPage(temp_href);
			}
		}
		return false;
	});
	liens_illustration.click(function() {
		if (!PAGE_IS_BUSY) {
			temp_href = $(this).attr('href');
			if (!$(this).hasClass('actif')) {
				liens_illustration.removeClass('actif');
				$(this).addClass('actif');
				loadIllustration(temp_href);
			}
		}
		return false;
	});
	liens_voir.bind('mouseover',function(){
		liens_voir.stop();
		liens_voir.animate({"backgroundPosition": "9px center",'backgroundColor':'#303030'},200);
	});
	liens_voir.bind('mouseleave',function(){
		liens_voir.stop();
		liens_voir.animate({"backgroundPosition": "4px center",'backgroundColor':'#000000'},200);
	});
}


function defineCurrentPage(_URL) {
	CURRENT_PAGE = _URL.replace(BASE_URL,'');
	if (CURRENT_PAGE == '') { CURRENT_PAGE = 'home'; }
	location.hash = CURRENT_PAGE;
}

function initVignettes() {
	_totalWi = $(window).width();
	totalElements = $('#table').find('a').size();
	totalMarge = baseMarge * totalElements;
	miniWI = Math.floor((_totalWi-Math.floor(maxWI*2.2))/totalElements)-baseMarge;
	if(miniWI>_miniWI) {
		miniWI=_miniWI;
	}
	var _table = $('#table');
	_table.find('img.label').css({width:miniWI+'px'});
	_table.find('img.thumb').css({width:miniWI+'px'});
	_table.find('img.title-1').css({width:miniWI+'px'});
	_table.find('img.title-2').css({width:miniWI+'px'});
	var _tableWi = _table.width();
	_table.stop();
	_table.css({marginLeft:'-'+Math.floor(_tableWi*0.5)+'px',left:'50%'});
	A = ((miniWI - maxWI) / (maxWI * reaction));
}


function activDock() {
	var firstTime = 0;
	var _timerDock = null;
	var _table = $('#table');
	var dock = _table.get(0);
	var td_tags = _table.find('td');
	var img_label = _table.find('img.label');
	var img_tags = _table.find('img.thumb');
	var img_title1 = _table.find('img.title-1');
	var img_title2 = _table.find('img.title-2');
	var currentIMG = null;
	var firstIMG = null;
	var lastIMG = null;
	_table.bind('mouseleave',function(){
		initVignettes();
		firstTime = 0;
	});
	_table.bind('mousemove', function (even) {
		x = even.clientX;
		x = even.pageX;
		x = x - dock.offsetLeft;
		//if (currentX < x - 10 || currentX > x + 10) {
		//if (currentX != x) {
		//if (currentX - tolerance >= x || currentX + tolerance <= x) {	
		currentX = x;
		//if(canOpen == true){fishEye()}
		fishEye();
		//}
	});
	
	function fishEye() {
		var totalWI = 0;
		if (prevX != x) {
			prevX = x;
			//for (i = 0; i < totalElements; i++) {
			for (i = 0; i < totalElements; i++) {
				var currentWi = parseInt(img_tags[i].style.width);
				var millieu = td_tags[i].offsetLeft + currentWi / 2;
				var delta = millieu - x;
				if (delta < 0) {
					delta = delta * -1;
				}
				coef = A * delta + maxWI +30 ;
				if (coef < miniWI) {
					coef = miniWI;
				} else if (coef > maxWI) {
					coef = maxWI;
				}
				thisPercent = parseInt(coef * 100 / maxWI);
				//borderBottomWi = parseInt(40 * thisPercent / 100);
				if(parseInt(img_tags[i].style.width)!=coef){
					if (img_label[i]) {
						img_label[i].style.width = coef + 'px';
					}
					img_tags[i].style.width = coef + 'px';
					img_title1[i].style.width = coef + 'px';
					img_title2[i].style.width = coef + 'px';
				}
				//img_tags[i].animate({width:coef + 'px'},200);
				totalWI = totalWI+coef+baseMarge;
			}
			dock.style.marginLeft = '-' + Math.floor(totalWI / 2) + 'px';
			//_table.stop();
		}
	}
}

function loadIllustration(_URL){
	PAGE_IS_BUSY = true;
	$('#contentInterne').prepend('<div id="tempIMG"><img src="'+_URL+'" id="TEMPIMAGE" /></div>');
	$('#TEMPIMAGE').load(function(){	
		$('#tempIMG').animate({paddingLeft:0,left:0},500,'easeOutCirc');
		var _timerSlideUmg = setTimeout(function(){
		$('#currentIMG').html($('#tempIMG').html());
		$('#tempIMG').remove();
		PAGE_IS_BUSY = false;
		},500);
	});
}

function load404() {
	PAGE_IS_BUSY = true;
	defineCurrentPage(BASE_URL+'404');
	var _newContent = '';
	
	fleches.masquer();
	
	$.post(BASE_URL+'404',{mainOnly: 1},function(data){
		_newContent = data;
		display404();
	});
	
	function display404() {
		PAGE_IS_BUSY = false;
		loadGalerie(BASE_URL);
		_gaq.push(['_trackPageview', '404']); // Traque la visite de la page pour Google Analytics
		_newContent = _newContent.replace('<title>','');
		var _contentArray = _newContent.split('</title>');
		var _newTitle = _contentArray[0];
		var _mainContent = _contentArray[1];
		document.title = _newTitle;
		$('#conteneur').html(_mainContent);
		bindLink('#conteneur');
		checkValue();
		
		$('#loaderCache').fadeOut(
			400, 
			function() {
				$('#loaderCache').remove();
			}
		);
	}
}

function loadPage(_URL, _noBottom, _noNextPrev){
	PAGE_IS_BUSY = true;
	defineCurrentPage(_URL);
	var _newContent = '';
	var _animationCompleted = false;
	
	if	(_noBottom) {
		$('#vignettes').stop();
		$('#vignettes').animate({bottom:'-200px'},400,function() {$('#vignettes').html('');});
	}
	
	fleches.masquer();
	
	$.post(_URL,{mainOnly: 1},function(data){
		_newContent = data;
		if (_animationCompleted) {
			displayNewPage();
		}
	});
	
	$('#content').prepend('<div id="loaderCache" style="display:none;"></div>');
	$('#loaderCache').fadeIn(
							400,
							function() {
								_animationCompleted = true; 
								if (_newContent != '') {
									displayNewPage();
								}
							});
	
	function displayNewPage() {
		PAGE_IS_BUSY = false;
		_gaq.push(['_trackPageview', CURRENT_PAGE]); // Traque la visite de la page pour Google Analytics
		_newContent = _newContent.replace('<title>','');
		var _contentArray = _newContent.split('</title>');
		var _newTitle = _contentArray[0];
		var _mainContent = _contentArray[1];
		document.title = _newTitle;
		$('#conteneur').html(_mainContent);
		bindLink('#conteneur');
		checkValue();
		
		if (!_noNextPrev) {
			fleches.definirLiens();
			fleches.afficher();
		}
		
		$('#loaderCache').fadeOut(
			400, 
			function() {
				$('#loaderCache').remove();
			}
		);
	}
}

function loadGalerie(_URL, _loadFirst){
	PAGE_IS_BUSY = true;
	var _newContent = '';
	var _animationCompleted = false;
	
	$.post(_URL,{bottomOnly: 1},function(data){
		_newContent = data;
		if (_animationCompleted) {
			displayNewGalerie();
		}
	});
	
	if ($('#vignettes').html() == '') {
		_animationCompleted = true;
		$('#vignettes').css('bottom','25px');
		$('#vignettes').addClass('LOADING');
	} else {
		$('#vignettes').stop();
		$('#vignettes').animate(
								{bottom:'-200px'},
								400,
								function() {
									_animationCompleted = true;
									if (_newContent != '') {
										displayNewGalerie();
									} else {
										$('#vignettes').html('');
										$('#vignettes').addClass('LOADING');
										$('#vignettes').css('bottom','25px');
									}
								});
	}

	function displayNewGalerie() {
		if ($('#vignettes').css('bottom') == '25px') {
			$('#vignettes').css('bottom','-200px');
		}
		$('#vignettes').html(_newContent);
		$('#vignettes').removeClass('LOADING');
		$('#vignettes').animate({bottom:'25px'},400);
		initVignettes();
		activDock();
		bindLink('#vignettes');
		if (_loadFirst) {
			var _premierProjet = $('#vignettes a:first');
			_premierProjet.addClass('actif');
			loadPage(_premierProjet.attr('href'));
		} else {
			PAGE_IS_BUSY = false;
		}
	}
}

function checkValue(){
	if ($('#form-partage').length == 1) {
		$('#form-partage').submit(function() {
			shareSite();
			return false;
		});
		$('#form-partage').append('<div id="shareLoad" style="display:none;">Chargement...</div>');
		$('#form-partage').append('<div id="erreur-partage" style="opacity:0;"></div>');
	}
	
	$('.checkValue').unbind();
	$('.checkValue').each(function(){
		var this_title = $(this).attr('title');
		if($(this).val()==this_title || $(this).val()==''){
			$(this).val(this_title);	$(this).addClass('champEmpty');
		}
		else
		{
			$(this).removeClass('champEmpty');	
		}
	});

	$('.checkValue').bind('focus',function(){
			var this_title = $(this).attr('title');
			$(this).removeClass('champEmpty');
		if($(this).val()==this_title){
			$(this).val('');	
		}
		
	});

	$('.checkValue').bind('blur',function(){
			var this_title = $(this).attr('title');
			if($(this).val()==''){
			$(this).val(this_title);	$(this).addClass('champEmpty');
		}
		else
		{
			$(this).removeClass('champEmpty');	
		}
	});
}

function flechesPrevNext() {
	$('#content').prepend('<a href="#" id="lien-precedent" rel="previous" style="width:0;"><span></span></a><a href="#" id="lien-suivant" rel="next" style="width:0;"><span></span></a>');
	this._flechePrecedent = $('#lien-precedent');
	this._flecheSuivant = $('#lien-suivant');
	this._fleches = $('#lien-precedent, #lien-suivant');
	this._fleches.hover(
		function(){
			if ($(this).width() == 17) {
				$(this).find('span').stop();
				$(this).find('span').animate({width:'15px'},220);
			}
		},
		function(){
				$(this).find('span').stop();
				$(this).find('span').animate({width:'0px'},200);
		}
	);
	
	this.afficher = afficherFleches;
	this.masquer = masquerFleches;
	this.definirLiens = definirLiensFleches;
	this.bind = bindFleches;
	
	function afficherFleches() {
		this._fleches.stop();
		this._flechePrecedent.animate({width:'17px'},300,'easeInCirc');
		this._flecheSuivant.animate({width:'17px'},300,'easeInCirc');
	}
	function masquerFleches() {
		this._fleches.stop();
		this._flechePrecedent.animate({width:'0px'},300,'easeInCirc');
		this._flecheSuivant.animate({width:'0px'},300,'easeInCirc');
	}
	function definirLiensFleches() {
		var _tdParent = $('#vignettes').find('a.actif').closest('td');
		if (_tdParent.prev().length == 1) {
			this._flechePrecedent.attr('href', _tdParent.prev().find('a').attr('href'));
		} else {
			this._flechePrecedent.attr('href', _tdParent.parent().find('td:last').find('a').attr('href'));
		}
		if (_tdParent.next().length == 1) {
			this._flecheSuivant.attr('href', _tdParent.next().find('a').attr('href'));
		} else {
			this._flecheSuivant.attr('href', _tdParent.parent().find('td:first').find('a').attr('href'));
		}
	}
	function bindFleches() {
		this._fleches.click(function() {
			if (!PAGE_IS_BUSY) {
				temp_href = $(this).attr('href');
				$('a.lien-work').removeClass('actif');
				$('a[href="'+temp_href+'"]').addClass('actif');
				loadPage(temp_href);
			}
			return false;
		});
	}
}



function checkMail(email) {
	var verif = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]{2,}[.][a-zA-Z.]{2,10}$/
	if (verif.exec(email) == null) {
		return false;
	} else {
		return true;
	}
} 


function errorNL(message){
	clearTimeout(_timer_errorNL);
	$('#alertNL').stop();
	$('#alertNL').css({opacity:1});
	$('#alertNL').html(message);
	_timer_errorNL = setTimeout(function(){$('#alertNL').animate({opacity:0},400);},1500);	
}


function inscriptionNL(){
	
	var new_mail = $('#nl-mail').val();
	
	if(checkMail(new_mail)==false){
		errorNL('<div class="erreur">Adresse invalide</div>');	
	} else {
		$.post(BASE_URL+INCLUDE_DIR+'gestionFormulaireNewsletter.php', { mail: $('#nl-mail').val(), ajax: 1 }, function(data) {
			if (data == 'ok') {
				errorNL('<div class="ok">Adresse enregistrée</div>');	
				$('#nl-mail').val($('#nl-mail').attr('title'));
			} else {
				errorNL('<div class="erreur">'+data+'</div>');
			}
		});
	}
	
	
}

function shareSite(){
	$('#shareLoad').show();
	$('#shareButton').hide();
	
	var _name = trim($('#shareName').val());
	var _mail = trim($('#shareMail').val());
	var _friends = trim($('#shareFriends').val());
	var _globError = 0;
	
	if(strlen(_name)<2 || _name==$('#shareName').attr('title')){
		_globError = 1;	
		$('#shareName').stop();
		$('#shareName').css({backgroundColor:'#F00'});
		$('#shareName').animate({backgroundColor:'#FFF'},800);
	}
	
	if(checkMail(_mail)==false){
		_globError = 1;
		$('#shareMail').stop();
		$('#shareMail').css({backgroundColor:'#F00'});
		$('#shareMail').animate({backgroundColor:'#FFF'},800);
	}
	
	if(strlen(_friends)<2 || _friends==$('#shareFriends').attr('title')){
		_globError = 1;
		$('#shareFriends').stop();
		$('#shareFriends').css({backgroundColor:'#F00'});
		$('#shareFriends').animate({backgroundColor:'#FFF'},800);
	} else {
		var _friendsError = false;
		var _line_delimiter=new RegExp('\n',"g");
		var _friends_array=_friends.split(_line_delimiter);
		for (_key in _friends_array) {
			if (checkMail(_friends_array[_key])==false) _friendsError = true;
		}
		if (_friendsError) {
			_globError = 1;
			$('#shareFriends').stop();
			$('#shareFriends').css({backgroundColor:'#F00'});
			$('#shareFriends').animate({backgroundColor:'#FFF'},800);
		}
	}
	
	
	if(_globError>0){
		$('#shareLoad').hide();	$('#shareButton').show();
	}
	else
	{
		$.post(BASE_URL+INCLUDE_DIR+'gestionFormulaireInvitation.php', { name: _name, mail: _mail, friends: _friends , ajax: 1 }, function(data) {
			if (data == 'ok') {
				errorShare('<div class="ok">Invitation(s) bien envoyé(s)</div>');
			} else {
				errorShare('<div class="erreur">Une erreur a empèchée l\'envoi</div>');
			}
			$('#shareLoad').hide();
			$('#shareButton').show();
		});
	}
	function errorShare(message){
		clearTimeout(_timer_errorNL);
		$('#erreur-partage').stop();
		$('#erreur-partage').css({opacity:1});
		$('#erreur-partage').html(message);
		_timer_errorNL = setTimeout(function(){$('#erreur-partage').animate({opacity:0},400);},1500);	
	}
}

/**-----------------------------**/
/**-Fonctions équivalente à PHP-**/
/**-----------------------------**/

function strlen (string) {
 
    var str = string+'';
    var i = 0, chr = '', lgth = 0;
 
    var getWholeChar = function (str, i) {
        var code = str.charCodeAt(i);
        var next = '', prev = '';
        if (0xD800 <= code && code <= 0xDBFF) { 
            if (str.length <= (i+1))  {
                throw 'High surrogate without following low surrogate';
            }
            next = str.charCodeAt(i+1);
            if (0xDC00 > next || next > 0xDFFF) {
                throw 'High surrogate without following low surrogate';
            }
            return str.charAt(i)+str.charAt(i+1);
        } else if (0xDC00 <= code && code <= 0xDFFF) {
            if (i === 0) {
                throw 'Low surrogate without preceding high surrogate';
            }
            prev = str.charCodeAt(i-1);
            if (0xD800 > prev || prev > 0xDBFF) { 
                throw 'Low surrogate without preceding high surrogate';
            }
            return false; 
        }
        return str.charAt(i);
    };
 
    for (i=0, lgth=0; i < str.length; i++) {
        if ((chr = getWholeChar(str, i)) === false) {
            continue;
        } 
        lgth++;
    }
    return lgth;
}	

function trim (myString){
	return myString.replace(/^\s+/g,'').replace(/\s+$/g,'');
}

function uniqid (prefix, more_entropy) {

    if (typeof prefix == 'undefined') {
        prefix = "";
    }
 
   var retId;
    var formatSeed = function (seed, reqWidth) {
        seed = parseInt(seed,10).toString(16); // to hex str
        if (reqWidth < seed.length) { // so long we split
            return seed.slice(seed.length - reqWidth);
        }
        if (reqWidth > seed.length) { // so short we pad
            return Array(1 + (reqWidth - seed.length)).join('0')+seed;
        }
        return seed;
    };
 
    // BEGIN REDUNDANT
    if (!this.php_js) {
        this.php_js = {};
    }
    // END REDUNDANT
    if (!this.php_js.uniqidSeed) { // init seed with big random int
        this.php_js.uniqidSeed = Math.floor(Math.random() * 0x75bcd15);
    }
    this.php_js.uniqidSeed++;
 
    retId  = prefix; // start with prefix, add current milliseconds hex string
    retId += formatSeed(parseInt(new Date().getTime()/1000,10),8);
    retId += formatSeed(this.php_js.uniqidSeed,5); // add seed hex string
 
    if (more_entropy) {
        // for more entropy we add a float lower to 10
        retId += (Math.random()*10).toFixed(8).toString();
   }

    return retId;
}
