/*
Permet de désactiver les champs d'une page dont la classe CSS contient "disabled"
*/
function ManageDisabledClass()
{
	//$(".disabled").attr("disabled","disabled");
		$(".disabled").attr("readonly","readonly");
}

function ManageBrForUdaPulldown()
{
	var MaxWidth = 0 ;
	$('.ui-dropdownchecklist-text').each(
		function()
		{
			var texte = $(this).text() ;
			if(texte.length > 50)
			{
				$(this).text('');
				var part1 = texte.substring(0,texte.substr(0,50).lastIndexOf(' '));
				var part2 = texte.substring(part1.length,texte.length) ;
				$(this).append(part1 + '<br>' + part2) ;
			}
			var divWidth = $(this).outerWidth() + $(this).prev().outerWidth() + 34;
			MaxWidth = MaxWidth < divWidth ? divWidth : MaxWidth ;
		}
	) ;
	$('.ui-dropdownchecklist-dropcontainer').each(
		function()
		{
			$(this).css({width: parseInt(MaxWidth) + "px"});
		}
	);
}

/*
Permet d'ajouter des commentaires à la facebook
*/
function CommentFBstyleAddLine(e)
{
	var currentHeight = e.height();
	var newHeight = currentHeight+15;
	e.height(newHeight);
}
/*
Permet de supprimer des commentaires à la facebook
*/
function CommentFBstyleRmLine(e)
{
	var currentHeight = e.height();
	
	if (currentHeight == $('#CommentDefaultHeight').val())
	return false;
	
	var newHeight = currentHeight-15;
	e.height(newHeight);
}

function CommentFBstyle()
{
	// Ajout de la taille par défaut
	$('.generic_comment .input-textarea').one("focus",function(){
   $(this).parent().append('<input type="hidden" id="CommentDefaultHeight" value="'+$(this).height()+'">');
	});
	
	
	$('.generic_comment .input-textarea').focus(
		function()
		{
			$(this).val('');
			CommentFBstyleAddLine($(this));
			$(this).next().next().show();
		}
	);
	 
		// Gestion de la touche entrée et backspace
	$(".generic_comment .input-textarea").bind("keydown", 
		function(e) 
		{
				// Assurer les compatibilités
				if(e){ // if the event object is present (NN only)
				e = e // var e = event
				}
				else {
				e = window.event // else e = winddow.event for IE
				}
				
				if(e.which){ // if there is syntax support for the property 'which' (NN only)
				var keycode = e.which // e.which is stored in variable "keycode"
				}
				else {
				var keycode = e.keyCode // otherwise for IE, var keycode stores e.keyCode syntax
				}
			
			  if (keycode == 13)
			  {
			  	CommentFBstyleAddLine($(this));
			  }
			  
			  if (keycode == 8)
			  {
			  	var lastChar = $(this).val().substr(($(this).val().length-1),1);
			  	
			  	if (lastChar.charCodeAt(0) == 10)
			  	CommentFBstyleRmLine($(this));
			  }
		});

		$('.generic_comment .input-textarea').blur(
			function()
			{
				$(this).attr('id','hideThis');

				setTimeout
				(
					function()
					{
						elem = $('#hideThis');
						
						elem.val(elem.text());
						elem.height($('#CommentDefaultHeight').val()+'px');
						elem.next().next().hide();
						
						elem.attr('id','');
					}
					,700
				);
				
				/*
				$(this).val($(this).text());
				$(this).height($('#CommentDefaultHeight').val()+'px');
				$(this).next().next().hide();
				*/
			}
		);
	
}

function blurIt(e)
{
	e.val(e.text());
	e.height($('#CommentDefaultHeight').val()+'px');
	e.next().next().hide();
}

// Extension JQUERY : next until ...
jQuery.fn.nextUntil = function(expr, include) { 
   var match = []; 
        include = include ? true : false 

        // We need to figure out which elements to push onto the array 
        this.each(function(){ 
                // Traverse through the sibling nodes 
                for( var i = this.nextSibling; i; i = i.nextSibling ) { 
                        // Make sure that we're only dealing with elements 
                        if ( i.nodeType != 1 ) continue; 

                        // Add it on to the stack if include is set 
                        if ( include ) { 
                                match.push( i ); 
                        } 
                        // If we find a match then we need to stop 
                        if ( jQuery.filter( expr, [i] ).length ) break; 

                        // Add it on to the stack if include is not set 
                        if (! include ) { 
                                match.push( i ); 
                        } 
                } 
        }); 
   return this.pushStack( match, arguments ); 
} 


function ManageAbstractGroupDescription()
{
	$('.search_listing_info span.hidden').show();
	$('.search_listing_info span.hidden').next('span').hide();
	$('.search_listing_info span.hidden a').click(
		function()
		{
			$(this).parent().next().show('fast');
			$(this).parent().hide();
		}
	);
}

