function addLoadEvent(func) { // Manage Load Event
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}

function addResizeEvent(func) { // Manage Resize Event
    var oldonresize = window.onresize;
    if (typeof window.onresize != 'function') {
        window.onresize = func;
    } else {
        window.onresize = function() {
            oldonresize();
            func();
        }
    }
}

window.lastone = 0;

/* MAP */

var defaultMapId;

function showTeritory(number) {

	$("#Map .Background").find(".r" + number).animate({ opacity: 'show' }, 360);
	
	if (number != window.lastone) {
		$("#Map .Background").find(".r" + window.lastone).animate({ opacity: 'hide' }, 350);
		$("#Map .Content").animate({ opacity: 'hide' }, 250);
		var html = $.ajax({url: 'source/src-' + number + '.txt', async: false}).responseText;
        setTimeout(function(){
            $("#Map .Content").html(html);
            setTimeout(function(){
                $("#mapArea"+number).attr("href",$("#Map .Content a:first").attr("href"));
                $("#Map .Content").animate({ opacity: 'show' }, 250);
            }, 100);
		}, 350);
	}
	window.lastone = number;
	
}

function initMap() {

  if ($("#Map").size() < 1) { return; }

  // Hides teritorys' elements
  $("#Map .Background .ter").animate({ opacity: 'hide' }, 50);

  // Init teritory event handlers
  mapAreas = $("#Map").find("area");
  $(mapAreas).each(
    function() {
      var href = $(this).attr("href");
      numb = href.replace("#","");
      $(this).attr("id","mapArea"+numb);
      $(this).mouseover(function(){ var mapAreaId=$(this).attr("id"); number=mapAreaId.replace("mapArea",""); showTeritory(number); });
    }
  );
  $("#Map .Background").hover(function(){},function(){showTeritory(defaultMapId)});
  $("#Map .Background .ter").click(function() { curClass=$(this).attr("class"); number=curClass.replace("ter r",""); document.location.href=$("#mapArea"+number).attr("href"); });
 
 // Get and init Default Teritory
  defaultMapId = $("#Map .Content").attr("default");
  showTeritory(defaultMapId);

}


function compareheight(element) {
	var countofelements = $(element).length;
	for(i = 0; i < countofelements; i=i+2) {
		if($(element).eq(i).height() > $(element).eq(i+1).height())
			$(element).eq(i+1).css('height', $(element).eq(i).height() + 'px');
		else if($(element).eq(i).height() < $(element).eq(i+1).height())
			$(element).eq(i).css('height', $(element).eq(i+1).height() + 'px');
		else
			continue;	
	}
}

// sets up jCarousel with buttons for paging
$.fn.pagedCarousel = function (pagingElem, numberofvisible, resourcepath, options) {
	elem = $(this);
	pagingElem = $(pagingElem);
	
	var numberofelements = Math.ceil($("li", elem).length/numberofvisible);
	
	function drawButtons(on) {
		//pagingElem.html(' ');
		pagingElem.empty();
		if(numberofelements > 1)
			for(i = 0; i < numberofelements; i++) {
				if(i != on)
					pagingElem.append('<a href="#" title="'+(i*numberofvisible+1)+'"><img src="' + resourcepath + 'icon_jc-point-blank.gif" alt="Point" /></a>');
				else
					pagingElem.append('<a href="#" title="'+(i*numberofvisible+1)+'"><img src="' + resourcepath + 'icon_jc-point-full.gif" alt="Point" /></a>');
			}
	}
	
	function reDrawButton(whichone) {
		$("a", pagingElem).removeClass('active');
		$("a", pagingElem).eq(whichone).addClass('active').find("img").attr('src','img/icon_jc-point-full.gif');
		$("a", pagingElem).not('.active').find("img").attr('src','img/icon_jc-point-blank.gif');
	}
	
	drawButtons(0);
	
	function mycarousel_initCallback(carousel) {
		$("a", pagingElem).bind('click', function() {
			carousel.scroll(jQuery.jcarousel.intval(jQuery(this).attr('title')));
			reDrawButton((jQuery(this).attr('title')-1)/numberofvisible);
			return false;
		});
	};	
	
	function mycarousel_itemLastInCallback(carousel, item, idx, state) {
		var currentpage = Math.ceil(idx/numberofvisible)-1;
		reDrawButton(currentpage);
	};
	
	options = $.extend(options, {
		visible: numberofvisible,
		itemLastInCallback: mycarousel_itemLastInCallback,
		initCallback: mycarousel_initCallback
	});
	
	elem.jcarousel(options);
}

