var ltie7 = ($.browser.msie && $.browser.version < 7);
var ltie8 = ($.browser.msie && $.browser.version < 8);
var ltie9 = ($.browser.msie && $.browser.version < 9);

$(function(){
	$.ifixpng('/extension/iogs/design/iogs/images/pixel.gif');

	// home
	if (ltie7) {$('#homeAnimation img:first-child').css({display: 'block'});}
	$('#articles_push li.item_child').adjustSize({periode: 2});
	$('li.item_child h3').adjustSize({periode: 2});
	animHome.init();
	evitement.init();
	menu.init();
	nav_sous_home.init();
	offres_emploi_menu.init();
	  var validator = $("#frmPlaceOJeunes").validate({
	  	submitHandler: function() { 
            $("#frmPlaceOJeunes").hide(); 
            $("h1.h3").html('<p>"Merci, votre offre a bien été envoyée aux services de placeOjeunes"</p>');
        }
	  	
	  });
	$('#liste_sites li').adjustSize();
	if (ltie7) {
		$('img[usemap]').css('border','none');
		$('input[type="radio"], input[type="checkbox"], input[type="file"], input[type="image"]').css('border','none');
		$('#liste_actus li:first-child').css({paddingTop: '0', borderTop: 'none'});
		$('.offres_emploi_menuItem:first-child a').css("background-image","none");
		$('.object-left + p, .object-right + p').css({margin: '14px 0 15px'});
		$('#headerAides li:first-child a').css({background: 'none'});
		$('.navRubItem:first-child').css({borderTop: 'none', paddingTop: '8px'});
		$('#groupe_axe_recherche li:first-child').css({borderTop: 'none'});
		$('#campusPratique li:first-child').css({borderTop: 'none'});
		$('#savoirPlus li:first-child a').css({borderTop: 0, paddingTop: '7px'});
		$('#footerLinks li:first-child').css({background: 'transparent', paddingLeft: 0});
		$('.fMenuItem:first-child').css({borderLeft: 'none'});
		$('img[src$=.png]').filter(function(){
			return $(this).parents('#menu').size() ? false : true;
		}).ifixpng();
	}
});



var animHome = function(){
	var imgs, img, nextImg;
	function _init(){
		imgs = $('#homeAnimation img');

		// s'assurer qu'il y a au moins deux images.
		if (imgs.size()<2) return;

		img = imgs.filter(':visible');

		animateTimer(img);
	}
	function animateTimer(img) {
		window.setTimeout(animateImg, 3000);
	}
	function animateImg() {
		getNextImg(img);
		nextImg.css('z-index','1').show();
		img.css('z-index','2').fadeOut(1500, function(){
			img.css('z-index','').hide();
			img=nextImg;
			animateTimer(img);
		});
	}
	function getNextImg(img) {
		tmp = img.next('img')
		if (tmp.size()) nextImg = tmp;
		else nextImg = imgs.filter(':first');
	}

	return {init:_init}
}();

var evitement = function(){
	function _init() {
		// permet d'afficher les liens d'évitement si une navigation au clavier est détectée (focus sur un lien hors de vue).
		var evitement = $('#liensEvitement')
		$('a',evitement).one('focus',function(){
			if (evitement.css('position')!='static') {
				evitement.hide().css('position','static').slideDown('fast');
			}
		});
	}
	return {init:_init}
}();

var nav_sous_home = function(){
	function _init() {
		// permet de centrer verticalement les texte du menu de navigation gauche de la sous home.
		$(".navRubLink .navRubLinkContainer").each(function(){
			var height_lien = $(this).height();
			var difference = 51 - height_lien;
			var padding = Math.round(difference/2);
			$(this).css("padding-top", padding);
		});


	}
	return {init:_init}
}();


var menu = function(){
	function _init() {
		$('.menuItem').not('.on').each(function(){$(this).switchImage("","> a > img");})
		if (ltie7) {
			$('.menuItem').hover(function(){
				$('.sMenu', $(this)).show();
			},function(){
				$('.sMenu', $(this)).hide();
			});
		}
	}
	return {init:_init}
}();

var offres_emploi_menu = function(){
	var menuLinks, offresListes, hash;
	function _init() {
		menuLinks = $('#offres_emploi_menu a');
		offresListes = $('.offres_emploi_liste');

		menuLinks.click(function(){
			var e = $(this);
			$('.offres_emploi_menuItemActif').removeClass('offres_emploi_menuItemActif');
			e.parent().addClass('offres_emploi_menuItemActif');
			var id = cleanId(e.attr('href'));
			offresSwap(id);
			window.location.hash = id;
			return false;
		});

		// s'il y a un hash dans l'URL, on vérifie que ça ne soit pas une des "rubriques". Si c'est le cas, on simule un clic sur le lien correspondant.
		hash = cleanId(window.location.hash);
		if (hash) menuLinks.filter('[href$=#'+hash+']').click();
	}

	function offresSwap(id) {
		var cible = $('#'+id);
		if (!cible.size()) return;
		$('.offres_emploi_liste_visible').removeClass('offres_emploi_liste_visible');
		cible.next('.offres_emploi_liste').addClass('offres_emploi_liste_visible');
	}

	function cleanId(id) {
		id = id.split('#');
		id = id.pop();
		return id;
	}

	return {init:_init}
}();

