$(document).ready(function() {
	
	// Ajout des classes first et last au elements suivants
	menuClasses ("#navThemes");
	menuClasses ("#navTypes");
	$('#meteo td:first').addClass('first');
	$('#liste h3:first').addClass('first');
	$('#tools a:last').addClass('last');
	
	// Arrondis des BlueBoxes
	$('.boxA, .boxB').prepend('<div class="tl"></div><div class="tr"></div>');
	$('#drigailles').prepend('<div class="bl"></div><div class="br"></div>');
	$('.boxE').prepend('<div class="tl"></div><div class="tr"></div><div class="bl"></div><div class="br"></div>');
	$('.boxF').prepend('<div class="tl"></div><div class="tr"></div><div class="bl"></div><div class="br"></div>');
	
	// Boites ouvrantes (fold)
	function openMyFold(me) {
		if ($(me).attr('class') == "opened") {return};
		$(me).parents(".box").find(".opened").removeClass('opened');
		$(me).parents(".box").find(".foldContent").slideUp("fast");
		$(me).parent().next().slideDown("fast");
		$(me).addClass('opened');
		var me = null;
	}

	$(".foldTitle").wrapInner('<a href="#"></a>');
	$('.box .foldContent').hide();
	$('.box').each(function() {
		$(this).find('.foldContent:first').show();
		$(this).find('.foldTitle:first a').addClass("opened");
		$(this).find('.fold:last').addClass("last");
	});

	$('.foldTitle a').click(function() {openMyFold(this);return false;});
	$('.foldTitle a').hover(function() {
		var me = $(this);
		autoFoldTimer = setTimeout(function(){openMyFold(me);}, 500);
	}, function() {
		clearTimeout(autoFoldTimer);
	});

	// Le CG : ouverture du fold à la Une
	$('#leCg .foldContent').hide();
	$('#leCg .foldTitle:first a').removeClass("opened");
	$('#leCg .foldOpenDefaut .foldTitle a').addClass("opened");
	$('#leCg .foldOpenDefaut .foldContent').show();
	
	// Pratique : ouverture du fold Mots Clés
	$('#pratique .foldContent').hide();
	$('#pratique .foldTitle:first a').removeClass("opened");
	$('#pratique .foldOpenDefaut .foldTitle a').addClass("opened");
	$('#pratique .foldOpenDefaut .foldContent').show();
	
	/* Boite à outils contenu */
	initTools();
   
	// Caroussel Actus Init
	if ($('#actus #liste ul').length) {
 		
		// Boutons de controle
		initCarousselControler();
 		
 		// JCarouselLite
 		$('#actus #liste').jCarouselLite({
			btnNext: "#actus .ctrl .next",
			btnPrev: "#actus .ctrl .prev",
			vertical: true,
			circular: true,
			visible:2,
			scroll: 2,
			speed: 4000
		});
 		
 		// Defilement auto
 		playActus();
 		
	};

	// Ajout des liens sur le blocs dossiers
	createLink(".dossier");
	createLink("#webcams .une");
	createLink("#galerie .une");
	createLink(".siteUne");

    /* TagCloud */
    initTagCloud();
    
}); 


// Caroussel Actus
function carousselActus() {
		$("#actus .ctrl a.next").click();
	}
function playActus() {
	intCarousselActus = setInterval(carousselActus, 3000);
}

// Caroussel Actus : Initialisation des controles
function initCarousselControler()
{
	$('#actus .ctrl').append('<a href="#" title="Actualités précédentes" class="prev"><img src="/global/img/pixel.gif" alt="&lt;" /></a>');
	$('#actus .ctrl').append('<a href="#" title="Actualités suivantes" class="next"><img src="/global/img/pixel.gif" alt="&gt;" /></a>');
	$('#actus .ctrl').append('<a href="#" title="Arrêter, reprendre le défilement" class="pause" id="actuControler"><img src="/global/img/pixel.gif" alt="-" /></a>');
	$('#actuControler').toggle(function() {
		clearInterval(intCarousselActus);
		$(this).addClass('play');
		$(this).removeClass('pause');
		return false;
	}, function() {
		playActus();
		$(this).addClass('pause');
		$(this).removeClass('play');
		return false;
	});
	
	// Pause et play sur le roll des titres actus
	$('#actus #liste').hover(function() {
		clearInterval(intCarousselActus);
		$("#actuControler").addClass('play');
		$("#actuControler").removeClass('pause');
	}, function() {
		playActus();
		$("#actuControler").addClass('pause');
		$("#actuControler").removeClass('play');
	});
	
}

