/* ------------------------ VARIABLES GLOBALES ------------------------ */

var speedSlideUpFormComment = 300;
var speedSlideDownFormComment = 300;

var effectSlideUpFormComment = "easeInOutExpo";
var effectSlideDownFormComment = "easeInOutExpo";

var defaultValueForSearch = "Rechercher...";

var speedShowBoxLogin = 1500;
var effectShowBoxLogin = "easeOutExpo";

var speedHideBoxLogin = 800;
var effectHideBoxLogin = "easeInExpo";

var viewportHeight;
var boxLoginHeight;
var posTopOverlayVideo;

/* ------------------------ INIT ------------------------ */
$(document).ready(function(){
	// On init le PNGfix	
	$("#container").pngFix();
	
	// on initialise la dimension du header
	initHeaderWidth();
	
	// On init la police speciale avec Cufon
	initFont();
	
	// On determine les differentes dimensions
	initDimensions();
	
	// On init les evenements de page
	initPageEvents();
	
	// On init les evenements de l'overlay d'authentification
	initOverlayLogin();
	
	// On init les evenements lies aux commentaires
	initCommentEvent();
	
	// On init les evenements lies aux formulaires de recherche
	initSearchEvent();
	
	// On init les sous-menu
	initSubMenu();
});

/* ------------------------ EVENEMENTS ------------------------ */
/* initHeaderWidth
 * 
 * Initialisation de la largeur du header en fonction des éléments contenus
 * 
 */
function initHeaderWidth(){
	// largeur du bloc logo
	var widthBlocLogo = $('#logo').outerWidth();
	
	// largeur du bloc menu
	var widthBlocMenu = $('#menu').outerWidth();
	
	// largeur du bloc de droite
	var widthBlocRight = $('#headerRight').outerWidth();
	
	// on calcule la taille du header
	var headerWidth = widthBlocLogo+widthBlocMenu+widthBlocRight;
	
	// on donne cette valeur à la largeur du header
	$('#contentHeader').css('width',headerWidth);
}

/* initFont
 * 
 * Initialisation de la police speciale avec Cufon
 * 
 */
function initFont(){
	Cufon.replace(".cufon");
}

/* initDimensions
 * 
 * Initialisation des dimensions
 * 
 */
function initDimensions(){
	viewportHeight = $("BODY").height();
	windowHeight = $(window).height();
	
	boxLoginHeight = 146;
	
	posTopBoxLogin = (windowHeight - boxLoginHeight)/2;
}

/* initCommentEvent
 * 
 * Initialisation des evenements lies aux commentaires
 * 
 */
function initCommentEvent(){	
	$(".btnAjoutComment").click(showBoxAjoutComment);
	
	// on neutralise la soumission du formulaire
	$('#commentform').bind('submit', function(){
		return false;
	});
	
	$('#commentform').submit(function(){
		curForm = $(this);
		curAction = curForm.attr('action');
		curPseudo = curForm.find('[name=author]').val();
		curEmail = curForm.find('[name=email]').val();
		curUrl = curForm.find('[name=url]').val();
		curComment = curForm.find('[name=comment]').val();
		
		aPost = {
			'author':curPseudo,
			'email':curEmail,
			'url':curUrl,
			'comment':curComment,
			'submit':curForm.find("[name='submit']").val(),
			'comment_post_ID':curForm.find("[name='comment_post_ID']").val(),
			'comment_parent':curForm.find("[name='comment_parent']").val(),
			'_wp_unfiltered_html_comment':curForm.find("[name='_wp_unfiltered_html_comment']").val()
		};
	
		// On envoi la requÃªte
		$.ajax({
			url:curAction,
			data:aPost,
			dataType:'html',
			type:'POST',
			success:function(data){
				location.reload();
			},
			error:function(XMLHttpRequest, textStatus, errorThrown){
				showErrorOnCommentSubmit(curForm, XMLHttpRequest.responseText);
			}
		});
		
	});
}

function showErrorOnCommentSubmit(curForm, sError){

	// On recup le message d'erreur de wordpress
	indexOpeningP = sError.indexOf("<p>",0);
	indexClosingP = sError.indexOf("</p>",0);
	sError = sError.substring(indexOpeningP+3, indexClosingP);
	indexDP = sError.indexOf(":",0);
	sError = sError.substr(indexDP+2, sError.length);
	
	sMessageToShow = sError.substr(0,1).toUpperCase()+sError.substr(1,sError.length);
	
	setInfoBulleAtElement(sMessageToShow, curForm.find("[name='submit']"), 0, 21, false);
}