function sidePager(urlPrefix) {
	// handle block "Les organismes se présentent"

	$("#sidePager").each(function() {
		// loads content using ajax request and sets up a carousel
		function loadCarousel(n) {
			$.get(urlPrefix + n + ".txt", { }, function (data) {
				$("#sidePagerContent").empty().html(data);
				$("#sidePagerNav").empty();
				$('#sidePagerContent a').Tooltip({
					delay: 0,
					showURL: false,
					track: true
				});

				$("#sidePagerContent ul.cards").jcarousel({
					scroll: 1,
					animation: 'slow',
					initCallback: function (carousel) {
						// create buttons for carousel navigation
						var nav = $("#sidePagerNav");
						$("#sidePager ul.cards li").each(function() {
							nav.append("<a href='#sidePager'>" + $(this).attr("jcarouselindex") +  "</a>");
						});
						nav.find('a')
							.click(function() {
								carousel.scroll($.jcarousel.intval($(this).text()));
								return false;
							})
							.slice(0, 1).addClass("current");
						
						// dirty method for centering block with unknown width
						nav.css("marginLeft", -1 * nav.width() / 2);
					},
					itemLoadCallback: {
						onBeforeAnimation: function () { },
						onAfterAnimation: function (carousel) {
							// mark proper button as active
							$("#sidePagerNav a").removeClass("current");
							$("#sidePagerNav a").slice(carousel.last - 1, carousel.last).addClass("current");
						}
					}
				});		
			});
		}
		loadCarousel(1);
		$("#sidePager select").change(function() {
			loadCarousel($(this).val());
		});
	});
} // sidePager()

function divPager(urlPrefix) {
	// handle block "Les organismes se présentent"

	$("#sidePager").each(function() {
		// loads content using ajax request and sets up a carousel
		function loadCarousel(n) {
										 
			var data = $('#'+ urlPrefix + n).html();
			$("#sidePagerContent").empty().html(data);
			$("#sidePagerNav").empty();
			$('#sidePagerContent a').Tooltip({
				delay: 0,
				showURL: false,
				track: true
			});

			$("#sidePagerContent ul.cards").jcarousel({
				scroll: 1,
				animation: 'slow',
				initCallback: function (carousel) {
					// create buttons for carousel navigation
					var cards=$("#sidePagerContent ul.cards > li");
					var nav = $("#sidePagerNav");
					$("#sidePager ul.cards li").each(function() {
						nav.append("<a href='#sidePager'>" + $(this).attr("jcarouselindex") +  "</a>");
					});
					
						$(nav).find('a').click(function() {
							carousel.scroll($.jcarousel.intval($(this).text()));
							return false;
						})
						.slice(0, 1).addClass("current");

                    $(nav).addClass("onlyText");
                    var navLnks = $("#sidePagerNav").find('a');

					if ($(cards).size() > 10) {
                        $(navLnks[0]).addClass("bigger");
					    var j=1,limitPage=(navLnks).size();
					    for (var i=1; i<limitPage; i++) {
                          if (j != 4) {
                            $(navLnks[i]).addClass("offleft");
                            j++;
                            if (i == (limitPage-1)){
                              $("#sidePagerNav").append("<a href='javascript:void(0);' class='bigger disabled'>" + ((i-j+6)) +  "</a>");
                            }
                          }
                          else {
                            $(navLnks[i]).addClass("bigger");
                            j=0;
                          }
					    }
					}
					else {
                      $(nav).removeClass("onlyText");
                      $(navLnks).removeClass("bigger").removeClass("offleft");
					}
                    // dirty method for centering block with unknown width
                    nav.css("marginLeft", Math.round(-1 * nav.width() / 2));
					
				},
				itemLoadCallback: {
					onBeforeAnimation: function () { },
					onAfterAnimation: function (carousel) {
						// mark proper button as active
						var biggersLnks=$("#sidePagerNav a.bigger");
						$("#sidePagerNav a").removeClass("current");
						if ($(biggersLnks).size() > 0) { $("#sidePagerNav a").not(".bigger").addClass("offleft"); }
						curLink = $("#sidePagerNav a").slice(carousel.last - 1, carousel.last);
						$(curLink).removeClass("offleft").addClass("current");
						if (($(biggersLnks).size() > 0) && ($(curLink).not(".bigger"))) { $("#sidePagerNav").css("marginLeft", Math.round(-1 * $("#sidePagerNav").width() / 2)); }
					}
				}
			});	
			
			$(".logos div").hoverClass("sfhover");
			
		}
		loadCarousel(1);
		$("#sidePager select").change(function() {
			loadCarousel($(this).val());
		});			
		
	});
} // sidePager()

