$(document).ready(function($){ 
	// fadeout flash messages on click
	//$('.cancel').click(function(){  $(this).parent().fadeOut(); return false;  });	
	$('.message').animate({opacity: 0.9}, 700).fadeIn();	
	// fade out good flash messages after 3 seconds
	$('.message').animate({opacity: 0.9}, 5000).fadeOut();
	$('.message').click(function (){	
		$('.message').stop();
		$('.message').animate({opacity: 0.9}, 200).fadeOut();
	});
	// bug ie
	var divalert = $('.ie6 #alert .message');
	var divalert2 = $('.ie6 #alert');
	if (divalert2.length !=0 && divalert.length == 0){
		$("#alert").css('display','none');
	}
	
	

	

	// Sortable #right #user_menu
	//
	$("#global-search-form").submit( function () {
		var S = $('input#searchbox').val();//.trim()split(' ');		
		window.location = '/search/'+S;
		return false;
	});
	/*$('#submit_search').click(function(){
		var S = $('#input_search').val();//.trim()split(' ');		
		window.location = '/search/'+S;
		return false;
	});*/
	
	//New Label
	//$('#user_labels .next_label img')
	$('#labelNew img').click(function(){
		$(this).hide();
		$('#newLabel').show();
		$('#newLabel input:first').focus();
		//$(this).next('input#newLabel').show().focus();
	});
	
	$.fn.hide_show = function(tohide, toshow){
		$('#newLabel').hide();
		$('#labelNew img').show();
		return false;
	};
	
	showLikersClick();
	//readMore();
});

var spinner = '<img src="/img/spinner.gif" style="vertical-align: text-bottom;" />';

function showFlashMessage(message){
	// TODO ajouter un type pour styliser et augmenter le sens (priorité) du message
	$('#alert').html('<div id="flashMessage" class="message">'+message+'</div>');

}

//déploie le visu des likers
function showLikersClick() {
	
	$('a[id^=likers_]').toggle(function(){
		var com_id = $(this).attr('id').split('_')[1];
		$('#likers_box_'+com_id).slideDown('normal', function(){
			
		});
		//$('#user_side_stats').slideDown('slow', function(){});
	},function(){
		var com_id = $(this).attr('id').split('_')[1];
		$('#likers_box_'+com_id).slideUp('normal', function(){ });
	});
}


var lkLnk1 = '<a onclick="';
var lkLnk2 = ');return false;" href="#';
var lkLnk3 = '">';
var unlikeLink = 'disLike';
var likeLink = 'iLike';
var nolikeLink = 'noLike';

