/*
	La barre de recherche à 2 statut :
	opened = ouverte au click (ferme lorsque l'utilisateur quite la recherche)
	forceOpen = ouverte a la recherche (ferme lorsque l'utilisateur choisi une image ds la galerie)

*/

function ouvrirRecherche(forceOpen){
	var el = $('#search');
	if ($(el).val() == 'Recherche')
		$(el).val('');

	if (!$('#search-bloc').hasClass('opened')){
		$('#search-bloc').css('background-image','url(' + tpl_url + '/images/background-search-opened.png)');
		$('#search-bloc').switchClass('search-bloc','search-bloc-opened',500);
		
		$('#arrow-top').animate({
			left: '+=268'
		  }, 500);
		$('#arrow-bottom').animate({
			left: '+=268'
		  }, 500);
		
		$('#search').animate({
			width: '+=234'
		  }, 500, function(){
			$('#fermer-recherche').show();
		  });
		$('#search-bloc').addClass('opened');
	}
	if (forceOpen){
		$('#search').addClass('forceOpen');
	}
}

function fermerRecherche(forceClose){
		var el = $('#search');
		
		if ($(el).hasClass('forceOpen') && !forceClose) return;
		
		if ($(el).val() == '')
			$(el).val('Recherche');
		if ($('#search-bloc').hasClass('opened')){
			$('#search-result').hide(0);
			$('#fermer-recherche').hide(0);
			if (!$('#arrow-top').hasClass('animate')){
				$('#arrow-top').addClass('animate');
				$('#arrow-top').animate({
					left: '-=268'
				  }, 500,
					function(){
						$('#arrow-top').removeClass('animate');
					}
				  );
			}
			if (!$('#arrow-bottom').hasClass('animate')){
				$('#arrow-bottom').addClass('animate');
				$('#arrow-bottom').animate({
					left: '-=268'
				  }, 500, 
					function(){
						$('#search-result').removeClass('animate');
						$('#arrow-bottom').removeClass('animate');
					}
				);
			}
			
			if (!$('#search').hasClass('animate')){
				$('#search').addClass('animate');
				$('#search').animate({
					width: '-=234'
				  }, 500,
				  function(){
						$('#search').removeClass('animate');
						$('#search').removeClass('animate');
					}
				  );
			}
			
			$('#search-bloc').switchClass('search-bloc-opened','search-bloc',500, function(){
				if ($('#search-bloc').hasClass('opened')){
					$(this).css('background-image','url(' + tpl_url + '/images/background-search.png)');
					$('#search-bloc').removeClass('opened');
					$('#search').removeClass('forceOpen');
					$('#search-result').show();
				}
			});
			
		}
}

function afficherGalerie(data){

	if (!data || data.length == 0){
		$('#search-result').html('Aucun r&eacute;sultat pour cette recherche');
		return;
	}
	
	var titre ='';
	
	//On nettoie avant de changer les images
	$('.resultat-image').unbind('hover');
	$('.resultat-image').unbind('click');
	
	$('#search-result').html('');
	
	var i = 0;
	jQuery.each(data, function(index, val){
		if (val.titre){
			titre = val.titre.replace("'","\'");
		}else{
			titre = $('#search').val();
		}
		
		var img = new Image();
		img.src = base_url + 'images/miniatures/' + val.fichier;
		img.id = 'img' + i;
		
		$('#search-result').append('<div class="resultat-image-container"><img class="resultat-image" fichier="' + val.fichier + '" src="' + base_url + 'images/miniatures/' + val.fichier + '" title="' +  titre + '" height="46" id="img' + i + '" w="" h="" /></div>');
		
		$(img).load(img.src,function(){
			var w;
			var h;
			//largeur et hauteur inferieure
			if (img.width < 556 && img.height < 430){
				if (img.width >= img.height){
					w = 556;
					h = '';
				}else{
					w = '';
					h = 430;
				}
			//largeur inferieure hauteur superieure
			}else if(img.height >= 430){
				w = '';
				h = 430;
			//hauteur inferieure largeur superieure
			}else if(img.width >= 556){
				w = 556;
				h = '';
			//egal
			}else{
				w = 556;
				h = 430;
			}
			
			$('#'+img.id).attr('w',w);
			$('#'+img.id).attr('h',h);
			
			
		});
		i++;
	});
	
	//Au survol
	$('.resultat-image').hover( 
		//Survol entrant
		function(){
			$('#autres-textes').css('display','none');
			if ($('#search-bloc').hasClass('opened') && !$('#search-result').hasClass('animate')){
				var tmpImg = new Image();
				tmpImg.src =  base_url + 'images/' + $(this).attr('fichier');
				$('#loader').show();
				$('#image-principale').fadeOut(200);
				$(tmpImg).load(tmpImg.src, function(){
					$('#loader').hide();
					$('#image-principale').attr('src', tmpImg.src);
					$('#image-principale').fadeIn(200);
				});
				if ($(this).attr('w') == '')
					$('#image-principale').removeAttr('width');
				else
					$('#image-principale').attr('width', $(this).attr('w'));
				if ($(this).attr('h') == '')
					$('#image-principale').removeAttr('height');
				else
					$('#image-principale').attr('height', $(this).attr('h'));
				$('#subtitle').html($(this).attr('title'));
			}
		},
		//Survol sortant
		function(){
			$('#autres-textes').css('display','none');
			if ($('#search-bloc').hasClass('opened') && !$('#search-result').hasClass('animate')){
				var img = new Image();
				
				$('#image-principale').attr('src', $('#image-principale').attr('last'));
				if ($('#image-principale').attr('w') == '')
					$('#image-principale').removeAttr('width');
				else
					$('#image-principale').attr('width', $('#image-principale').attr('w'));
				if ( $('#image-principale').attr('h') == '')
					$('#image-principale').removeAttr('height');
				else
					$('#image-principale').attr('height', $('#image-principale').attr('h'));
				
				$('#subtitle').html($('#image-principale').attr('title'));
			}
		}
	);
	
	//Affichage image
	$('.resultat-image').click( function(){
		$('#autres-textes').css('display','none');
		var img = new Image();
		if ($('.thejloupe').hasClass('active')){
			$('#loupe').attr('src', tpl_url + 'images/loupe.png');
			$('#image-principale').unbind('mousemove');
			$('#image-principale').unbind('mouseleave');
			$('#image-principale').unbind('mouseenter');
			$('.thejloupe').removeClass('active');
			$('.thejloupe').remove();
		}
		$('#search-result').addClass('animate');
		$('#image-principale').attr('last', $('#image-principale').attr('src'));
		$('#image-principale').attr('title', $(this).attr('title'));
		$('#subtitle').html($('#image-principale').attr('title'));
		
		var tmpImg = new Image();
		tmpImg.src =  base_url + 'images/' + $(this).attr('fichier');
		$('#loader').show();
		$('#image-principale').fadeOut(200);
		$(tmpImg).load(tmpImg.src, function(){
			$('#loader').hide();
			$('#image-principale').attr('src', tmpImg.src);
			$('#image-principale').fadeIn(200);
		});
		
		$('#sauver').attr('href', base_url + 'telechargement.php?chemin=images/&fichier=' + $(this).attr('fichier') );
		if($(this).attr('w') == '')
			$('#image-principale').removeAttr('width');
		else
			$('#image-principale').attr('width', $(this).attr('w'));
		if($(this).attr('w'))
			$('#image-principale').removeAttr('height');
		else
			$('#image-principale').attr('height', $(this).attr('h'));
		fermerRecherche(true);
		$('#search-result').removeClass('animate');
	});
	
	ouvrirRecherche();
}