$(function($) {
	$(".slidingTips a").each(function() {
		var s = $(this).attr("title");
		$(this).attr("title", "");
		$(this).attr("tooltip", s);
	});	
	
	$(".slidingTips li").hover(		
		function(){ 
			$(".slidingTip").animate({ opacity: 'hide' }, 150);
			$(this).append('<div class="slidingTip">'+ $("a", this).attr('tooltip') +'</div>');
			$(".slidingTip", this).animate({ opacity: 'show' }, 350);
		}, 
		function(){
			setTimeout(function(){
				$(".slidingTip").animate({ opacity: 'hide' }, 350);
			}, 500);
		}
	);	
	
	// Rechercher fields
	$(".RechercheInput").bind("focus", function(){ if(this.value == "RECHERCHER") this.value = ""; });
	$(".RechercheInput").bind("blur", function(){ if(this.value == "") this.value = "RECHERCHER"; });
	
	// Newsletter fields
	$(".NewsletterInput").bind("focus", function(){ if(this.value == "Votre email") this.value = ""; });
	$(".NewsletterInput").bind("blur", function(){ if(this.value == "") this.value = "Votre email"; });

	// Bookmarker
	$("ul.tools li.fav a").click(function() {
		$.get("source/bookmarker.txt", {}, function (data) {
			$("body").append(data);
			var m = parseInt($("#bookmarker").css("margin-top"));
			$("#bookmarker")
				.css("margin-top", m + $(window).scrollTop())
				.show()
				.bgiframe()
			$("#bookmarker a.close").click(function() {
				$("#bookmarker").remove();
				return false;
			});
		});
		return false;
	});
	
	$("ul.tools li.mail a").click(function() {
		$.get("source/sendtofriend.txt", {}, function (data) {
			$("body").append(data);
			var m = parseInt($("#SendToFriend").css("margin-top"));
			$("#SendToFriend")
				.css("margin-top", m + $(window).scrollTop())
				.show()
				.bgiframe()
			$("#SendToFriend a.close").click(function() {							  
				$("#SendToFriend").remove();
				return false;
			});
		});
		return false;
	});
	
	$(".selectCheckBoxButton").hover(
		function(){ 
			$(".selectCheckBoxButton").click(function() {
				$(".selectCheckBox", this).show(333);
			});
		},
		function() {
			setTimeout(function(){
				$(".selectCheckBox", this).hide(333);
			}, 260);
		}
	);
	$("#dropMenu li ul").bgiframe();
});

function initNewsletter() {
	var newsletterResponseURL = $("#newsletterForm").attr("action") + "?";
	newsletterInputs = $("#newsletterForm").find("input");
	$(newsletterInputs).each( function(){ newsletterResponseURL += $(this).attr("name") + "=" + $(this).attr("value") + "&"; } );
	newsletterResponseURL = newsletterResponseURL.substr(0, newsletterResponseURL.length-2);
        // alert(newsletterResponseURL);
	// $.get("source/sendtofriend.txt", {}, function (data) {
	$.get(newsletterResponseURL, {}, function (data) {
			$("body").append(data);
			var m = parseInt($("#newsletterResult").css("margin-top"));
			$("#newsletterResult")
				.css("margin-top", m + $(window).scrollTop())
				.show()
				.bgiframe()
			$("#newsletterResult a.close").click(function() {							  
				$("#SendToFriend").remove();
				return false;
			});
		});
		return false;
}