/* Boite à outils contenu */
function initTools() {
	
	var tools = '<a href="#" class="ct1" title="Imprimer ce document"><img src="/global/img/pixel.gif" alt="Imprimer" /></a> ' +
				'<h2 class="hc">Outils de consultation</h2>' + 
    			'<a href="#" class="ct2" title="Envoyer cette page à un ami"><img src="/global/img/pixel.gif" alt="Envoyer à un ami" /></a>';
				//<a href="#" class="ct5" title="Recevoir des alertes par courriel"><img src="/global/img/pixel.gif" alt="Alertes par courriel" /></a>  
	$('#contentTools').prepend(tools);
	
	// Impression
	$('#contentTools a.ct1').click(function() {
		print();
		return false;
	});

	// Envoyer a un ami
	$('#envoyerAmi').wrap('<div id="outerEnvoyer"></div>')
	$('#outerEnvoyer').hide();
						
	$('#contentTools a.ct2').click(function() {

		$('#alertEmail').fadeOut();
		$('#outerAlert').slideUp();

		if ($('#outerEnvoyer').is(":visible")) {
			$('#envoyerAmi').fadeOut();
			$('#outerEnvoyer').slideUp();
		} else {
			$('#envoyerAmi .envoyerAmiForm').show();
			$('#envoyerAmi .envoyerAmiMessage').hide();
			$('#outerEnvoyer').slideDown();
			$('#envoyerAmi').fadeIn();
		};
		
		return false;
		
	});

	$('#envoyerAmi .close').click(function() {
		$('#envoyerAmi').fadeOut();
		$('#outerEnvoyer').slideUp();
		return false;
	});

}

/* TagCloud */
function initTagCloud() {

	var flashvars = { 
	    tcolor: "0x025587",
	    tcolor2: "0x0088d6",
	    hicolor: "0x025587",
	    mode: "tags",
	    distr: "true",
	    tspeed: "100",
	    tagcloud: '<tags>' + tagCloudTags + '</tags>'
	};
	var params = { wmode: "transparent" };
	var attributes = { id: "tagCloud" };
	swfobject.embedSWF("/global/swf/tagcloud.swf", "tagCloud", (window.location.pathname == '/' ? "280" : "120"), "180", "9.0.0", false, flashvars, params, attributes);
	
}

function createLink (selector) {
	// Ajout de liens sur le bloc container
	$(selector).click(function(){
		if ($(this).find("a").attr("target") == "_blank")
			window.open($(this).find("a").attr("href"));
		else
			window.location=$(this).find("a").attr("href");
		return false;
	});

	$(selector).hover(function() {
		$(this).toggleClass('jHover');
	}, function() {
		$(this).toggleClass('jHover');
	});
	
}

function menuClasses (elementID){
	// Cree les classes first et last sur les menus
	$(elementID + " li:first").addClass('first');
	$(elementID + " li:last").addClass('last');
}
function createLoader(where) {
	$(where).prepend('<div class="loading">Chargement en cours…</div>')
}

function URLEncode(unencodedValue )
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = unencodedValue;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};