/* initPageEvents
 * 
 * Initialisation des evenements de page
 * 
 */
function initPageEvents(){
	$(".lineOption").hover(
      function(){	
	  	
		$(this).css({"background":"#c5c5c5"});
      }, 
      function(){
	  	$(this).css({"background":"none"});
      }
    );
	
	$(".linkLogin").hover(
      function(){	
	  	
		$(this).css({"color":"#006699"});
      }, 
      function(){
	  	$(this).css({"color":"#666666"});
      }
    );
}


/* initSearchEvent
 * 
 * Initialisation des evenements lies aux formulaires de recherche
 * 
 */
function initSearchEvent(){
	setMainSearch();
	setSearchSidebar();
	
}

/* initSubMenu
 * 
 * Initialisation des sous-menus
 * 
 */
function initSubMenu(){
	// si on click sur un menu contenant un sous-menu
	$(".menuWithSubMenu span").click(function(){
		// on récupère l'identifiant du sous-menu lié
		var curIdSubMenu = $(this).parents('.menuWithSubMenu').attr('rel');

		// si ce sous-menu est masqué
		if ($("#"+curIdSubMenu).css("display") == "none")
		{
			// on cache tous les sous-menu sauf celui-ci 
			hideAllSubMenuExceptThis(curIdSubMenu);
			// on montre le sous-menu
			showSubMenu(curIdSubMenu);
		}
		// sinon on le masque
		else
		{
			hideAllSubMenuExceptThis('none');
		}
	});
}


/* ------------------------ FONCTIONS ------------------------ */


function showSubMenu(idSubMenu){
	// on récupère la position et la largeur du menu contenant le sous-menu
	menuWithSubMenuPos = $(".btnMenu[rel="+idSubMenu+"]").offset();
	menuWithSubMenuWidth = $(".btnMenu[rel="+idSubMenu+"]").width();
	
	// On place le sous-menu
	$("#"+idSubMenu).css({
		left:menuWithSubMenuPos.left,
		top:menuWithSubMenuPos.top+25
	});
	
	$("#"+idSubMenu+" .flecheSubMenu").css({
		paddingLeft:menuWithSubMenuWidth/2-3.5
	});
	
	// On affiche le sous-menu
	$("#"+idSubMenu).slideDown({
			duration:500,
			easing:"easeOutExpo"});
	
}

function hideAllSubMenuExceptThis(idSubMenu){
	// On masque tous les sous-menus excepté celui en paramètre
	$(".subMenu[id!="+idSubMenu+"]").slideUp({
			duration:500,
			easing:"easeOutExpo"
	});
	
}

function setMainSearch(){
	// initialisation de la liste déroulante pour le type de recherche
	initListesDeroulantes();
	
	// clic sur le bouton go, on soumet le formulaire
	$('.inputSubmitSearch').click(function(){$('[name=form_recherche]').submit();});
	
	curSearchInput = $('[name=form_recherche] [name=recherche_communaute]');
	// si sur le submit, la recherche est vide ou à la valeur par défaut, on ne submit pas
	$('[name=form_recherche]').submit(function(){
		curValueToSearch = curSearchInput.val();
		if(curValueToSearch == '' || curValueToSearch == defaultValueForSearch)
		{
			
			setInfoBulleAtElement("Merci de saisir une recherche", curSearchInput, 0, curSearchInput.outerHeight(), false);
			
			return false;
		}
	});
	
	if($('.inputTextSearch').val() == '')
	{
		$('.inputTextSearch').val(defaultValueForSearch);
	}
	
	$('.inputTextSearch').focus(function() {  
        if (this.value == defaultValueForSearch){  
            this.value = '';  
        }  
        if(this.value != defaultValueForSearch){  
        	this.select();
        }  
    });
	
	$('.inputTextSearch').blur(function() {   
		if(this.value == ''){  
            this.value = defaultValueForSearch;  
        } 
	});
}

function setSearchSidebar(){
	if($('.inputTextSearchSidebar').val() == '')
	{
		$('.inputTextSearchSidebar').val(defaultValueForSearch);
	}
	$('.inputTextSearchSidebar').focus(function() {  
        if (this.value == defaultValueForSearch){  
            this.value = '';  
        }  
        if(this.value != defaultValueForSearch){  
             this.select();  
         }  
    }); 
	
	 /*$('.inputTextSearchSidebar').blur(function(e) {
		 this.value = defaultValueForSearch;
     });*/
}