// J'aime
function iLike(com_id){
	var unlikeTxt = $.trim($('#disLike_'+com_id).text());
	var likeTxt =  $.trim($('#iLike_'+com_id).text());
	var nolikeTxt = $.trim($('#'+nolikeLink+'_'+com_id).text());
	var open_plus = function (){$('#info_plus_'+com_id).css('display', 'block');};
	$.ajax({
		type: 'POST',
		url: '/loves/like.json',
		dataType: 'json',
		cache: false,
		async: true,
		data: {'data[com_id]':com_id},
		beforeSend: function() { $('#iLike_'+com_id).html(spinner); },
		success: function(data){
			
			if(data.rep == 1){//data.nb_like | data.nb_unlike
				open_plus();
				$('#nblike_'+com_id).html(data.nb_like);
				$('#disLike_'+com_id).html(lkLnk1 + unlikeLink +'('+com_id+ lkLnk2 + unlikeLink + lkLnk3 + unlikeTxt+'</a>');
				$('#'+nolikeLink+'_'+com_id).html(lkLnk1 + nolikeLink +'('+com_id+ lkLnk2 + nolikeLink + lkLnk3 + nolikeTxt+'</a>');
				$('#like_sentence_'+com_id).html(data.sentence);
				var sentence_disp = $('#likers_box_'+com_id).css('display');
				if(sentence_disp == 'none')
					$('#likers_box_'+com_id).slideDown('normal', function(){ });
			} else {//data.msg
				alert(data.msg);
			}
		},
		complete: function(data){ 		
			$('#iLike_'+com_id).html(likeTxt);
			$('#iLike_'+com_id).addClass("grey");			
		}
	});
	
}
// Je n'aime pas
function disLike(com_id){
	var unlikeTxt =  $.trim($('#disLike_'+com_id).text());
	var likeTxt =  $.trim($('#iLike_'+com_id).text());
	var nolikeTxt = $.trim($('#'+nolikeLink+'_'+com_id).text());
	$.ajax({
		type: 'POST',
		url: '/loves/unlike.json',
		dataType: 'json',
		cache: false,
		async: true,
		data: {'data[com_id]':com_id},
		beforeSend: function() { $('#disLike_'+com_id).html(spinner); },
		success: function(data){
			if(data.rep == 1){//data.nb_like | data.nb_unlike
				$('#nblike_'+com_id).html(data.nb_like);
				$('#iLike_'+com_id).html(lkLnk1 + likeLink +'('+com_id+ lkLnk2 + likeLink + lkLnk3 + likeTxt+'</a>');
				$('#'+nolikeLink+'_'+com_id).html(lkLnk1 + nolikeLink +'('+com_id+ lkLnk2 + nolikeLink + lkLnk3 + nolikeTxt+'</a>');
				$('#like_sentence_'+com_id).html(data.sentence);
			} else {//data.msg
				alert(data.msg);				
			}
		},
		complete: function(data){			
			$('#disLike_'+com_id).html(unlikeTxt);
			$('#disLike_'+com_id).addClass("grey");
		}
	});
}
// Je n'aime plus (Pas d'avis)
function noLike(com_id){
	var unlikeTxt =  $('#disLike_'+com_id).text();
	var likeTxt =  $('#iLike_'+com_id).text();
	var nolikeTxt = $('#'+nolikeLink+'_'+com_id).text();
	$.ajax({
		type: 'POST',
		url: '/loves/nolike.json',
		dataType: 'json',
		cache: false,
		async: true,
		data: {'data[com_id]':com_id},
		beforeSend: function() { $('#'+nolikeLink+'_'+com_id).html(spinner); },
		success: function(data){			
			if(data.rep == 1){//data.nb_like | data.nb_unlike
				$('#'+nolikeLink+'_'+com_id).html(nolikeTxt);
				$('#nblike_'+com_id).html(data.nb_like);
				$('#'+likeLink+'_'+com_id).html(lkLnk1 + likeLink +'('+com_id+ lkLnk2 + likeLink + lkLnk3 + likeTxt +'</a>');
				$('#'+unlikeLink+'_'+com_id).html(lkLnk1 + unlikeLink +'('+com_id+ lkLnk2 + unlikeLink + lkLnk3 + unlikeTxt +'</a>');
				$('#like_sentence_'+com_id).html(data.sentence);
			} else {//data.msg
				alert(data.msg);			
			}
		},
		complete: function(data){			
			$('#'+nolikeLink+'_'+com_id).addClass("grey").html(nolikeTxt);
		}
	});
}

function iFollow(tag_id){
	var beforeSubLnk = $('#subscribe_link_'+tag_id).html();
	$.ajax({
		type: 'POST',
		url: '/subscribes/follow.json',
		cache: false,
		dataType: 'json',
		data: {'data[tag_id]':tag_id},
		beforeSend: function() {
			$('#subscribe_link_'+tag_id).html(spinner);
		},
		success: function(data){
			if(data.rep == 1){
				$('#subscribe_link_'+tag_id).html('<a href="#" class="" onclick="unFollow('+data.tagId+');return false;">'+data.link+'</a>');
				if ($('span#nbr_membre')) {
					var nbr_membre = parseInt(data.nbFollowers + 0);
					$('span#nbr_membre').html(nbr_membre);
					if (nbr_membre > 1)
						$('span#word_membre').html(" membres");
					else
						$('span#word_membre').html(" membre");
				}
				var link_lbl = '<li id="subs_'+data.tagId+'" class="selected"><div>';
				link_lbl += '<img class="handle2" alt="" src="/img/handle.png"/>';
				link_lbl += '&nbsp;<a href="/'+data.tagKeyNom+'"><img class="subsImg" alt="" src="'+data.tagImg+'"/>&nbsp;';//key_nom
				link_lbl += data.tagNom+'</a></div></li>';
				$('#nbFoIng').html(data.nbFollowing);
				$('#left span#nbFoErs').html(data.nbFollowers);
				$('ul #lbl_subs_'+data.labelId+' li:first').before(link_lbl);
			} else {
				//FIXME appel de la fonction de gestion d'erreurs JSON
				alert(data.msg);
				$('#subscribe_link_'+tag_id).html(beforeSubLnk);
			}
		}
	});
}