// Fonction permettant de changer l'accès à une donnée par AJAX
function ManageAccessAJAX()
{
	// Transforme le select en liste cachée
	$('.ajaxAccess').append('<ul class="accessList"></ul>');
	
	$('.ajaxAccess select option').each(
		function()
		{
			$(this).parent().parent().find('.accessList').append('<li rel="'+$(this).val()+'">'+$(this).text()+'</li>');
			
			if ($(this).parent().val() == $(this).val())
			$(this).parent().parent().find('.accessList li:last').addClass('selected defaultValue');
		}
	);
	
	$('.ajaxAccess select').hide();
	$('.accessList').hide();
	
	// Affichage de la liste des acces
	$('.ajaxAccess img').toggle(
		function()
		{
			$('.accessList').hide();
			$(this).next().show('fast');
			$(this).trigger('mouseout');
		},
		function()
		{
			$(this).next().find('li.selected').removeClass('selected');
			$(this).next().find('li.defaultValue').addClass('selected');
			$(this).next().hide('fast');
		}
	);
	
	// Affichage de l'acces actuel
	$('.ajaxAccess img').hover(
		function()
		{
			if ($(this).next().css('display') == 'block')
			return false;
			
			var content = '<span class="currentVisibility">'+$(this).next().find('li.defaultValue').text()+'</span>';
			
			if (!$(this).prev().hasClass('currentVisibility'))
			$(this).before(content);
		},
		function()
		{
			$(this).parent().find('.currentVisibility').remove();
		}
	);
	
	
	$('.accessList li').hover(
		function()
		{
			$(this).parent().find('.selected').removeClass('selected');
			$(this).addClass('selected');
		}
	);
	
	// Appel AJAX
	$('.accessList li').not('.defaultValue').click(
		function()
		{
			metadataID = $(this).parent().parent().find('select').attr('name').match(/[0-9]+/);
			access = $(this).attr('rel');
			$(this).parent().prev().before('<span class="ajax_loader"></span>');
			
			$.ajax(
			 {
			   type: "POST",
			   url: $('#ajaxURL').val(),
			   data: "metadataID="+metadataID+"&access="+access,
			   success: function(feedback){
			   	if (feedback == 1)
			   	{	
			   		$('.ajax_loader').parent().find('.accessList li.defaultValue').removeClass('defaultValue');
						$('.ajax_loader').parent().find('.accessList li[rel='+access+']').addClass('defaultValue');
						$('.ajax_loader').parent().find('.accessList li.selected').removeClass('selected');
						$('.ajax_loader').parent().find('.accessList li.defaultValue').addClass('selected');
						$('.ajax_loader').parent().find('.accessList').prev().trigger('mouseover');
			   	}
			   	else
				  {
				   	$('.ajax_loader').parent().find('.accessList').prev().before(feedback);
				   	setTimeout(
				   		function()
				   		{
				   			$('.UDAerrorMessage').hide('fast');
				   		}
				   	,3000);
				  }
			   	$('.ajax_loader').remove();
			   }
			  }
			  );
		}
	);
	
	
	$('body').click(
		function()
		{
			$('.accessList:visible').prev().trigger('click');
			return true;
		}
	);
}

function LoginInfoBox()
{
	$('.login-textarea').focus(
		function()
		{
			$(".infoLogin[rel="+$(this).attr('name')+"]").show('fast');
		}
	);
	
	$('.login-textarea').blur(
		function()
		{
			$(".infoLogin[rel="+$(this).attr('name')+"]").hide('fast');
		}
	);
}

function AffichageActiveBanner()
{
	if ($("#active_banner").size() == 1)
	$("#layout_header").hide();
}

// Rend le champ input file regardable
/*
function NicerInputFile()
{
	$(".file_input input").filestyle({ image: "", imageheight : 27, imagewidth : 76, width : 250 });
}


// Fonction style input file
(function($){$.fn.filestyle=function(options){var settings={width:250};if(options){$.extend(settings,options);};return this.each(function(){var self=this;var wrapper=$("<div>").css({"width":settings.imagewidth+"px","height":settings.imageheight+"px","background-position":"right","display":"inline","position":"absolute","overflow":"hidden"});var filename=$('<input class="file">').addClass($(self).attr("class")).css({"display":"inline","width":settings.width+"px"});$(self).before(filename);$(self).wrap(wrapper);$(self).css({"position":"relative","height":settings.imageheight+"px","width":settings.width+"px","display":"inline","cursor":"pointer","opacity":"0.0"});if($.browser.mozilla){if(/Win/.test(navigator.platform)){$(self).css("margin-left","-142px");}else{$(self).css("margin-left","-168px");};}else{$(self).css("margin-left",settings.imagewidth-settings.width+"px");};$(self).bind("change",function(){filename.val($(self).val());});});};})(jQuery);
*/
// Fonction pour mettre un style sur les users avec qui on est en contact
function rmFriendCss()
{
	$(".rmFriend").each(
		function()
		{
			$(this).parents('.search_listing').addClass('inContact');
		}
	);
}


// Fonction pour gérer les catégories personnalisées dans les listes
function customCategories()
{
	// Ajouter une catégorie
	$('#new_category').click(
		function()
		{
			$('#createNewCategoryForm').show();
			$(this).hide();
			
			// Cancel button
			$('#createNewCategoryForm button:last').click(
				function()
				{
					$('#new_category').show();
					$('#createNewCategoryForm').hide();
					$('#createNewCategoryForm input').val('');
				}
			);
			
			// OK Button
			$('#createNewCategoryForm button:first').click(
				function()
				{
					$.ajax(
					{
					   type: "POST",
					   url: $('#ajaxURL').val(),
					   data: "type="+$('#dataType').val()+"&function=newCategory&name="+$('#createNewCategoryForm input').val(),
					   success: function(feedback){
							alert(feedback);
					   }
					}
					);
				
					$('#createNewCategoryForm button:last').trigger('click');
				}
			);
		}
	);
}

// Affichage des memebres d'une collection de contacts
function ManageFriendCollection()
{
	$('#friends_collections_accordian h2').click(function () {
		$(this).parent().find(".friends_picker").slideToggle("fast");
		//return false;
	});
}


$(document).ready(function(){
	ManageDisabledClass();
	CommentFBstyle();
	ManageAbstractGroupDescription();
	//initDatePicker();
	ManageAccessAJAX();
	LoginInfoBox();
	//AffichageActiveBanner();
	//NicerInputFile();
	rmFriendCss();
	setTimeout('ManageBrForUdaPulldown()', 1000);
	$(document).pngFix();
	customCategories();
	ManageFriendCollection();
});
