/* ****************************************************

	@file		  global.js
	@description  Comportements globaux
	@author		  remi (ixmedia.com)
	@version	  20090511

***************************************************** */
(function($){

	$(function() {

		/*=======================================================
		 * Liens externes
		 * ====================================================*/
		$('a').liensExternes({
			exclude : window.location.host
		});

		/*=======================================================
		 * Imprimer
		 * ====================================================*/
		 $('.imprimer a, a.imprimer').click(function() {
			window.print();
			return false;
		 });

		/*=======================================================
		 * Champ de recherche cliquable
		 * ====================================================*/

		$('#recherche input').rendreCliquable('.plein');
		$('#recherche button').click(function() {
			var $input = $('input[name=s]');
			if ($input.val() == 'Recherche par mot-clé') {
				$input.val('')
			}
		});
		
		/*=======================================================
		 * Mots-clés toggle
		 * ====================================================*/
		$('.keywords-toggle').each(function() {
			var lang = $('html').is('[lang=fr]') ? 'fr' : 'en';
			$(this).data('hide', ( lang == 'fr' ? 'Cacher' : 'Hide' ) );
			$(this).data('show', ( lang == 'fr' ? 'Afficher' : 'Show' ) );
		}).toggle(function() {
			$(this).find('span').html( $(this).data('hide') );
			$(this).find('strong').html('-');
			$(this).parent().next().slideToggle();
		}, function() {
			$(this).find('span').html( $(this).data('show') );
			$(this).find('strong').html('+');
			$(this).parent().next().slideToggle();
		});
		$('.keywords-toggle').parent().next().hide();

		/*=======================================================
		 * Onglets dans outil
		 * ====================================================*/
		$('body.outil .outil-contenu').hide().eq(0).show();
		$('body.outil .outil-entete .onglets a').click(function() {
			$('.outil-contenu').filter( $(this).attr('href') ).show().siblings('.outil-contenu').hide();
			$(this).parent().addUniqueClass('actif');
			return false;
		}).eq(0).parent().addUniqueClass('actif');

		/*=======================================================
		 * Formulaires
		 * ====================================================*/
		$('.total, .types').find('form input[type=submit]').hide().siblings('select').change(function() {
			var form = $(this).parents('form')[0];
			form.submit();
		});

		/*=======================================================
		 * Formulaire: Ajout d'un outil
		 * ====================================================*/

		if ($('.option_materiel').length) {
			$('.option_materiel').hide();
			function updateMateriel() {
				$('.option_materiel').hide();
				$('ul.materiel > li > input').filter(':checked').siblings('.option_materiel').show();
			}
			$('ul.materiel > li > input').click(updateMateriel);
			updateMateriel();

			$('ul.materiel ul li input:radio').click(function() {
				$(this).parent().parent().find('li label input:text').attr('disabled', 'disabled');
				if ($(this).is(':checked')) {
					$(this).siblings('label').find('input').attr('disabled', '');
				}
			});

			$('ul.materiel ul li input:radio').filter(':checked').siblings('label').find('input').attr('disabled', '');
			$('ul.materiel ul li input:text').focus(function(e) {
				e.preventDefault();
				e.stopPropagation();
				var f = $(this)[0];
				setTimeout(function(){
					f.focus();
				}, 300);
				return false;
			});
		 }

		/*=======================================================
		 * Accueil: début
		 * ====================================================*/

		 if ($('#debut').length) {
			$('#debut .liste h2').hide().parent().hide();
			$('#debut .onglets a').click(function() {
				if ($(this).parent().is('.active')) {
					$('#debut .liste').hide().siblings('.image').show();
					$(this).parent().removeClass('active')
				} else {
					$(this).parent().addClass('active').siblings('li').removeClass('active');
					$('#debut .liste').filter('.'+$(this).attr('href').replace(/#/g, '')).show().siblings('.liste, .image').hide();
				}
				return false;
			});

		 }


		/*=======================================================
		 * Formulaires en overlay
		 * ====================================================*/

		var ixOverlay = {
			topOffset: 60, url : '', titre : '', lang : 'fr',
			$o : null,
			init : function(selector) {
				// initialise le code HTML de l'overlay

				var self = this;
				self.lang = $('html').is('[lang=fr]') ? 'fr' : 'en';

				var close = (self.lang == 'fr') ? 'Fermer' : 'Close';
				$('body').append('<div id="overlay"><div class="formulaire"><div class="fermer"><a href="javascript://"><span>'+close+'</span></a></div><div class="titre"></div><div class="inner"></div></div><div class="shadow"></div></div>');

				$(selector).click(function() {
					ixOverlay.open(this);
					if ( $(this).parents('#nav').length ) {
						$('#overlay').addClass('recit');
					} else {
						$('#overlay').removeClass('recit');
					}
					return false;
				});

				self.$o = $('#overlay');
				self.$o.find('.fermer a').click(function() { self.hide(); });
				self.$o.find('.shadow').css('opacity', 0);

				$(document).keyup(function(e){
					keycode = (e == null) ? event.keyCode : e.which;
					if (keycode == 27 && self.$o.is(':visible')) { self.hide(); }
				});

			},
			open : function(lien) {
				// ouvre un formulaire

				var self = this;
				var metadata = $.metadata.get(lien);
				self.url = lien.href;
				self.titre = unescape(metadata.titre);
				self.$o.find('.titre').html(self.titre);
				self.load(false);

			},
			load : function(submit) {
				// load un url dans l'overlay

				var self = this;
				var data = (submit) ? $('#overlay form').formSerialize() + "&ajax=1" : "&ajax=1";
				self.show();

				$.ajax({
					type: 'POST',
					url : self.url,
					data : data,
					success : function (data) {
						if (parseInt(data) == 1) {
							window.location.reload();
							return true;
						}
						self.$o.find('.formulaire .inner').html(data)
						var $parent = self.$o.find('.formulaire');
						var newtop = $(window).scrollTop() + self.topOffset;

						// Au premier affichage du formulaire, on l'anime
						if (!submit) {
							self.$o.find('.formulaire').css('top', newtop+'px');
							$parent.css('opacity', 0).css('height', 'auto').show();
							var formHeight = $parent.height();
							$parent.css('height', '0px').css('opacity', 1).stop().animate({
								height: formHeight+'px'
							},{
								duration: 200,
								complete : function(){
									$(this).css('height', 'auto');
									var input = self.$o.find('.formulaire #usager');
									if (input.length > 0) {
										var input = input[0];
										input.focus();
									}
								}
							});
						} else {
							$('html, body').animate({
								scrollTop : $('.formulaire').offset().top-self.topOffset
							},{
								duration: 400
							});
							$parent.css('height', 'auto');
						}

						self.$o.find('form').submit(function(){
							self.load(true);
							return false;
						});

					}
				});
			},
			show : function() {
				// affiche l'overlay

				if ($.browser.msie && $.browser.version < 7) {
				$('object:visible, select:visible')
					.filter(function() {
						return $(this).parents('#overlay').length == 0
					})
					.css('visibility', 'hidden')
					.addClass('ixoverlay_torestore');
				}
				
				var self = this;
				self.$o.show();
				self.$o.find('.shadow').stop().animate({
					opacity: 0.8
				},{
					duration: 600,
					complete : function() {

					}
				});
			},
			hide : function() {
				// cache l'overlay

				var self = this;
				self.$o.find('.formulaire').stop().slideUp(400);
				self.$o.find('.shadow').stop().animate({
					opacity: 0
				},{
					duration: 600,
					complete : function() {
						self.$o.hide();
						$('.ixoverlay_torestore').css('visibility', 'visible').removeClass('ixoverlay_torestore');
					}
				});

			}
		}

		ixOverlay.init('.proposer a, .ami a, .connexion > a, a.connexion, #outils-entete a.courriel');

		/*=======================================================
		 * Agrégateur
		 * ====================================================*/

		$('#flux .item .action a').each(function() {
			var $item = $(this).parents('.item');
			var meta = $.metadata.get($item[0]);
			var output = '<input type="checkbox" id="action-'+meta.item_id+'" '+ ($item.is('.item-lu')?'checked="checked"':'') +' />';
			output += '<label for="action-'+meta.item_id+'">';
			output += '<strong>'+$(this).text()+'</strong>';
			output += '</label>';

			$(this).parent().append(output);
			$(this).remove();
		});

		$('#flux .item h2 a').click(function() {
			var $item = $(this).parents('.item');
			if ($item.is('.item-nonlu')) {
				$item.find('.action input').attr('checked', 'checked');
				flux_toggle_item($item);
			}
		});

		$('#flux .item .action input').click(function() {
			var $item = $(this).parents('.item');

			var meta = $.metadata.get($item[0]);

			var etat_old = $item.is('.item-lu') ? 'lu' : 'nonlu';
			var etat_new = etat_old == 'lu' ? 'nonlu' : 'lu';

			var url = "?"+etat_new+"s="+meta.item_id;
			$.ajax({
				type: 'GET',
				url : url,
				data : { 'ajax' : 1 },
				success : function(data) {
					flux_toggle_item($item);
				}
			});
		});

		function flux_toggle_item(item) {
			var etat_old = item.is('.item-lu') ? 'lu' : 'nonlu';
			var etat_new = etat_old == 'lu' ? 'nonlu' : 'lu';

			var opacity_new = (etat_new == 'lu') ? 0.3 : 1;
			var duration = (etat_new == 'lu') ? 300 : 1;
			
			item
			.stop()
			.css('background-color', '#FFF6CC')
			.animate(	{
							backgroundColor : 'rgb(255,255,255)'
						},{
							duration: 1500
						});

			var label = (etat_new == 'lu') ? 'agregateur_afficherFlux_marquerNonLu' : 'agregateur_afficherFlux_marquerLu';

			item.removeClass('item-'+etat_old);
			item.addClass('item-'+etat_new);
		}

		/*=======================================================
		 * Forum
		 * ====================================================*/

		
			$('.forum-categorie #forum tbody td').mouseover(function() {
				if ($.browser.msie && $.browser.version < 7) {
					$(this).parent().addClass('hover');
				}
			}).bind('mouseout', function() {
				if ($.browser.msie && $.browser.version < 7) {
					$(this).parent().attr('class', '' );
				}
			}).click(function() {
				window.location = $(this).parent().find('a').eq(0).attr('href');
			});

	});

})(jQuery);
