var listeFormationCallback;
var listeMetiersCallback;
var repliRechercheCallback;
var listeFormationCarifCallback;
var initializeVideoPlayer;
var initializeVideoPlayerBloc;
var changeFavoriteHref;
var dialogDomaines;
var dialogMetiers;
var dialogDiplomes;
var selectTreeVals;
var checkSelectedValInTree;
var removeAccents;
var getRawValue;

(function($) {

	repliRechercheCallback = function($lien) {
		repliRecherche();
	}

	listeFormationCallback = function($lien) {
		strippedTable();
		customizeCheckboxListeFormation();
		changeFavoriteHref($lien)
	};

	listeFormationCarifCallback = function($lien) {
		customizeCheckboxListeFormation();
		changeFavoriteHref($lien)
	};

	listeMetiersCallback = function($lien) {
		strippedTable();
		changeFavoriteHref($lien)
	};

	listeMetierParCentreInteretCallback = function($lien) {
		sortAndStripTable();
		changeFavoriteHref($lien)

	};

	listeProfessionelsOrientationCallback = function($lien) {
		sortAndStripTable();
		changeFavoriteHref($lien);
	}

	/* Change la cible du lien d'ajout en favoris pour les pages ajax */
	changeFavoriteHref = function($lien) {
		$("a.jQueryBookmark").attr('href', $lien);

	}

	initializeVideoPlayer = function($thumb, $width, $height) {
		var widthTmp = $width;
		var heightTmp = $height;
		var flashvars = {};
		flashvars.file = $thumb.href;
		flashvars.image = $("img:eq(0)", $thumb).attr("src");
		var params = {};
		params.allowfullscreen = 'true';
		params.allowscriptaccess = 'always';
		params.wmode = 'opaque';
		swfobject
				.embedSWF(
						"/extension/meformer/design/meformer/javascript/mediaplayer/player.swf",
						"player",
						widthTmp,
						heightTmp,
						"9.0.0",
						"/extension/meformer/design/meformer/javascript/mediaplayer/expressInstall.swf",
						flashvars, params);
	};
	initializeVideoPlayerBloc = function($thumb, $width, $height) {
		var widthTmp = $width;
		var heightTmp = $height;
		var flashvars = {};
		flashvars.file = $thumb.href;
		flashvars.image = $("img:eq(0)", $thumb).attr("src");
		var params = {};
		params.allowfullscreen = 'true';
		params.allowscriptaccess = 'always';
		params.wmode = 'opaque';
		swfobject
				.embedSWF(
						"/extension/meformer/design/meformer/javascript/mediaplayer/player.swf",
						$thumb.id,
						widthTmp,
						heightTmp,
						"9.0.0",
						"/extension/meformer/design/meformer/javascript/mediaplayer/expressInstall.swf",
						flashvars, params);
	};

	var repliRecherche = function() {
		// Repli du formulaire de recherche lorsqu'on clique sur l'un des lien
		// du bloc resultat
		$(".searchPreResults a").click(function() {
			$(".searchControl .displayCriteria").trigger("click");
			return false;
		});
	};

	var sortAndStripTable = function() {
		$("#metiersparcentresinteret").tablesorter({
			textExtraction : [ 'complex' ],
			widgets : [ 'zebra' ]
		});
	};

	var strippedTable = function() {
		$("table.stripped tbody tr").filter(":odd").addClass("odd").end()
				.filter(":even").addClass("even").end();
	};

	var customizeCheckboxListeFormation = function() {
		$(".cbxPanier").customizeCheckbox({
			checkboxCssClass : "customizeCbxPanier",
			checkboxCssClassChecked : "customizeCbxPanierChecked",
			checkboxCssClassUnchecked : "customizeCbxPanierUnchecked",
			checkboxSpanText : "panier"
		});

		var tableResult = $(".resultsItem table");
		$(".cbxAllPanier", tableResult)
				.customizeCheckbox(
						{
							checkboxCssClass : "customizeCbxPanierAll",
							checkboxCssClassChecked : "customizeCbxPanierCheckedAll",
							checkboxCssClassUnchecked : "customizeCbxPanierUncheckedAll",
							checkboxSpanText : $(".checkall span:eq(0)",
									tableResult).html(),
							checkboxAfterTriggeringClick : function(selectSrc,
									spanDest) {
								if (selectSrc.attr("checked")) {
									$(".customizeCbxPanierUnchecked",
											tableResult).trigger("click");
								} else {
									$(".customizeCbxPanierChecked", tableResult)
											.trigger("click");
								}
							}
						});
		$(".checkall span:eq(0)", tableResult).hide();
	};

	$(document).ready(function() {
		$("label.taperici").taperici();
		strippedTable();
		customizeCheckboxListeFormation();
	});
	$(document).ready(function() {
		$(".linkRadioWithText").each(function() {
			var $container = $(this);
			$("input[type=radio]", $container).bind("click", function() {
				$("input[type=text]", $container).focus();
			});
			$("input[type=text]", $container).bind("focus", function() {
				$("input[type=radio]", $container)[0].checked = true;
			});
		});
	});

	$(document)
			.ready(
					function() {
						$('.gallery a')
								.lightBox(
										{
											imageLoading : '/extension/meformer/design/meformer/images/lightbox/lightbox-ico-loading.gif',
											imageBtnPrev : '/extension/meformer/design/meformer/images/lightbox/lightbox-btn-prev.gif',
											imageBtnNext : '/extension/meformer/design/meformer/images/lightbox/lightbox-btn-next.gif',
											imageBtnClose : '/extension/meformer/design/meformer/images/lightbox/lightbox-btn-close.gif',
											imageBlank : '/extension/meformer/design/meformer/images/lightbox/lightbox-blank.gif',
											txtOf : 'sur'

										});
					});

	$(document)
			.ready(
					function() {
						var descriptionDestField = $(".searchPreResultWithDescription .description");
						$(".checkboxDescription label").hover(
								function() {
									descriptionDestField.html($(this).next(
											".cbDescription").html());
								}, function() {
									descriptionDestField.html("");
								});
					});

	// Par defaut on cache les search controls en arrivant sur la page

	$(document).ready(function() {
		$(".searchControlHidden").hide();
	});

	// Sur les fiches on replit le div de formulaire de recherche
	$(document).ready(function() {
		$(".hideSearchForm").hide();
	});

	$(document).ready(function() {

		repliRecherche();
	
		 $(".searchControl .displayCriteria").click(function(){
			var searchForm = $(".searchForm");
			var $visible = searchForm.filter(":visible");
			if ($visible.length > 0){
				searchForm.slideUp("slow");
				$(this).html('visualiser vos critères');
			} else {
				searchForm.slideDown("slow");
				$(this).html('masquer vos critères');
			}
			return false;
	    });
	    
	});


	/* Recherche metier par fonction pliage/depliage des fonctions */
	$(document).ready(function() {
		var $liToggle = $("li.toggle");
		$("ul", $liToggle).hide();
		$liToggle.click(function() {

			$("ul", this).slideToggle("slow");
		});
	});

	$(document).ready(function() {
		var $listFold = $("div.list_fold");
		$("dt.folded + dd", $listFold).hide();

		$("dt.folded, dt.unfolded", $listFold).bind("click", function() {
			var $this = $(this);
			$this.next("dd").toggle();
			$this.toggleClass("folded");
			$this.toggleClass("unfolded");
		});
	});

	/* Gestion des videos sur la page d'accueil */
	$(document).ready(
			function() {
				$("#home a.thumbail").click(
						function() {
							initializeVideoPlayer(this, 308, 260);
							/* Maj du champ description */
							var parent = $(this).parent();
							$("#description_video").html(
									$(this).parent().find(".description_video")
											.html());
							$("#infoTitle").html(
									$(this).parent().find(".titre_video")
											.html());
							return false;
						});
				/* On affiche aleatoirement l'une des 6 videos */
				var maxVideo = $("#home a.thumbail").size();
				/* retourne un chiffre en 0 et (maxVideo -1) */
				var numVideo = Math.floor((maxVideo) * Math.random())
				$("#home a.thumbail:eq(" + numVideo + ")").trigger("click");
				return false;
			});

	/* Gestion des videos sur la page recherche video */
	$(document).ready(
			function() {
				$(".trouverVideoResult a.thumbail")
						.click(
								function() {
									$("#ancrePlayer").html("<div id=\"player\"></div><div class=\"descriptionFilePlayer\"> </div>");
									initializeVideoPlayer(this, 308, 260);
									/* Maj des champs description */
									$(".descriptionFilePlayer").html(
											$(this).parent().find(".infoVideo")
													.html());
									$("#ancrePlayer").attr("tabindex", -1)
											.focus();
									return false;
								});

				$(".trouverVideoResult a.videoTitle")
						.click(
								function() {
									$("#ancrePlayer").html("<div id=\"player\"></div><div class=\"descriptionFilePlayer\"> </div>");
									var thumbnail = $(this).parent().find(
											'.thumbail').get(0);
									initializeVideoPlayer(thumbnail, 308, 260);
									$(".descriptionFilePlayer").html(
											$(this).parent().find(".infoVideo")
													.html());
									$("#ancrePlayer").attr("tabindex", -1)
											.focus();
									return false;
								});

				$(".trouverVideo select").change(function() {
					$(this).parents("form").submit();
				});
				
				
				$(".trouverVideoResult a.thumbail_photo")
				.click(function() {
					var thumbnail = $(this).parent().find(
							'.thumbail').get(0);
					$("#ancrePlayer").html(
							$(this).parent().find(".infoPhotoContainer").html()
									);
					$("#ancrePlayer").attr("tabindex", -1)
							.focus();
					return false;
				});

				$(".trouverVideoResult a.videoTitle_photo")
				.click(function() {
					var thumbnail = $(this).parent().find(
							'.thumbail').get(0);
					$("#ancrePlayer").html(
							$(this).parent().find(".infoPhotoContainer")
									.html());
					$("#ancrePlayer").attr("tabindex", -1)
							.focus();
					return false;
				});

			});
	
	/*
	 * Gestion des blocs video
	 */
	$(document).ready(
			function() {
				$("a.video_bloc").each(
						function() {
							initializeVideoPlayerBloc(this, 300, 260);
						}
				);
	});

	/* Gestion des videos du bloc de ressource*/
	$(document).ready(
			function() {
				$(".block_resources_multi .playerThumbnail").hide();
				$(".block_resources_multi a.thumbail").click(
						function() {
							$(".secondBloc .block_media_bottom").html(
									'<div id="title_video" class="title_media">'+$(this).parents('.block_actualite').find(
											'.video_title').html()+'</div><div id="player"></div>');
							initializeVideoPlayer(this, 280, 240);
							return false;
						});
				$(".block_resources_multi a.video_title").click(
						function() {
							var thumbnail = $(this).parents('.block_actualite')
									.find('.thumbail').get(0);
							$(".secondBloc .block_media_bottom").html(
									'<div id="title_video" class="title_media">'+$(this).parents('.block_actualite').find(
											'.video_title').html()+'</div><div id="player"></div>');
							initializeVideoPlayer(thumbnail, 280, 240);
							return false;
				});
				
				/* Videos externes*/
				$(".block_resources_multi a.thumbail_photo").click(
						function() {
							var thumbnail = $(this).parents('.block_actualite')
							.find('.thumbail').get(0);
							$('.secondBloc .block_media_bottom').html(
									'<div id="title_video" class="title_media">'+$(this).parents('.block_actualite').find(
									'.video_title_photo').html()+'</div>'+
									$(this).parents('.block_actualite').find(
									'.infoPhotoContainer').html()
							);
							return false;
				});
				$(".block_resources_multi .actualite_title_photo a.video_title_photo").click(
						function() {
							var thumbnail = $(this).parents('.block_actualite')
									.find('.thumbail').get(0);
							$('.secondBloc .block_media_bottom').html(
									'<div id="title_video" class="title_media">'+$(this).parents('.block_actualite').find(
									'.video_title_photo').html()+'</div>'+
									$(this).parents('.block_actualite').find(
									'.infoPhotoContainer').html()
							);
							return false;
				});
				if($.trim($(".block_resources_multi .secondBloc").html())=="" && ($(".video_title").first().length||$(".video_title_photo").first().length)){
					$(".block_resources_multi .secondBloc").html('<div class="block_media"><div class="block_media_bottom"></div></div>');
				}
				$(".video_title").first().trigger("click");
				if($(".video_title").first().length==0){
					$(".video_title_photo").first().trigger("click");
				}
			});
	$(document)
			.ready(
					function() {
						$("a.jQueryBookmark")
								.click(
										function(e) {
											e.preventDefault(); // this will
																// prevent the
																// anchor tag
																// from going
																// the user off
																// to the link
											var bookmarkUrl = this.href;
											var bookmarkTitle = this.title;

											if (window.sidebar) { // For
																	// Mozilla
																	// Firefox
																	// Bookmark
												window.sidebar.addPanel(
														bookmarkTitle,
														bookmarkUrl, "");
											} else if (window.chrome) {
												alert('Votre navigateur ne supporte pas cette mise en favoris.');
											} else if (window.external
													|| document.all) { // For
																		// IE
																		// Favorite
												window.external.AddFavorite(
														bookmarkUrl,
														bookmarkTitle);
											} else if (window.opera) { // For
																		// Opera
																		// Browsers
												$("a.jQueryBookmark").attr(
														"href", bookmarkUrl);
												$("a.jQueryBookmark").attr(
														"title", bookmarkTitle);
												$("a.jQueryBookmark").attr(
														"rel", "sidebar");
											} else { // for other browsers
														// which does not
														// support
												alert('Votre navigateur ne supporte pas cette mise en favoris.');
												return false;
											}
										});
					});

	/* Selection dans les arbres carif */

	selectTreeVals = function(selectedHidden, checkbox) {
		var selected_vals = $('#' + selectedHidden).val();
		var current_val = checkbox.val();
		// Si on coche la case, on ajoute la valeur courante au champ hidden qui
		// stocke toutes les valeurs
		if (checkbox.is(':checked')) {
			// suppression des caches cochees en dessous de la case courante
			var tab = selected_vals.split('|');
			var filteredTab = tab.filter(function(val) {
				return !(val.indexOf(current_val) === 0);
			});
			filteredTab.push(current_val)
			$('#' + selectedHidden).val(filteredTab.join('|'));
			// Si on decoche la case, on retire la valeur du champ hidden si
			// elle existe
		} else {
			var tab = selected_vals.split('|');
			var filteredTab = tab.filter(function(val) {
				return !(val.indexOf(current_val) === 0);
			});
			$('#' + selectedHidden).val(filteredTab.join('|'));
		}
		return true;
	};
	
	/*  Initialisation de l'arbre avec les valeurs preselectionnees*/
	
	checkSelectedValInTree = function(selectedHidden){
		var selected_vals = $('#' + selectedHidden).val();
		var tab_selected_vals = selected_vals.split('|');
		for(var i=0; i< tab_selected_vals.length;i++){
			if(tab_selected_vals[i] != ''){
				var checkbox = $('input[type=checkbox][value="' + tab_selected_vals[i] + '"]');
				checkbox.attr('checked',true);
			}
		}
		return true;
	};
	
	/* Suppression des accents pour la recherche dans les arbres */
	removeAccents = function(chaine) {
		  var temp = chaine.replace(/[àâä]/gi,"a");
		  temp = temp.replace(/[éèêë]/gi,"e");
		  temp = temp.replace(/[îï]/gi,"i");
		  temp = temp.replace(/[ôö]/gi,"o");
		  temp = temp.replace(/[ùûü]/gi,"u");
		  return temp;
	};
	
	/* Suppression des accents + passage en lower case pour la recherche dans les arbres */
	getRawValue = function(val){
		return removeAccents(val.toLowerCase());
	};
	
	
	
	
})(jQuery);

if (!Array.prototype.filter) {
	Array.prototype.filter = function(fun /* , thisp */) {
		var len = this.length >>> 0;
		if (typeof fun != "function") {
			throw new TypeError();
		}

		var res = [];
		var thisp = arguments[1];
		for ( var i = 0; i < len; i++) {
			if (i in this) {
				var val = this[i]; // in case fun mutates this
				if (fun.call(thisp, val, i, this)) {
					res.push(val);
				}
			}
		}

		return res;
	};
}

