// Scripts fait maison spécifiques au thème proframa
$(document).ready(function(){
// Redimensionne les images trop larges
	$("img").each(function(){
		if($(this).width()>500) {
			if($(this).parent("a").attr("href")==$(this).attr("src")) {
				$(this).replaceWith('<img src="'+ $(this).attr("src") +'" alt="'+ $(this).attr("alt") +'" style="width:500px" />');
			} else {
				$(this).replaceWith('<a href="'+ $(this).attr("src") +'"><img src="'+ $(this).attr("src") +'" alt="'+ $(this).attr("alt") +'" style="width:500px" /></a>');
			}
		}
	});	
	$("img").load(function() { 
		if($(this).width()>500) {
			if($(this).parent("a").attr("href")==$(this).attr("src")) {
				$(this).replaceWith('<img src="'+ $(this).attr("src") +'" alt="'+ $(this).attr("alt") +'" style="width:500px" />');
			} else {
				$(this).replaceWith('<a href="'+ $(this).attr("src") +'"><img src="'+ $(this).attr("src") +'" alt="'+ $(this).attr("alt") +'" style="width:500px" /></a>');
			}
		}
	});	
//----------------------

// Flux de l'utilisateur
	var feed_url = "profile_feeds.php?url="+$("#my_feed > b > a").html();
	$("#my_feed").load(feed_url); // Chargement du flux de l'utilisateur
//----------------------

// Flux Identi.ca
	if ($("#my_idc > b > a").html()) { // user@status.net
		var idc_url = "profile_feeds.php?idc="+$("#my_idc > b > a").html();
	} else { // user
		if ($("#my_idc > b ").html()) {
		var idc_url = "profile_feeds.php?idc="+$("#my_idc > b ").html().replace("@", "");
		}
	}
	$("#my_idc").load(idc_url); // Chargement du flux Identi.ca
//----------------------

/* Flux Framactions (pas utilisé)
	var fa = $("#framactions").text().toLowerCase();
	var f_ids = "";
	f_ids += (fa.indexOf( 'annuaire' )!='-1' || fa.indexOf( 'asoft' )!='-1') ? "-150" : "";
	f_ids += (fa.indexOf( 'ablog' )!='-1') ? "-153" : "";
	f_ids += (fa.indexOf( 'abook' )!='-1') ? "-152" : "";
	f_ids += (fa.indexOf( 'acom' )!='-1') ? "-151" : "";
	f_ids += (fa.indexOf( 'advd' )!='-1') ? "-149" : "";
	f_ids += (fa.indexOf( 'apack' )!='-1') ? "-154" : "";
	f_ids += (fa.indexOf( 'atube' )!='-1') ? "-155" : "";
	f_ids += (fa.indexOf( 'atools' )!='-1') ? "-157" : "";
	f_ids += (fa.indexOf( 'agora' )!='-1') ? "-158" : "";
	f_ids += (fa.indexOf( 'akey' )!='-1') ? "-159" : "";
	f_ids = f_ids.substring(1, f_ids.length);
	$("#fa_feed").load("profile_feeds.php?url=http://forum.framasoft.org/profile_feeds.php?forums="+f_ids+"&ot=1");
//----------------------*/

/* Flux tout le forum (pas utilisé)
	$("#last_posts").load("profile_feeds.php?url=http://forum.framasoft.org/rss_trigger2.php");
//----------------------*/
/* Flux mes derniers posts (pas utilisé)
	var user = $("h2").text();
	$("#my_last_posts").load("profile_feeds.php?url=http://forum.framasoft.org/rss_trigger2.php?user="+user);
//----------------------*/

/* Flux actu Framasoft (pas utilisé)
	$("#fs_feed").load("profile_feeds.php?url=http://framapack.org/~framaflux/framanav_rss.php");
//----------------------*/

// Tooltip pour les liens site et wiki dans la description du forum
	$("img[src=http://forum.framasoft.org/styles/frama_pearl2/imageset/wiki.png]").parent("a").hover(
		function(){ 
			$(this).after($('<span id="tooltip" >'+this.href+'</span>'));
		}, 
		function () {
			$("span#tooltip").remove();
		}
	);
	$("img[src=http://forum.framasoft.org/styles/frama_pearl2/imageset/url.png]").parent("a").hover(
		function(){ 
			$(this).after($('<span id="tooltip" >'+this.href+'</span>'));
		}, 
		function () {
			$("span#tooltip").remove();
		}
	);
//----------------------

// Ajout d'une icone F et W devant les liens Framasoft et Wikipédia.
// Et alignement des smilies
	$("a[href*=framasoft.net/article]").prepend('<img src="http://forum.framasoft.org/images/icons/f.png" alt="" /> ');
	$("a[href*=wikipedia.org/wiki/]").prepend('<img src="http://forum.framasoft.org/images/icons/w.png" alt="" /> ');
	$("img[src*=./images/smilies/]").css('vertical-align', 'middle');
//----------------------

// Tooltip OpenID
	$('input[name="openid_url"]').focusin(function() {	
		$('#tooltip').fadeIn('slow'); 
	});
	$('input[name="openid_url"]').focusout(function() {
		$('#tooltip').fadeOut('slow');
	});
//----------------------

// Afficher/Masquer les colonnes de stats
	$(".show_stats:eq(1)").remove();
	$(".show_stats div").click(function () {
		$("dd.views").toggle(); 
		$("dd.posts").toggle();
		$("dd.topics").toggle();
		if ($('.show_stats div').attr('class')=='slantT') { 
			$('.show_stats div').attr('class', 'slantR'); 
			$('dl.icon dt').width('64%');
		} else {
			$('.show_stats div').attr('class', 'slantT'); 
			$('dl.icon dt').width('48%');
		};
	});
//----------------------

// Bascule Navigation / Modération
	$(".jumpindex .slantL").click(function () {
		$(".jumpbox").toggle();
	});
//----------------------

// Suppression de la barre de navigation UCP/MCP s'il n'y a qu'une seule entrée dans le menu.
	if ($("#navigation li").size()==1) { $("#navigation").remove();}
//----------------------

// Centre les user_icons selon leur nombre (1, 2 ou 3)
	switch ($('.user_icons:eq(0) li').size()) {
		case 1: $('.user_icons:eq(0) li').width('100%'); break;
		case 2: $('.user_icons:eq(0) li').width('50%'); break;
	}
	switch ($('.user_icons:eq(1) li').size()) {
		case 1: $('.user_icons:eq(1) li').width('100%'); break;
		case 2: $('.user_icons:eq(1) li').width('50%'); break;
	}
//----------------------

// Correctif sur jappix
function jm_update() {
	$("p:contains('Framasoft, Framabook, Framablog, Framakey, FramaDVD, Framapack...')").html('Le salon de Framasoft :<br /><a href="xmpp:framasoft@muc.jappix.com">framasoft@muc.jappix.com</a>');
	var doublons = $("a.jm_friend[data-nick$=_]");
	doublons.hide();
	$(".jm_counter").html($("a.jm_friend:not([data-nick$=_])").length);
	if ($("#jappix_popup").has("form:contains('framasoft@muc.jappix.com')").length==0) {
		$("form:contains('Veuillez entrer l'adresse du salon à rejoindre.')").prepend('Le salon de Framasoft est <a href="xmpp:framasoft@muc.jappix.com">framasoft@muc.jappix.com</a>, mais vous pouvez évidemment en taper un autre...<br />')
	}
}
var interval = window.setInterval(jm_update, 1000);

//----------------------
// Masquer la navbar

$('.e_top').after('<span class="e_mask"><a href="#" onclick="return false"></a></span>');
function maskbarRight() {
	if (top.location==self.document.location) { $.cookie('navbar', 'hidden', { expires: 365, path: '/', domain: '.'+document.domain.replace(/^(www|test)\./i, ""), secure: false });}
	$('.navbar').attr('id', 'navbar'); // Navbar passe en "position absolue" mobile comme l'étiquette
	$('.login,.jumpbox,.navbar .time,.navbar .big-buttons,.e_nav').hide(); // Vide le contenu de la navbar
	// Déplace la "maskbar" à droite, agrandit la page, déplace l'étiquette
	$('#page-body').css('margin-right', '0px');
	$('span.e_mask a').css('background-position', '-32px -16px');
	$('span.e_mask a').attr('title', 'Afficher le menu');
	//------------------
	$('.jumpbox,.login').css({
		'min-height':'80px',
		'-webkit-border-radius': '5px 0 0 5px', 
		'-moz-border-radius': '5px 0 0 5px', 
		'border-radius' : '5px 0 0 5px'
	});
	// Ajoute les liens nav et user
	$('.e_bottom').before('<span class="e_user"><a href="#" onclick="return false" title="Mes outils"></a></span>');
	$('.e_bottom').before('<span class="e_nav2"><a href="#" onclick="return false" title="Navigation"></a></span>');

	// Affiche/masque la jumbox et déplace l'étiquette
	$('.e_nav2').toggle( 
		function () {
			$('.etiquette').css('right', '250px');
			$('.jumpbox').show();
			$('.mod,.login,.e_user,.e_mask').hide();
			$('#navbar').css('top', $('.etiquette').css('top').replace('px', '')-10+'px');
		},
		function () {
			$('.jumpbox').hide();$('.e_user,.e_mask').show();
			$('.etiquette').css('right', '0px');
		}
	);
	// Affiche/masque le cadre utilisateur et déplace l'étiquette
	$('.e_user').toggle( 
		function () {
			$('.etiquette').css('right', '250px');
			$('.login').show();
			$('.jumpbox,.e_nav2,.e_mask').hide();
			$('#navbar').css('top', $('.etiquette').css('top').replace('px', '')-10+'px');
		},
		function () {
			$('.login').hide();
			$('.e_nav2,.e_mask').show();
			$('.etiquette').css('right', '0px');
		}
	);
	//----------------------
}

function maskbarLeft() {
	$.cookie('navbar', 'visible', { expires: 365, path: '/', domain: '.'+document.domain.replace(/^(www|test)\./i, ""), secure: false });
	$('.navbar').removeAttr('id'); // Navbar repasse en posistion relative
	$('.login,.jumpbox,.navbar .time,.navbar .big-buttons,.e_nav').show(); $('.mod').hide(); // On remet le contenu sauf le bloc de modération
	$('#page-body').css('margin-right', '255px'); // On réduit la page
	// Déplace la maskbar à gauche, réduit la page, déplace l'étiquette
	$('span.e_mask a').css('background-position', '-16px -16px');
	$('span.e_mask a').attr('title', 'Masquer le menu');
	//------------------
	$('.navbar').css('top', '0');
	$('.jumpbox,.login').css({
		'min-height' : '0px',
		'-webkit-border-radius': '5px', 
		'-moz-border-radius': '5px', 
		'border-radius' : '5px'
	});
	$('.e_user,.e_nav2').remove();
}

// *********** Mode iframe *************
	if (top.location!=self.document.location) {
		$("a[href^=http]").attr('target', '_blank'); // lien ouverts en onglet
		$("a[href^=ftp]").attr('target', '_blank');
		$("a[href*=forum.framasoft.org]").removeAttr("target"); // sauf liens internes
		
		$("#page-header").remove(); // supprime l'entête 
		$(".copyright").remove(); // supprime le copyright phpbb
		$("#jappix_mini").remove(); // supprime le tchat
		$("#donation").remove(); // supprime le bouton don
		$("#framanav").remove(); // supprime la framanav
		$("#who_is_online").remove(); // supprime le Qui est en ligne (dans les forums et sujets)
		$(".p_stats").remove(); // supprime les statistiques de la page profil
		$("#wrap").css({'margin-top':'20px', 'min-width':'400px'}); // corrige un bug et réduit la largeur minimale
		$('.e_top').after('<span class="e_search"><a href="./search.php" title="Recherche"></a></span>'); // ajoute un lien vers la recherche avancée
// Etiquette/Navbar suivent la souris
$('.etiquette').css('position', 'absolute');
$(document).mousemove(function(m){
	var e = $('.etiquette').offset();
	var n = $('#navbar').offset();
	var b = $('#bottom').offset();
	var eh = $('.etiquette').height();
	var nh = $('#navbar').height();
	if (n && m.pageY > 200) { 
		if($('#navbar').height() > 10) { // Navbar + Etiquette
			if (n.left-m.pageX > 40 || m.pageY < n.top-60 || m.pageY > n.top+nh+60) {
				$('#navbar').css('top', m.pageY-50+'px');
				$('.etiquette').css('top', m.pageY-38+'px');
			}
		} else { // Etiquette (grande)
			if (e.left-m.pageX > 40 || m.pageY < e.top-60 || m.pageY > e.top+eh+60) {
				$('.etiquette').css('top', m.pageY-58+'px');
			}
		}
	} else { // Etiquette (petite)
		if (m.pageY > 200 && (e.left-m.pageX > 20 || m.pageY < e.top-40 || m.pageY > e.top+eh+40)) {
			$('.etiquette').css('top', m.pageY-38+'px');
		}
	}
}); 
		maskbarRight(); // Masque la barre (sans cookie)
		$('.e_mask').remove(); // Supprime le bouton de Masquer/afficher la barre
		$('#page-body .big-buttons').clone().prependTo("#wrap");
//----------------------
// *********** Mode hors iframe *************
	} else {
		// Scroll animé sur liens haut/bas *hors mode iframe*
		$('.e_top').click(function(){
			var offset = $('#top').offset();
			$('html,body').animate({scrollTop: offset.top}, 1000);
		});
		$('.e_bottom').click(function(){
			var offset = $('#bottom').offset();
			$('html,body').animate({scrollTop: offset.top}, 1000);
		});
		$('.e_nav').click(function(){
			var offset = $('#jumpbox').offset();
			$('html,body').animate({scrollTop: offset.top}, 1000);
		});
		//----------------------

// Masque/Affiche la barre selon le contenu du cookie		
if ($.cookie('navbar')=="visible") {
	$('.e_mask').toggle( function () {maskbarRight();}, function () {maskbarLeft();});
	maskbarLeft();
} else if ($.cookie('navbar')=="hidden") {
	$('.e_mask').toggle( function () {maskbarLeft();}, function () {maskbarRight();});
	maskbarRight();
} else {
	$('.e_mask').toggle( function () {maskbarRight();}, function () {maskbarLeft();});
	$.cookie('navbar', 'visible', { expires: 365, path: '/', domain: '.'+document.domain.replace(/^(www|test)\./i, ""), secure: false });
}
//-----------------------

// Fancybox pour uploader des fichiers sur le wiki
		$("#join").fancybox({
				'width'				: 920,
				'height'			: 500,
				'autoScale'			: false,
				'transitionIn'		: 'none',
				'transitionOut'		: 'none',
				'type'				: 'iframe'
		});
//-----------------------
	}
//***************************************

// Mode mobile
function DetectMobile() {
	var uagent = navigator.userAgent.toLowerCase();
	var mobiles = ["ipad", "iphone", "ios", "opera mobi", "blackberry", "android", "iemobile", "symbian"];
	var detected = false;
	for(var i=0; i < mobiles.length; i++) {
		if (uagent.search(mobiles[i]) > -1) {
			detected = true;
		};
	}
	return detected;
}
if (DetectMobile()) {
	$('.etiquette').css('top', '100px');
}
//----------------------


});

