var ltie7 = ($.browser.msie && $.browser.version <= 7);

$(function(){
		$.ifixpng('/extension/novactive/design/novactive/images/pixel.gif');
		$('img[src$=.png]').ifixpng();

		if (ltie7) {
			$('img[usemap]').css('border','none');
			$('input[type="radio"], input[type="checkbox"], input[type="file"]').css('border','none');
		}

		evitement.init();
		vertical_align_middle.init();
		survol_illust.init();
		gestionMenuTop.init();
		gestionMenuSideBar.init();
		gestionCarouselMetiers.init();
		gestionCarouselMetiersPopup.init();
	 	gestionCarouselReferences.init();
		homeGestionClients.init();
		BlocTabs.init();

		if ($('ul#roundabout_bloc').children().size() > 0) {RoundaboutPush.init();}

		$('#plan_du_site li.item_titre').adjustSize({periode: 3});

		$('ul#sous_rubriques li a').not('.on').hover(
			function(){$(this).addClass('on');},
			function(){$(this).removeClass('on');}
		);

		$('#carousel_page_references').jcarousel({scroll: 1});

		$('ul#menu .sous_menu li:last-child').css('border-bottom','none');

		$('#form_newsletter, #form_newsletter_full').submit(function() {
			$(".message").load("/newsletter/register_subscription/1",
				{'StoreButton': true,
					'Email': $('#subscriptionEmail').val(),
					'Firstname': $('#Firstname').val(),
					'Name': $('#Name').val(), 'OutputFormat[]': $('#OutputFormat').val(), 'ajax': '1'},
				function(){
					$(".message p, .message-warning").fadeOut(10000);
				}
			);

			return false;
		});

		$('#subscriptionEmail, #unSubscriptionEmail').click(function(){$(this).val('')});

		$('#unsubscribe').submit(function() {
			$(".messageUnsubscribe").load(
				"/newsletter/unsubscribe",
				{'StoreButton': true, 'Email': $('#unSubscriptionEmail').val()},
				function(){
					$('.message-warning p, .message-warning .error').fadeOut(10000);
				}
			);
			return false;

		});

});

/* = EVITEMENT */
var evitement = function(){
	function _init(){
		var bloc = $('#liensEvitement');

		$('a', bloc).focus(function(){
			bloc.animate({
				top: '0'
			});
		});

	}
	return {
		init:_init
	}
}();

/* =ROUNDABOUTPUSH */
var RoundaboutPush = function() {
	function _init() {
		var homeItemsRoundabout = $('#roundabout_bloc .item');
		homeItemsRoundabout.each(function(){
			var e = $(this);
			var img = e.find('img');
			var imgHeight = parseInt(img.height());
			var imgWidth = parseInt(img.width());
			if(imgWidth >= imgHeight){
				e.find('img').css('width', '100%');
			}
			else {e.find('img').css('height', '100%');}
		});
		var interval;
		var interval2;

		$('ul#roundabout_bloc').roundabout({
				reflect: true,
				minOpacity: 1.0,
				duration: 1000
		});
		$('ul#roundabout_bloc').hover(
			 function() {
				clearInterval(interval);
			 },
			 function() {
				interval = startAutoPlay('roundabout_bloc', 850);
			 }
		 );
		interval = startAutoPlay('roundabout_bloc', 850);
	}
	function startAutoPlay(block, duration) {
		return setInterval(function() {
			$('ul#'+block).roundabout_animateToNextChild();
		},duration);
	}
	return {init:_init};
}();

/* =BLOCTABS */
var BlocTabs = function(){
	function _init(){
		$("ul.tabs").tabs("div.panes_inner > div",{tabs:'li',current: 'item_actif'});
	}
	return {init:_init};
}();

$(window).load(function(){
	equipe.init();
});

/* =VERTICAL_ALIGN_MIDDLE */
var vertical_align_middle = function() {
	function _init() {
		$(".va_middle").each(function(){
			var Hself = $(this).height();
			var Hparent = $(this).parent().height();
			var pad = (Hparent - Hself)/2;
			$(this).parent().css({'padding-top':pad+"px", 'height': (Hparent - pad)+"px"});
		});
	}
	return {init:_init};
}();