function unFollow(tag_id){
	var beforeSubLnk = $('#subscribe_link_'+tag_id).html();
	$.ajax({
		type: 'POST',
		url: '/subscribes/delete.json',
		cache: false,
		dataType: 'json',
		data: {'data[tag_id]':tag_id},
		beforeSend: function() {
			$('#subscribe_link_'+tag_id).html(spinner);
		},
		success: function(data){
			if(data.rep == 1){
				$('#subscribe_link_'+tag_id).html('<a href="#" onclick="iFollow('+data.tag+');return false;" class="">'+data.link+'</a>');
				if ($('span#nbr_membre')) {
					var nbr_membre = parseInt(data.nbFollowers + 0);
					$('span#nbr_membre').html(nbr_membre);
					if (nbr_membre > 1)
						$('span#word_membre').html(" membres");
					else
						$('span#word_membre').html(" membre");
				}
				$('#user_labels li #subs_'+data.tag).remove();
				$('span#nbFoIng').html(data.nbFollowing);
				$('#left span#nbFoErs').html(data.nbFollowers);
			} else {
				//FIXME appel de la fonction de gestion d'erreurs JSON
				alert(data.msg);
				$('#subscribe_link_'+tag_id).html(beforeSubLnk);
			}
		}
	});
}



function iVote(com_id, vote){
	if (vote == 1) {
		var myurl = '/loves/like.json';
	}
	else {
		var myurl = '/loves/nolike.json';
	}
	$.ajax({
		type: 'POST',
		url: myurl,
		dataType: 'json',
		cache: false,
		async: true,
		data: {'data[com_id]':com_id},
		beforeSend: function() { 
			if (vote == 1) {
				$('#iVote_' + com_id).hide();
				$('#iNoVote_' + com_id).show();
				$('#span_vote_' + com_id).hide();
				$('#appreciate_vote_' + com_id).show();	
			}
			else {
				$('#iNoVote_' + com_id).hide();
				$('#iVote_' + com_id).show();
				$('#span_novote_' + com_id).hide();
				$('#appreciate_novote_' + com_id).show();
			}
			 
		},
		success: function(data){
			if (data.rep == 1) {
				if (vote == 1) {
					$('#appreciate_vote_' + com_id).hide();
					$('#span_vote_' + com_id).show();
					showFlashMessage("Votre vote a bien été pris en compte, merci.");
				}
				else {
					$('#appreciate_novote_' + com_id).hide();
					$('#span_novote_' + com_id).show();
					showFlashMessage("Votre vote a bien été supprimé.");
				}
				
				
			}
		}
	});
}	

$.fn.buildExpandCategories = function(size, strA, strB ){

  var $nombreItem = size ;
  
  var addListStyle = function(){
    if($(this).is(':visible')) 
      $(this).css('display','list-item'); 
  } 
  
  return this.each( function($i, $e) {
    
    $(this).find("li:gt("+ ($nombreItem-1) +")").hide();
    $(this).append('<a href="" class="categoryExpandHandle">' + strA + '</a>');
    
    $(this).children('a.categoryExpandHandle').click( function() {
      var $elmts = $(this).parent().find("li:gt("+ ($nombreItem-1) +")");
      $elmts.slideToggle('slow', addListStyle );
      
      if( $(this).html() == strA ){
        $(this).html( strB );
      }else{
        $(this).html( strA );
      }
      
      return false;
    });
    
  })
}