// Zone de navigation (plugin jQuery)
ddaccordion.init({
	headerclass: "jumpheader", 
	contentclass: "jumpmenu", 
	revealtype: "click", 
	collapseprev: true, 
	defaultexpanded: [0], 
	onemustopen: false, 
	persiststate: true, 
	toggleclass: ["", "selected"]
});
//----------------------

/* Plugin embedVanilla, fichier local.js avec quelques modifs :
 * ajout de messages à envoyer pour rendre les liens "jumpbox", "top" et "bottom" actifs
 * (sur le modèle des popups de vanilla )
 */
$(function() {
   if (typeof(gdn) == "undefined") {
      gdn = {};
      gdn.definition = function() {
         return '';
      }
   }
      
   var currentHeight = null,
      minHeight = 400,
      remotePostMessage = null,
      inIframe = top !== self,
      inDashboard = gdn.definition('InDashboard', '') != '',
      embedDashboard = gdn.definition('EmbedDashboard', '') != '',
      remoteUrl = gdn.definition('RemoteUrl', ''),
      forceRemoteUrl = gdn.definition('ForceRemoteUrl', '') != '',
      webroot = gdn.definition('WebRoot'),
      pathroot = gdn.definition('UrlFormat').replace('/{Path}', '').replace('{Path}', '');
      
   if (inIframe) {
      if ("postMessage" in parent) {
         remotePostMessage = function(message, target) {
            return parent.postMessage(message, target);
         }
         setLocation = function(newLocation) {
            parent.window.frames[0].location.replace(newLocation);
         }
      } else {
         var messages = [];
   
         messageUrl = function(message) {
            var id = Math.floor(Math.random() * 100000);
            if (remoteUrl.substr(-1))
               remoteUrl += '/';
               
            return remoteUrl + "/poll.html#poll:" + id + ":" + message;
         }
        
         remotePostMessage = function(message, target) {
            messages.push(message);
         }
        
         setLocation = function(newLocation) {
            if (messages.length == 0)
               parent.window.frames[0].location.replace(newLocation);
            else {
               setTimeout(function(){
                  setLocation(newLocation);
               },500);
            }
         }
         
         setMessage = function() {
            if (messages.length == 0)
               return;
            
            var message = messages.splice(0, 1)[0];
            document.getElementById('messageFrame').src = messageUrl(message);
         }
           
         $(function() {
            var body = document.getElementsByTagName("body")[0],
               messageIframe = document.createElement("iframe");
       
            messageIframe.id = "messageFrame";
            messageIframe.name = "messageFrame";
            messageIframe.src = messageUrl('');
            messageIframe.style.display = "none";
            body.appendChild(messageIframe);
            setMessage();
            setInterval(setMessage, 300);
         });
      }
   }

   // If not embedded and we should be, redirect to the embedded version.
   if (!inIframe && forceRemoteUrl && remoteUrl != '') {
      var path = document.location.toString().substr(webroot.length);
      var hashIndex = path.indexOf('#');
      if (hashIndex > -1)
         path = path.substr(0, hashIndex);
      
      document.location = remoteUrl + '#' + path;
   } else if (inIframe && inDashboard && !embedDashboard) {
      remotePostMessage('unembed', '*');
   }

   // hijack all anchors to see if they should go to "top" or be within the embed (ie. are they in framagora or not?)
   if (inIframe) {
      setHeight = function() {
         var newHeight = document.body.offsetHeight;
         if (newHeight != currentHeight) {
            currentHeight = newHeight;
            if (currentHeight < minHeight)
               currentHeight = minHeight;
               
            remotePostMessage('height:'+currentHeight, '*');
         }
      }
   
      setHeight();
      setInterval(setHeight, 300);
    
      $('a').live('click', function() {
         var href = $(this).attr('href'),
            isHttp = href.substr(0, 7) == 'http://' || href.substr(0,8) == 'https://';
                
         if (isHttp && href.substr(0, webroot.length) != webroot) {
            $(this).attr('target', '_blank');
         } else {
            // Strip the path from the root folder of the app
            var path = isHttp ? href.substr(webroot.length) : href.substr(pathroot.length);
            var hashIndex = path.indexOf('#');
            var hash = '';
            if (hashIndex > -1) {
               hash = path.substr(hashIndex);
               path = path.substr(0, hashIndex);
            }
            
            if (path != '')
               remotePostMessage('location:' + path, '*');
               
            // setLocation(pathroot + path + hash);
            // return false;
         }
      });
      
      // Simulate a page unload when popups are opened (so they are scrolled into view).
      $('body').bind('popupReveal', function() {
         remotePostMessage('scrollto:' + $('div.Popup').offset().top, '*');
      });
    
		$('.e_top').click(function(){
			var offset = $('#top').offset();
			remotePostMessage('scrollto:' + offset.top, '*');
		});
		$('.e_bottom').click(function(){
			var offset = $('#bottom').offset();
			remotePostMessage('scrollto:' + offset.top, '*');
		});
      	$('.e_nav').click(function(){
			var offset = $('#jumpbox').offset();
			remotePostMessage('scrollto:' + offset.top, '*');
		});

      $(window).unload(function() { remotePostMessage('unload', '*'); });
   }
});