/* =SURVOL_ILLUST */
var survol_illust = function() {
	function _init() {
		$("a.illustration").hover(
			function(){
			    $(this).find('.intro_illus').css({"display": "block"});
			    $(this).find(".content_box").animate({"top": "0px"}, "fast");
			},
			function(){
			    $(this).find('.intro_illus').css({"display": "none"});
			    $(this).find(".content_box").animate({"top": "137px"}, "fast");
			}
		);
	}
	return {init:_init};
}();

var equipe = function() {

	function _init() {
//		$('#liste_avatars > ul').slideDown();
//		ola.init();

                $('#liste_avatars > ul').show();
		$('#liste_avatars li').adjustSize({periode: 3});

		$('#liste_avatars li.item_avatar').hover(function(){
			$(this).css('z-index','300').children('.image').hide();
			$(this).children('.image_on').show();
		}, function(){
			$(this).css('z-index','0').children('.image').show();
			$(this).children('.image_on').hide();
		});
	}

	var ola = function () {
		var liste, items, nbItems;
		function init () {
			liste = $('#liste_avatars > ul');
			items = $('.item_avatar', liste);

			var nbItems = items.size();
			var j=0;
			for (var i=0;i<=nbItems;i++){
				if(ltie7) {
					var t=setTimeout("$('#liste_avatars li').eq("+i+").css('z-index','200').children('.image_on').animate({'height': 'toggle'}).animate({'height': 'toggle'});",j);
				} else {
					var t=setTimeout("$('#liste_avatars li').eq("+i+").children('.image_on').animate({'height': 'toggle'}).animate({'height': 'toggle'});",j);
				}
				j=j+50;
			}
		}

		return {init:init};
	}();

	return {init:_init};
}();

// initilisation de caroussel dans le thickbox (appel de la fonction dans thickbox.js )
function dialogue_suggestion() {
	gestionCarouselMetiersPopup.init();
	if (!$('#TB_closeWindowButton').size()) {
		$('#TB_ajaxContent').append('<div id="bottom_popup"><a href="#" id="TB_closeWindowButton"><img height="24" width="77" alt="Fermer" src="/extension/novactive/design/novactive/images/carousel3/fermer_popup.gif" /></a></div>');
		$("#TB_closeWindowButton").click(tb_remove);
	}
}


var gestionMenuTop = function() {

	var container, top, left, left_contenu, width_contenu, position_contenu, offset_menu_top;

	function init() {

		container = $('#menu_top .container_ssmenu:first');
		top = container.css("top");
		left = container.css("left");
		left_contenu = $('#contenu').offset();
		width_contenu = 1024;
		position_contenu = Math.ceil(left_contenu.left) + width_contenu;

		offset_menu_top=$('#menu_top').offset();

		// switchImage
		$('#menu_top ul > li').each(
			function(){
				$(this).switchImage(""," > a.menuItemLink > img:first");
			}
		);

		/* traitement evenement hover, focus et blur sur les rubriques dans menu */
		$('#menu_top li').hover(
			function(){
				displayItems($(this));
			},
			function(){
				hideItems($(this));
			}
		).find('a').focus(function(){
			displayItems($(this).parents('li.litem'));
		}).blur(function(){
			hideItems($(this).parents('li.litem'));
		});
		/* traitement evenement hover, focus et blur sur les rubriques dans menu */
	}

	function hideItems (elmt){
		elmt.children('.menuItemLink').removeClass('on');
		elmt.children('.container_ssmenu').css("left",left);
		elmt.children('.menuItemLink').children('.coinBD').hide();
		elmt.children('.menuItemLink').children('.coinBG').hide();
	};

	function displayItems (elmt){
		var width_ss_menu = elmt.find('.container_ssmenu').width();

		if(width_ss_menu){
			elmt.find('.container_ssmenu').css('width',width_ss_menu);
		}
		elmt.children('.menuItemLink').addClass('on');

		var offset = elmt.offset();
		var width_container_sslist = elmt.children('.container_ssmenu').width();
		var position_sslist = width_container_sslist + Math.ceil(offset.left);
		var position = parseInt(top) + Math.ceil(offset_menu_top.top);
		if( position_sslist > position_contenu ) {
			elmt.children('.menuItemLink').children('.coinBD').hide();
			elmt.children('.menuItemLink').children('.coinBG').show();

			var width_item = elmt.width();
			var position_item_menu = width_item + Math.ceil(offset.left);
			var diff2 = position_sslist - position_item_menu;
			var left_optimise = position_sslist - diff2 - width_container_sslist;

			elmt.children('.container_ssmenu').css({left:left_optimise +"px", top: position+"px"});
		} else {
			elmt.children('.container_ssmenu').css({left: Math.ceil(offset.left)+"px", top: position+"px"});
			elmt.children('.menuItemLink').children('.coinBD').show();
			elmt.children('.menuItemLink').children('.coinBG').hide();
		}
	}

	return {init:init};
}();