/*
 * jQuery ifixpng plugin
 * (previously known as pngfix)
 * Version 2.1  (23/04/2008)
 * @requires jQuery v1.1.3 or above
 *
 * Examples at: http://jquery.khurshid.com
 * Copyright (c) 2007 Kush M.
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */

 /**
  *
  * @example
  *
  * optional if location of pixel.gif if different to default which is images/pixel.gif
  * $.ifixpng('media/pixel.gif');
  *
  * $('img[@src$=.png], #panel').ifixpng();
  *
  * @apply hack to all png images and #panel which icluded png img in its css
  *
  * @name ifixpng
  * @type jQuery
  * @cat Plugins/Image
  * @return jQuery
  * @author jQuery Community
  */

(function($) {

	/**
	 * helper variables and function
	 */
	$.ifixpng = function(customPixel) {
		$.ifixpng.pixel = customPixel;
	};

	$.ifixpng.getPixel = function() {
		return $.ifixpng.pixel || 'images/pixel.gif';
	};

	var hack = {
		ltie7  : $.browser.msie && $.browser.version < 7,
		filter : function(src) {
			return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=crop,src='"+src+"')";
		}
	};

	/**
	 * Applies ie png hack to selected dom elements
	 *
	 * $('img[@src$=.png]').ifixpng();
	 * @desc apply hack to all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').ifixpng();
	 * @desc apply hack to element #panel and all images with png extensions
	 *
	 * @name ifixpng
	 */

	$.fn.ifixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			// in case rewriting urls
			var base = $('base').attr('href');
			if (base) {
				// remove anything after the last '/'
				base = base.replace(/\/[^\/]+$/,'/');
			}
			if ($$.is('img') || $$.is('input')) { // hack image tags present in dom
				if ($$.attr('src')) {
					if ($$.attr('src').match(/.*\.png([?].*)?$/i)) { // make sure it is png image
						var oH = $$.attr('height') ? $$.attr('height') : $$.height();
						var oW = $$.attr('width') ? $$.attr('width') : $$.width();
						// use source tag value if set
						var source = (base && $$.attr('src').search(/^(\/|http:)/i)) ? base + $$.attr('src') : $$.attr('src');
						// apply filter
						$$.css({filter:hack.filter(source), width:$$.width(), height:$$.height()})
						  .attr({src:$.ifixpng.getPixel()})
						  .positionFix();
						// rétablir les dimensions originales de l'image.
						$$.height(oH);
						$$.width(oW);
					}
				}
			} else { // hack png css properties present inside css
				var image = $$.css('backgroundImage');
				if (image.match(/^url\(["']?(.*\.png([?].*)?)["']?\)$/i)) {
					image = RegExp.$1;
					image = (base && image.substring(0,1)!='/') ? base + image : image;
					$$.css({backgroundImage:'none', filter:hack.filter(image)})
					  .children().children().positionFix();
				}
			}
		});
	} : function() { return this; };

	/**
	 * Removes any png hack that may have been applied previously
	 *
	 * $('img[@src$=.png]').iunfixpng();
	 * @desc revert hack on all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').iunfixpng();
	 * @desc revert hack on element #panel and all images with png extensions
	 *
	 * @name iunfixpng
	 */

	$.fn.iunfixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			var src = $$.css('filter');
			if (src.match(/src=["']?(.*\.png([?].*)?)["']?/i)) { // get img source from filter
				src = RegExp.$1;
				if ($$.is('img') || $$.is('input')) {
					$$.attr({src:src}).css({filter:''});
				} else {
					$$.css({filter:'', background:'url('+src+')'});
				}
			}
		});
	} : function() { return this; };

	/**
	 * positions selected item relatively
	 */

	$.fn.positionFix = function() {
		return this.each(function() {
			var $$ = $(this);
			var position = $$.css('position');
			if (position != 'absolute' && position != 'relative') {
				$$.css({position:'relative'});
			}
		});
	};

})(jQuery);


// 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");});
(function($) {
	$.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));
					//if ($.ifixpng && ltie7) $(this).ifixpng();
				}
			});
		}

		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));
					//if ($.ifixpng && ltie7) $(this).ifixpng();
				}
			});
		}

		var getSrcElmts = function() {
			var src,srcPathSplit, srcPathSplitLength;
			function init(e){
				//if ($.ifixpng && ltie7) e.iunfixpng();
				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);
			//if ($.ifixpng && ltie7) $(this).ifixpng();
		});

		return this;
	}
})(jQuery);

//ltie7 : $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent),
// Nouvelle fonction jquery de retaillage de blocks
$.fn.adjustSize=function(options) {
	var settings = {
		periode: 3,
		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');
			if (ltie8) $(this).height(blockComputedHeight+'px');
			if (ltie9) $(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;
}