function showBoxAjoutComment(){
	$(".boxAjoutComment").slideDown(speedSlideDownFormComment, effectSlideDownFormComment);
	hideBtnAjoutComment();
}

function hideBoxAjoutComment(){
	$(".boxAjoutComment").slideUp(speedSlideUpFormComment, effectSlideUpFormComment, function(){
		showBtnAjoutComment();
	});
}


function hideBtnAjoutComment(){
	$(".boxBtnAjoutComment").hide();
}

function showBtnAjoutComment(){
	$(".boxBtnAjoutComment").show();
}




///////////////////////////////////////////
$(function(){
	$('#postGallery .urlSlide').click(displayImage);
	
	$('#sidebarArrow').click(displaySidebar).hover(function(){
		$('#sidebarButton').stop().animate({'width':73});
	}).mouseout(function(){
		$('#sidebarButton').stop().animate({'width':0});
	});
	
	$('#sidebarButton').delay(2000).animate({'width':0});
});

function displayImage(){
	var $this = $(this);
	var opened = ($this.attr('class').split(' '))[1];
	var href = $this.attr('href');
	var mainImage = $('#mainImage');
	var iHeight = $this.find('img').attr('data-height');
	var iWidth = $this.find('img').attr('data-width');
	var iType = $this.attr('data-type');
	var content;
	
	if (opened !== 'opened'){
		$('#postSlider .opened').removeClass('opened');
		$this.addClass('opened');
		if (iType){
			if (iType == 'youtube') 				{content = '<iframe width="579" height="388" src="http://www.youtube.com/embed/'+href+'" frameborder="0" allowfullscreen style="position:relative;top:70px;left:120px;"></iframe>';}
			if (iType == 'dailymotion') 		{content = '<iframe frameborder="0" width="579" height="388" src="http://www.dailymotion.com/embed/video/xk0sxq"></iframe><br /><a href="http://www.dailymotion.com/video/'+href+'" target="_blank">';}
			if (iType == 'vimeo')					{content = '<iframe src="http://player.vimeo.com/video/'+href+'?title=0&amp;byline=0&amp;portrait=0" width="579" height="388" frameborder="0"></iframe>'}
		}
		else{
			content = '<img src="'+href+'" alt=""/>';
		}
		mainImage.html(content);
		var mWidth = $('#mainImage').width();
		var mHeight = $('#mainImage').height();
			console.log(iWidth);
		if (iWidth > mWidth){
			mainImage.find('img').width(mWidth).height(iHeight/iWidth * mWidth).css({'top':'auto'});
		}
		else{
			mainImage.find('img').width('auto').height('auto').css('top',mHeight / 2 - iHeight/2);
		}
		mainImage.find('img').attr('src',href).attr('data-height',iHeight).attr('data-width',iWidth);
	}
	
	
	mainImage.removeAttr('width').removeAttr('height');
		
	if (opened == 'opened'){
		$('#postSlider .opened').removeClass('opened');
		$this.addClass('opened');
		
		
	}
	
	
	
	return false;
}

function displaySidebar(){
	var $this = $(this);
	var image = $('#mainImage img');
	var video = $('#mainImage iframe');
	var iWidth = image.attr('width');
	var iHeight = image.attr('height');
	var mWidth = $('#mainImage').width();
	var mHeight = $('#mainImage').height();
	
	var dataWidth = image.attr('data-width');
	var dataHeight = image.attr('data-height');
	
	if ($this.attr('class') != 'opened'){
		$this.addClass('opened');
		$('#page').animate({'width':582});
		$('#sidebarContainer').animate({'width':195});
		$('#mainImage').animate({'width':579, 'height':388});
		$('.slideImage').animate({'width':144, 'height':103});
		$('#navigation').animate({'width':579});
		video.animate({'top':0, 'left':0});
		image.animate({'top':0});
		
		if (dataWidth > 579){
			image.animate({'width':579, 'height':dataHeight/dataWidth * 550});
		}
	}
	else{
		$this.removeClass('opened');
		$('#page').animate({'width':820});
		$('#sidebarContainer').animate({'width':0});
		
		$('#mainImage').animate({'width':807, 'height':550});
		$('.slideImage').animate({'width':201, 'height':145});
		$('#navigation').animate({'width':820});
		video.animate({'top':70, 'left':120});
		image.animate({'top':mHeight / 2 - iHeight/2});
		
		if (dataWidth > 819){
			image.animate({'width':819, 'height':dataHeight/dataWidth * 819});
		}
		
	}
}