var gestionMenuSideBar = function () {

	var menuItems ;
	var sousMenuItems;
	var isHome;

	function init () {
		menuItems = $('#menu .item_rubr');
		sousMenuItems = $('.sous_menu', menuItems);
		isHome = $('body').is('#home');

		if (isHome) {
			sousMenuItems.css({height: '0', display: 'block', overflow: 'hidden'});
		}
		menuItems.click(function(clickEvent){

			var elmt = $(this);
			var ssMenu = elmt.find('.sous_menu');

			if (ssMenu.size() && !ssMenu.is('.sousMenuActif')) {
				clickEvent.preventDefault();
				replier(sousMenuItems.filter('.sousMenuActif'));
				deplier(ssMenu);
			}
		});

		if(ltie7) {
			// c'est trÃ¨s trÃ¨s sale, mais IE6 mÃ©rite bien Ã§a.
			replier(menuItems.find('.sous_menu'));
			deplier(menuItems.find('.sous_menu'));
		}

		if (isHome) {
			deplier(menuItems.random(1).find('.sous_menu'));
		} else {
			deplier(menuItems.filter('.on').find('.sous_menu'));
		}

		function deplier(elmt) {
			replier(sousMenuItems.filter(':animated').stop(true));
			if (isHome) {
				elmt.animate({height: '137px'}, 'slow', function() {
					postDepliement(elmt);
				});
			} else {
				elmt.slideDown('fast', function(){
					postDepliement(elmt);
				});
			}
		}

		function postDepliement(elmt) {
			elmt.addClass("sousMenuActif");
			elmt.parent().addClass("on");
			elmt.parent().find(".menuSideLink").attr('id','ItemActive');
		}

		function replier (elmt) {
			if (isHome) {
				elmt.animate({height: '0'}, 'slow', function() {
					postRepliement(elmt);
				});
			} else {
				elmt.slideUp('fast', function(){
					postRepliement(elmt);
				});
			}
		}

		function postRepliement(elmt) {
			elmt.removeClass("sousMenuActif");
			elmt.parent().removeClass("on");
			elmt.parent().find(".menuSideLink").attr('id','');
		}

	}
	return {init:init};
}();

var gestionCarouselMetiers = function () {
	function init() {
		$('.jcarousel-skin-metiers').jcarousel({
			animation: 'slow',
			wrap: 'circular',
			scroll: 1,
			easing: 'swing',
			auto: '6'
		});
	}
	return {init:init};
}();

var gestionCarouselReferences = function () {
	function init() {
		$('#carousel_references').jcarousel({
			animation: 'fast',
			wrap: 'circular',
			scroll: 4,
			visible: 4,
			easing: 'linear',
			itemFallbackDimension: '195'
		});
	}

	return {init:init};
}();

var gestionCarouselMetiersPopup = function () {
	function init() {
		$('#carousel_metiers_popup').jcarousel({
			wrap: 'circular',
			scroll: 1,
			easing: 'swing',
			itemFallbackDimension: '560'
		});
	};

	return {init:init};
}();