$(window).load(function(){
	
	//Si on appuie sur une touche
	$('#search').keydown(function(event){
		//Si on appuite sur entrée alors on valide la recherche pour le moment
		//Ajouter la recherche autocomplété jquery
		if (event.keyCode == 13){
			$('#search-result').html('');
				
			$.ajax({
					url: "php/public/search.php",
					data: {
						keywords : $('#search').val()
					},
					dataType : 'json',
					method : 'post',
					success: function(data, textStatus, jqXHR){
						afficherGalerie(data);
					},
					error: function(jqXHR, textStatus, errorThrown){
						//A voir
					}
			});
			
		}
	});
	
	
	//click scroll bas
	$('#arrow-bottom').click(function(e){
		e.preventDefault();
		if ($('#search-result').css('top') == 'auto')
			$('#search-result').css('top', 0)
		if (!$('#search-result').hasClass('animate') && parseInt($('#search-result').css('top'), 10) - 315  > -$('#search-result').outerHeight()){
			$('#search-result').addClass('animate');
			if ($('#search-bloc').hasClass('opened'))
				ouvrirRecherche(true);
			$('#search-result').animate({'top':'-=315'}, function(){$('#search-result').removeClass('animate'); $('#search').removeClass('forceOpen'); });
		}
	});
	
	//click scroll haut
	$('#arrow-top').click(function(e){
		e.preventDefault();
		if ($('#search-result').css('top') == 'auto')
			$('#search-result').css('top', 0)
		if (!$('#search-result').hasClass('animate') && parseInt($('#search-result').css('top'), 10)  < 0){
			if ($('#search-bloc').hasClass('opened'))
				ouvrirRecherche(true);
			$('#search-result').addClass('animate');
			$('#search-result').animate({'top':'+=315'}, function(){$('#search-result').removeClass('animate'); $('#search').removeClass('forceOpen');});
		}
	});
	
	
	//Fermeture recherche
	$('#fermer-recherche').click(function(e){
		if (!$('#search-result').hasClass('animate')){
			fermerRecherche();
		}
	});
	
	//Ouverture recherche
	$('#search').click(function(){
		var tmp = $('#image-principale').attr('src');
		$('#image-bloc').html('<table width="556" height="430"><tr valign="center"><td>' +
			 '<img src="' + tmp + '" class="image" id="image-principale" alt="TITRE" title="" height="430"/>' +
		'</td></tr></table>' +
		'<img src="' + tpl_url + 'images/agrandir.png" id="agrandir" class="agrandir" />' +
		'<div class="subtitle" id="subtitle">' +
			'<strong>ACCUEIL</strong>' +
		'</div>' +
		'<div class="autres-textes" id="autres-textes"></div>');
		ouvrirRecherche();
	});
	
	//Autocomplete la recherche
	$( "#search" ).autocomplete({
		//Go check in database
		source: function( request, response ) {
			if (request.term == parseInt(request.term))
				response("");
			$.ajax({
				url: base_url + 'php/public/autocompletion-recherche.php',
				dataType: "json",			//Automatically parse data
				data: {
					arg: request.term
				},
				success: function(data) {
					if (data){
						if (data.statut && data.tags.length > 0){
							response(data.tags);
						}
					}
				},
				error : function(data){
					response("");
				}
			});
		},
		select:function(event,ui){
			$('#search-result').html('');
				
			$.ajax({
					url: "php/public/search.php",
					data: {
						keywords : ui.item.value
					},
					dataType : 'json',
					method : 'post',
					success: function(data, textStatus, jqXHR){
						afficherGalerie(data);
					},
					error: function(jqXHR, textStatus, errorThrown){
						//A voir
					}
			});
		}
	});
});