var supersleight	= function() {
	
	var root = false;
	var applyPositioning = true;
	
	// Path to a transparent GIF image
	var shim			= '/global/img/x.gif';
	
	// RegExp to match above GIF image name
	var shim_pattern	= /x\.gif$/i;
	
	
	
	var fnLoadPngs = function() { 
		if (root) {
			root = document.getElementById(root);
		}else{
			root = document;
		}
		for (var i = root.all.length - 1, obj = null; (obj = root.all[i]); i--) {
			// background pngs
			if (obj.currentStyle.backgroundImage.match(/\.png/i) !== null) {
				bg_fnFixPng(obj);
			}
			// image elements
			if (obj.tagName=='IMG' && obj.src.match(/\.png$/i) !== null){
				el_fnFixPng(obj);
			}
			// apply position to 'active' elements
			if (applyPositioning && (obj.tagName=='A' || obj.tagName=='INPUT') && obj.style.position === ''){
				obj.style.position = 'relative';
			}
		}
	};

	var bg_fnFixPng = function(obj) {
		var mode = 'scale';
		var bg	= obj.currentStyle.backgroundImage;
		var src = bg.substring(5,bg.length-2);
		if (obj.currentStyle.backgroundRepeat == 'no-repeat') {
			mode = 'crop';
		}
		obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + mode + "')";
		obj.style.backgroundImage = 'url('+shim+')';
	};

	var el_fnFixPng = function(img) {
		var src = img.src;
		img.style.width = img.width + "px";
		img.style.height = img.height + "px";
		img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')";
		img.src = shim;
	};
	
	var addLoadEvent = function(func) {
		var oldonload = window.onload;
		if (typeof window.onload != 'function') {
			window.onload = func;
		} else {
			window.onload = function() {
				if (oldonload) {
					oldonload();
				}
				func();
			};
		}
	};
	
	return {
		init: function() { 
			addLoadEvent(fnLoadPngs);
		},
		
		limitTo: function(el) {
			root = el;
		},
		
		run: function() {
			fnLoadPngs();
		}
	};
}();
//supersleight.limitTo('mini_matin, mini_midi, mini_soir');

// limit to part of the page ... pass an ID to limitTo:
supersleight.limitTo('donneesPrevisions');
supersleight.init();
var supersleightMinisites	= function() {
	
	var root = false;
	var applyPositioning = true;
	
	// Path to a transparent GIF image
	var shim			= '/global/img/x.gif';
	
	// RegExp to match above GIF image name
	var shim_pattern	= /x\.gif$/i;
	
	
	
	var fnLoadPngs = function() { 
		if (root) {
			root = document.getElementById(root);
		}else{
			root = document;
		}
		for (var i = root.all.length - 1, obj = null; (obj = root.all[i]); i--) {
			// background pngs
			//if (obj.currentStyle.backgroundImage.match(/\.png/i) !== null) {
			//	bg_fnFixPng(obj);
			//}
			// image elements
			if (obj.tagName=='IMG' && obj.src.match(/\.png$/i) !== null){
				el_fnFixPng(obj);
			}
			// apply position to 'active' elements
			if (applyPositioning && (obj.tagName=='A' || obj.tagName=='INPUT') && obj.style.position === ''){
				obj.style.position = 'relative';
			}
		}
	};

	var bg_fnFixPng = function(obj) {
		var mode = 'scale';
		var bg	= obj.currentStyle.backgroundImage;
		var src = bg.substring(5,bg.length-2);
		if (obj.currentStyle.backgroundRepeat == 'no-repeat') {
			mode = 'crop';
		}
		obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + mode + "')";
		obj.style.backgroundImage = 'url('+shim+')';
	};

	var el_fnFixPng = function(img) {
		var src = img.src;
		img.style.width = img.width + "px";
		img.style.height = img.height + "px";
		img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')";
		img.src = shim;
	};
	
	var addLoadEvent = function(func) {
		var oldonload = window.onload;
		if (typeof window.onload != 'function') {
			window.onload = func;
		} else {
			window.onload = function() {
				if (oldonload) {
					oldonload();
				}
				func();
			};
		}
	};
	
	return {
		init: function() { 
			addLoadEvent(fnLoadPngs);
		},
		
		limitTo: function(el) {
			root = el;
		},
		
		run: function() {
			fnLoadPngs();
		}
	};
}();
//supersleight.limitTo('mini_matin, mini_midi, mini_soir');

// limit to part of the page ... pass an ID to limitTo:
supersleightMinisites.limitTo('minisites');
supersleightMinisites.init();