var homeGestionClients = function(){
	var clients;
	function _init(){
		clients=$('.clients a');

		clients.hover(
			function(){clientsOver($(this))},
			function(){clientsOut($(this))}
		).focus(
			function(){clientsOver($(this))}
		).blur(
			function(){clientsOut($(this))}
		);

		function clientsOver(elmt) {
			elmt.css({zIndex: '1'}).find('img').animate({width: '+=6', height: '+=4', left: '-3px', top: '-2px'}, "fast");
		}

		function clientsOut(elmt) {
			elmt.css({zIndex: ''}).find('img').animate({width: '-=6', height: '-=4', left: '0', top: '0'}, "fast");
		}

	};

	return {init:_init};
}();

// Nouvelle fonction jquery de retaillage de blocks
$.fn.adjustSize=function(options) {
	var settings = {
		periode: 2,
		mode: 'height',
		minHeight: 0,
		minWidth: 0
	};
	var ltie7 = $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent);
	if (options) {
		jQuery.extend(settings, options);
	}
	var totalSize = $(this).size();
	var nbPeriodes = Math.ceil(totalSize/settings.periode);
	var index = 0;
	if (settings.mode == 'height' || settings.mode == 'both') {
		var maxTotalHeightArray = new Array();
		$(this).each(function(){
			var blockId = Math.floor(index/settings.periode);
			if (!maxTotalHeightArray[blockId]) maxTotalHeightArray[blockId]=0;
			var blockTotalHeight = $(this).height();
			if (blockTotalHeight > maxTotalHeightArray[blockId]) {
				if (settings.minHeight && settings.minHeight > blockTotalHeight) blockTotalHeight = settings.minHeight;
				maxTotalHeightArray[blockId] = blockTotalHeight;
			}
			index++;
		});
		var index = 0;
		$(this).each(function(){
			var blockId = Math.floor(index/settings.periode);
			var blockComputedHeight = maxTotalHeightArray[blockId];
			if (ltie7) $(this).height(blockComputedHeight+'px');
			else $(this).css('minHeight',blockComputedHeight+'px');
			index++;
		});
	};

	if (settings.mode == 'width' || settings.mode == 'both') {
		var maxTotalWidthArray = new Array();
		$(this).each(function(){
			var blockId = Math.floor(index/settings.periode);
			if (!maxTotalWidthArray[blockId]) maxTotalWidthArray[blockId]=0;
			var blockTotalWidth = $(this).width() ? $(this).width() : $(this).attr('offsetWidth') ;
			if (blockTotalWidth > maxTotalWidthArray[blockId]) {
				if (settings.minWidth && settings.minWidth > blockTotalHeight) blockTotalWidth = settings.minWidth;
				maxTotalWidthArray[blockId] = blockTotalWidth;
			}
			index++;
		});
		var index = 0;
		$(this).each(function(){
			var blockId = Math.floor(index/settings.periode);
			var blockComputedWidth = maxTotalWidthArray[blockId];
			if (ltie7) $(this).width(blockComputedWidth+'px');
			else $(this).css('minWidth',blockComputedWidth+'px');
			index++;
		});
	};

	return this;
};


// Target est un sÃ©lecteur jQuery qui permet d'indiquer quel est l'Ã©lement (image ou input) qui doit changer.
// Sa valeur par dÃ©faut est '$myself', ce qui indique que l'objet est sa propre cible.
// Ex : $('#menu > li').each(function(){$(this).switchImage("","> a > img");});
$.fn.switchImage=function(eventTargetSelector, changeTargetSelector, options) {
	var eventTargetSelector, changeTargetSelector, eventTarget, changeTarget;
	if (!eventTargetSelector) eventTargetSelector = '?myself';
	if (!changeTargetSelector) changeTargetSelector = '?myself';
	var settings = {
		stringDefault: '_off',
		stringHover: '_on'
	};
	if (options) {
		jQuery.extend(settings, options);
	}
	if (eventTargetSelector == '?myself') eventTarget=$(this);
	else eventTarget = $(this).find(eventTargetSelector);
	if (changeTargetSelector == '?myself') changeTarget=$(this);
	else changeTarget = $(this).find(changeTargetSelector);
	eventTarget.filter(function(index){
		return (changeTarget.is("input[type=image][src]") || changeTarget.is("img[src]"));
	}).mouseover(function(){switchToHover(changeTarget)}).focus(function(){switchToHover(changeTarget)}).mouseout(function(){switchToDefault(changeTarget)}).blur(function(){switchToDefault(changeTarget)});

	function switchToHover(e) {
		e.each(function(){
			getSrcElmts.init($(this));
			if (getSrcElmts.fileName().indexOf(settings.stringDefault) != -1) {
				$(this).attr('src', getSrcElmts.filePath()+'/'+getSrcElmts.replaceFileName(settings.stringDefault, settings.stringHover));
			}
		});
	}
	function switchToDefault(e) {
		e.each(function(){
			getSrcElmts.init($(this));
			if (getSrcElmts.fileName().indexOf(settings.stringHover) != -1) {
				$(this).attr('src', getSrcElmts.filePath()+'/'+getSrcElmts.replaceFileName(settings.stringHover, settings.stringDefault));
			}
		});
	}

	var getSrcElmts = function() {
		var src,srcPathSplit, srcPathSplitLength;
		function init(e){
			src = e.attr('src');
			srcPathSplit = src.split('/');
			srcPathSplitLength = srcPathSplit.length;
		}
		function filePath(){
			if (srcPathSplitLength)	return srcPathSplit.slice(0,-1).join('/');
		}
		function fileName(){
			if (srcPathSplitLength)	return srcPathSplit[srcPathSplitLength-1];
		}
		function replaceFileName(stFrom,stTo){
			elemts=fileName().split(stFrom);
			end=elemts.pop();
			begin=elemts.join(stFrom);
			return begin+stTo+end;
		}
		return {init:init,filePath:filePath,fileName:fileName,replaceFileName:replaceFileName};
	}();

	changeTarget.each(function(){
		// preload
		getSrcElmts.init($(this));
		var preload = new Image;
		preload.src=getSrcElmts.filePath()+'/'+getSrcElmts.replaceFileName(settings.stringDefault, settings.stringHover);

	});
	return this;
};

// By Olivier â€œLespacedunmatinâ€? G., under GPL 3+ licence, WTFPL, or Beer Copyright.
// Example : $('li').random().show(); $('li').random(4).show(); $('li').random({howManyElementsToReturn: 'all'}).show();
jQuery.fn.random = function(options) {
	var elements = this;
	var numberOfElements;
	var elementsToReturn = jQuery([]);
	var settings = {
		howManyElementsToReturn: 'all'
	};

	if(options) {
		if (typeof(options) == 'number') {
			settings.howManyElementsToReturn = options;
		} else {
			jQuery.extend(settings, options);
		}
	}

	if (settings.howManyElementsToReturn != 'all') {
		settings.howManyElementsToReturn = parseInt(settings.howManyElementsToReturn);
		// FIXME : if options == NaN or 0, settings.howManyElementsToReturn == 'all'. The next line is useless.
		if (isNaN(settings.howManyElementsToReturn) || settings.howManyElementsToReturn < 1) return null;
	}

	numberOfElements = elements.size();

	if (settings.howManyElementsToReturn >= numberOfElements || settings.howManyElementsToReturn == 'all') {
		settings.howManyElementsToReturn = numberOfElements;
	}

	while(settings.howManyElementsToReturn > 0 && numberOfElements > 0) {
		var rand = Math.round( Math.random() * (numberOfElements-1));

		elementsToReturn = elementsToReturn.add(elements.eq(rand));
		elements = elements.not(':eq('+rand+')');

		numberOfElements = elements.size();
		settings.howManyElementsToReturn = settings.howManyElementsToReturn-1;
	}

	return elementsToReturn;
};
