altran = {

	load: function(){
		this.setWidgets();
		this.setRolloverTabs();
		this.setLinkList();
		this.setAccordions();
		this.setVideoDetailsPlayer();
		this.setPopupVideo();
		this.setPopupFlash();
		this.setStructureSlideshow();
		this.setFlashDiaporama();
		this.setVideoCoverflow();
		this.setLightbox();
		this.setSearchBoxBehavior();
		this.setTools();
		this.setDownloadForm();
	},
	setWidgets: function(){
		$.widget("ui.altranSlideshow", altran.widgets.slideshow);
		$.widget("ui.altranDialog", altran.dialog);
		$.widget("ui.diaporama",DiaporamaManager);
		$(".slideshow").altranSlideshow();
	},
	setTools: function(){
		$('.btnPrint').click(function(){
			window.print();
		});
		$('.btnSend').click(function(){
			return addthis_sendto('email');
		});
	},
	setLightbox: function(){
		$('a[rel*="lightbox"]').lightBox({
			imageLoading: '/fileadmin/templates/main/img/lightBox/lightbox-ico-loading.gif',
			imageBtnPrev: '/fileadmin/templates/main/img/lightBox/lightbox-btn-prev.gif',
			imageBtnNext: '/fileadmin/templates/main/img/lightBox/lightbox-btn-next.gif',
			imageBtnClose: '/fileadmin/templates/main/img/lightBox/lightbox-btn-close.gif',
			imageBlank: '/fileadmin/templates/main/img/lightBox/lightbox-blank.gif'
		});
	},
	setRolloverTabs: function(){
		$(".btnTabContainer .tabCol").click(function(){
			var index = $(".btnTabContainer .tabCol").index(this) + 1;
			var container = $(this).parent().parent().parent();
			container.find("a.btnCell").removeClass("active");
			$(this).children("a").addClass("active");
			container.children("div:not(.btnTabContainer)").hide();
			container.children(".contentTab"+index).show();
		});
	},

	setLinkList: function(){
		$(".selectLinksForm a").click(function(){
			form = $(this).parent();
			url = $(form).children(".selectLinks").val();
			window.location = url;
		});
	},

	setAccordions: function(){
		$(".accordion").accordion({
			collapsible : true,
			active : false,
			autoHeight:false
		});
		$(".accordion .accordionTitle:first").addClass("firstItem");
		$(".accordion .accordionTitle:last").addClass("lastItem");
	},

	setExpandable: function(id, height){
		$("#"+id).prepend('<ul class="tabNavigation"></ul>');
		nbElt = $("#"+id+" .tabContent .contentPadding h3").size();
		cssClass = "";
		if(nbElt > 0){
			/* Tab configuration */
			$("#"+id+" .tabContent .contentPadding h3").each(function(index){
				if(index == 0) cssClass="selected firstTab";
				else if(index == nbElt - 1) cssClass="lastTab";
				$("#"+id+" .tabNavigation").append('<li class="'+cssClass+'"><a href="javascript:;">'+$(this).html()+'</a></li>');
				$(this).remove();
			});
			$("#"+id+" .tabNavigation li a").each(function(index){
				$(this).click(function(){
					$("#"+id+" .tabContent:not(:eq("+index+"))").hide();
					$("#"+id+" .tabContent:not(:eq("+index+")) .contentPadding .tabContentExpandable").height(height);
					$("#"+id+" .tabContent:not(:eq("+index+")) .contentPadding .deployBox").show();
					$("#"+id+" .tabContent:eq("+index+")").show();
					$("#"+id+" .tabNavigation li").removeClass("selected");
					$(this).parent().addClass("selected");
				});
			});

			/* Sizing configuration */
			$("#"+id+" .tabContent .contentPadding .tabContentExpandable").height(height);
			$("#"+id+" .tabContent:not(:first)").hide();

			/* Deploy button */
			$("#"+id+" .tabContent .contentPadding a.btnDeploy").click(function(){
				p = $(this).parents(".contentPadding");
				div = $(p[1]).find(".tabContentExpandable");
				div.height("");
				$(this).parents(".deployBox").hide();
			});
		}
	},
	
	setVideoDetailsPlayer : function(){
		this.setVideoDetailsAccordeon();
		var videoDetailsPlayers = $(".videoDetailsPlayer");
		var params = {
			allowFullScreen:"true",
			menu: "false",
			scale: "noScale",
			wmode: "transparent"
		};
		$.each(videoDetailsPlayers,function(i,val){
			var videoId = $(val).attr("videoid");
			var containerId = $(val).attr("id");
			var videoWidth = $(val).attr("videoWidth");
			var videoHeight = (typeof(videoWidth) == "undefined") ? 333 : videoWidth;  //Math.ceil(videoWidth/1.34);
			videoWidth = (typeof(videoWidth) == "undefined") ? 490 : videoWidth;
			var flashvars = {
				playerURL : "/typo3conf/ext/lp_webtvcreator/Resources/Public/swf/video/player/player.swf",
				playerClassRef : "org.coreplayer.view.components.CorePlayer",
				controlsURL : "/typo3conf/ext/lp_webtvcreator/Resources/Public/swf/video/player/controls.swf",
				skinURL : "/typo3conf/ext/lp_webtvcreator/Resources/Public/swf/video/player/skin.swf",
				accessibilityURL : '/typo3conf/ext/lp_webtvcreator/Resources/Public/swf/video/player/accessibility.xml',
				sessionId : 1,
				userId : 1,
				playHandler : "altran.updateView",
				videoId : parseInt(videoId),
				gatewayURL : '/?type=900'

			};
			if(swfobject.hasFlashPlayerVersion("9.0"))
			{
				swfobject.embedSWF( "/typo3conf/ext/lp_webtvcreator/Resources/Public/swf/video/player/preloader.swf", containerId, videoWidth, videoHeight, "9.0.0", "/typo3conf/ext/lp_webtvcreator/Resources/Public/swf/video/player/install/expressInstall.swf", flashvars, params );
			}
		});
	},

	setDownloadForm: function(){
		$(".downloadForm").click(function(e){
			var link = $(this).attr('href');
			$('<div id="downloadFormPopup"></div>')
			.load('/?type=102', function(){
				var popup = this;
				$("#downloadForm").validate({
					invalidHandler: function(form, validator){
						var errors = validator.numberOfInvalids();
						if (errors) {
							$("#downloadForm .error").show();
						} else {
							$("#downloadForm .error").hide();
						}
					},
					errorPlacement: function(error, element) {}
				});
				$('#downloadForm').submit(function(){
					var fields = $('#downloadForm').serializeArray();
					$.ajax({
						type: 'POST',
						url: '/?type=102',
						data: fields,
						success: function(data){
							$(popup).dialog("close");
							window.location = link;
						},
						dataType: "json"
					});
					return false;
				});
			})
			.dialog({
				modal: true,
				width: 630
			});
			return false;
		});
	},

	fixImageSizeInVideoList : function()
	{
		var imagesTofix = $(".virtualColBody .videolistImg");
		if(imagesTofix.length==0) return;
		imagesTofix.attr("width",93);
		imagesTofix.attr("height",73);
		/*remove video's description too*/
		$(".virtualColBody .videoDesc").remove();
	},

	altranVideosView : [],
	updateView : function(videoId)
	{
		if(videoId=="undefined") return false;
		if($.inArray(videoId,this.altranVideosView) >= 0 ) return false; //vidéo déja vue par l'utilisateur uniquement pour la session
		var self = this;
		var data = {};
		data.tx_lpwebtvcreator_videoplayerwithdetail = {};
		data.tx_lpwebtvcreator_videoplayerwithdetail.idVideo = videoId;
		var ajaxUrl = $(".videoPlayer").eq(0).attr("ajaxViewUpdate");
		$.ajax({
			url : ajaxUrl,
			data: data,
			success : function(responseData){
				if(responseData.success) self.altranVideosView.push(videoId);
			}
		});
	},
	setFlashDiaporama : function()
	{
		var allDiapos = $(".diaporamaFlash");
		var params = {
			allowFullScreen:"true",
			menu: "false",
			scale: "noScale",
			wmode: "transparent"
		};
		$.each(allDiapos,function(i, diapoContainer){
			var albumId = $(diapoContainer).attr("albumId");
			var containerId = $(diapoContainer).attr("id");
			var zoomText = $(diapoContainer).attr("zoomText");
			var flashvars = {
				sessionId:1,
				userId:1,
				albumId:parseInt(albumId),
				zoomText:zoomText,
				gateway:'/?type=900'
			};
			if(swfobject.hasFlashPlayerVersion("9.0"))
			{
				swfobject.embedSWF( "/typo3conf/ext/lp_altran/Resources/Public/swf/Diaporama.swf", containerId, "490", "250", "9.0.0", "/typo3conf/ext/lp_webtvcreator/Resources/Public/swf/video/player/install/expressInstall.swf", flashvars, params );
			}

		
		});
	},

	setVideoCoverflow : function()
	{
		var allItems = $(".videoCoverFlow");
		var params = {
			allowFullScreen:"true",
			menu: "false",
			scale: "noScale",
			wmode: "transparent"
		};
		$.each(allItems,function(i,coverFlowContener){
			var coverFlowId = $(coverFlowContener).attr("id");
			var cObId = parseInt(coverFlowId.replace("videoCoverFlow_",""));
			var flashvars = {
				sessionId : 1,
				userId : 1,
				albumId : parseInt(cObId),
				gateway : '/?type=900'
			};
			if(swfobject.hasFlashPlayerVersion("9.0"))
			{
				swfobject.embedSWF( "/typo3conf/ext/lp_webtvcreator/Resources/Public/swf/video/diapo/Diaporama_sans_liens.swf", coverFlowId, "490", "250", "9.0.0", "/typo3conf/ext/lp_webtvcreator/Resources/Public/swf/video/player/install/expressInstall.swf", flashvars, params );
			}
		
		});

	},

	setVideoDetailsAccordeon : function()
	{
		$("#accordion1").accordion({
			active: 1 ,
			'autoHeight' : false,
			//'fillSpace' : true
			'clearStyle' :true
		});
	},
	
	setPopupVideo : function()
	{
		var allVideos = $(".showInPopup");
		var self = this;
		allVideos.bind("click",function(e){
			//$("#popupContent").remove();
			$("body").append("<div id='popupContent'></div>");
			isAppleMobileDevice = $(this).hasClass("html5Player");
			//$("#popupContent").altranDialog("destroy");
			var videoId =  $(this).attr("videoid");
			var videoTitle = $(this).attr("videotitle");
			var closeCaption = $(".videoClose").eq(0).text();
			if(isAppleMobileDevice)
			{
				var openCallback = self.initHtml5Player.call(this,videoId,videoTitle);
			}
			else
			{
				var openCallback = self.initPopupPlayer.call(this,videoId, videoTitle);
			}
			$("#popupContent").altranDialog({
				modal:true,
				title: videoTitle,
				minWidth:495,
				closeText:closeCaption,
				open : openCallback
			});
		});
	},
	setPopupFlash : function()
	{
		var allVideos = $('.flashInPopup');
		if(allVideos.length > 0){
			$("body").append("<div id='flashPopin'><div id='flash'></div>");
			
			//add active zone to click over the flash in IE7 and IE8
			allVideos.each(function(i,el){
				//zone_activeHeight = 200;
				//zone_activeHeight = $(el).height();
				$(el).prepend('<div class="zone_active" style="height:'+zone_activeHeight+'px"></div>');
			});
		}
		
		allVideos.bind("click",function(e){        
			flashTitle = $(this).attr("flashtitle");
			flashWidth = $(this).attr("flashWidth");
			flashHeight = $(this).attr("flashHeight");
			flashPath = $(this).attr("flashPath");
			closeCaption = $(".videoClose").eq(0).text();
			flashvars = jQuery.parseJSON($(this).children(".flashvars").html());
			if(swfobject.hasFlashPlayerVersion("9.0"))
			{
				var params = {
					allowFullScreen:"true",
					menu: "false",
					scale: "noScale",
					wmode: "transparent"
				};
				swfobject.embedSWF( flashPath, "flash", flashWidth, flashHeight, "9.0.0", "/typo3conf/ext/lp_webtvcreator/Resources/Public/swf/video/player/install/expressInstall.swf", flashvars, params );
				$("#flashPopin").dialog({
					modal:true,
					title: flashTitle,
					width:parseInt(flashWidth)+parseInt(2),
					closeText:closeCaption,
					position:['center',0]
				});
			}
            
		});
		$("body").delegate(".ui-widget-overlay","click",function(e){
			$("#flashPopin").dialog( "close" );
		});
		
	},

	setStructureSlideshow: function() {
		// -- hide all implantations
		$($("ul.entities-implantations>li")).hide();
		// -- select first entity
		$("ul#entities-carousel li:first div.pictureBox").addClass("selected");
		// -- display first entity implantations
		$($("ul.entities-implantations").children().get(0)).show();
		// -- add onclick event to entities image a
		$("ul#entities-carousel li div.pictureBox div.imgBox a").click(
			function() {
				// -- remove selected to all pictureBox
				$("div.pictureBox").removeClass("selected");
				// -- add selected class to clicked pictureBox
				$(this).parents("div.pictureBox").addClass("selected");
				// -- hide all entities implantations
				$("ul.entities-implantations>li").hide();
				// -- show entity implantation li matching current entity li index
				$($("ul.entities-implantations").children().get($("ul#entities-carousel li").index($(this).parents("li")))).show();
			}
			);

		// -- create carousel
		var jCarouselOptions = new Object();
		if ($("ul#entities-carousel li").length <= 3) {
			jCarouselOptions.buttonPrevHTML = null;
			jCarouselOptions.buttonNextHTML = null;
		}
		$(".tabCol:eq(1)").click(function(){
			$("ul.jcarousel-skin-altran").jcarousel(jCarouselOptions);
		});
		$("div.contentTab2").hide();
	},

	setSearchBoxBehavior: function() {
		var searchInput = $("input#inputSearch");
		jQuery.data(searchInput, "cleaned", false)
		if (searchInput) {
			searchInput.bind("focus", function(e) {
				if (!jQuery.data(this, "cleaned")) {
					$("input#inputSearch").val("");
					jQuery.data(this, "cleaned", true);
				}
			});
		}
	},

	setHeaderPromo: function(blocId, animPerso){
		if(swfobject.hasFlashPlayerVersion("9.0")){
			if(animPerso == '') animPerso = '/fileadmin/templates/main/flash/anim_perso.swf';
			swfobject.embedSWF(
				'/fileadmin/templates/main/flash/bandeau.swf',
				'headpieceData',
				"100%",
				320,
				"9.0",
				'/fileadmin/templates/main/js/expressInstall.swf',
				{
					blocId: blocId,
					animPerso: animPerso,
					gateway: "/?type=900%26L="+sys_language_uid
				},
				{
					menu: "false",
					scale: "noScale",
					wmode: "transparent"
				}
				);
		}else{
			$("#headerPromo .framesGallery li").each(function(i, el){
				if(i==0) $(el).addClass("selected");
				$(el).attr("itempos", i);
				supertitle = $(el).find(".supertitle").text();
				title = $(el).find(".title").text();
				thumbnail = $(el).find("img").attr("thumbsrc");
				item = "<li><div class=\"galleryThumbnail\"><img src=\""+thumbnail+"\"></div><div class=\"caption\"><strong>"+supertitle+"</strong>"+title+"</div></li>";
				$("#headerPromo .navigationGallery").append(item);
			});
			$("#headerPromo .navigationGallery li").each(function(i, el){
				$(el).click(function(elt){
					$("#headerPromo .framesGallery li").removeClass("selected");
					$("#headerPromo .framesGallery li[itempos='"+i+"']").addClass("selected");
				})
			});
			$.extend($.fn.jScrollPane.defaults, {
				showArrows:true
			});
			$('div.withSroll ul.navigationGallery').jScrollPane({
				scrollbarWidth:9,
				scrollbarMargin:0
			});
		}
	},

	initPopupPlayer : function(videoId, videoTitle)
	{
		var videoId = parseInt(videoId);
		var videoTitle = videoTitle;
		return function(e){
			var params = {
				allowFullScreen:"true",
				menu: "false",
				scale: "noScale",
				wmode: "transparent"
			};
			var flashvars = {
				playerURL : "/typo3conf/ext/lp_webtvcreator/Resources/Public/swf/video/player/player.swf",
				playerClassRef : "org.coreplayer.view.components.CorePlayer",
				controlsURL : "/typo3conf/ext/lp_webtvcreator/Resources/Public/swf/video/player/controls.swf",
				skinURL : "/typo3conf/ext/lp_webtvcreator/Resources/Public/swf/video/player/skin.swf",
				accessibilityURL : '/typo3conf/ext/lp_webtvcreator/Resources/Public/swf/video/player/accessibility.xml',
				sessionId : 1,
				userId : 1,
				videoId : videoId,
				playHandler : "altran.updateView",
				gatewayURL : '/?type=900'

			};
			if(swfobject.hasFlashPlayerVersion("9.0"))
			{
				swfobject.embedSWF( "/typo3conf/ext/lp_webtvcreator/Resources/Public/swf/video/player/preloader.swf", "popupContent", "490", "333", "9.0.0", "/typo3conf/ext/lp_webtvcreator/Resources/Public/swf/video/player/install/expressInstall.swf", flashvars, params );
			}
		}
	},

	initHtml5Player : function(videoId, videoTitle)
	{
		var videoId = parseInt(videoId);
		var videoTitle = videoTitle;
		return function(e)
		{
			var videoC = $("#html5Video_"+videoId).clone().attr({
				width:490,
				height:333,
				controls:'controls'
			});
			/*event listener*/
			var videoObject = $(videoC).get(0);
			videoObject.addEventListener("play",function(){
				altran.updateView(videoId);
				return false;
			}, false);

			$("#popupContent").append(videoC);
		}

	},


	widgets: {
		slideshow: {
			// default options
			options: {

			},
			slides: [],
			current: 1,
			_create: function(){
				myself = this;
				this.element.find(".homeTabContainer li.tab").each(function(i, tab){
					myself._setTab(i, tab);
				});
			},
			_setTab: function(i, tab){
				$(tab).children("a").click({
					widget: this,
					tab: tab
				},this._tabClicked);
				if(i==0) $(tab).children("a").click();
			},
			_tabClicked: function(e){
				e.data.widget.slides = [];
				// Display clicked tab as selected
				$(e.data.tab).siblings("li").removeClass("selected");
				$(e.data.tab).addClass("selected");
				// Init slideshow with good content
				e.data.widget.element.find(".tabContent .slideshowArea").html($(e.data.tab).find(".slideshowArea").html());
				e.data.widget.element.find(".tabContent .slideshowArea .pictureBox").each(function(i, el){
					e.data.widget.slides.push(el)
				});
				e.data.widget.element.find(".tabContent .slideshowArea .pictureBox").remove();
				e.data.widget._moveTo(1);
				// Init arrows
				e.data.widget.element.find(".tabContent .slideshowArea .btnPrev").click({
					widget: e.data.widget,
					tab: e.data.tab
				}, e.data.widget._prevArrowClicked);
				e.data.widget.element.find(".tabContent .slideshowArea .btnNext").click({
					widget: e.data.widget,
					tab: e.data.tab
				}, e.data.widget._nextArrowClicked);
				return false;
			},
			_prevArrowClicked: function(e){
				e.data.widget._moveTo(e.data.widget.current - 1);
			},
			_nextArrowClicked: function(e){
				e.data.widget._moveTo(e.data.widget.current + 1);
			},
			_thumbnailClicked: function(e){
				e.data.widget._moveTo(e.data.pos);
			},
			_moveTo: function(newPos){
				if (newPos < 0) newPos = this.slides.length - 1;
				if(newPos > this.slides.length - 1) newPos = 0;
				this.current = newPos;

				if (this.current - 1 < 0) first = this.slides.length - 1; else first = this.current - 1;
				if(this.current + 1 > this.slides.length - 1) last = 0; else last = this.current + 1;

				$(this.slides).removeClass("selected");
				$(this.slides[this.current]).addClass("selected");

				var container = this.element.find(".tabContent .slideshowArea .slideshowPictures .pictureBoxes");
				container.html(this.slides[first]);
				container.append(this.slides[this.current]);
				container.append(this.slides[last]);
				container.find(".imgBox:eq(0)").click({
					widget: this,
					pos: first
				}, this._thumbnailClicked);
				container.find(".imgBox:eq(2)").click({
					widget: this,
					pos: last
				}, this._thumbnailClicked);
			},
			destroy: function(){
				$.Widget.prototype.destroy.apply(this, arguments);
			}
		}
	}
}

var MainMenuManager = {

	options : {
		mainNavID : "mainNav",
		itemClass : "btnNav",
		firstItem : "firstItem",
		subNavClass : "subNav",
		subNavColClass : "subNavCol",
		subMainClass : "subNavContent",
		grayColClass : "subNavColGrey",
		colMaxSize : "subNav5Col"
	},

	init : function(userOptions){
		if(!userOptions) userOptions = {};
		this.options = $.extend(this.options,userOptions);
		this.o = this.options;
		this.bindEvents();
	},

	handleClickedMenuItem : function(e){
		var isFirstItem = this.isFirstItem(e);
		if(isFirstItem) return false; //first Item
		/*otherwhise*/
		this.fixMenuSize(e);
	},

	bindEvents : function(){
		var selectedField = "#"+this.o.mainNavID +" a."+this.o.itemClass;
		$(selectedField).bind("mouseover",$.proxy(this.handleClickedMenuItem, this));
	},

	isFirstItem : function(e){
		var mainTarget = e.currentTarget;
		var parent = $(mainTarget).parent(".firstItem");
		return parent.length;
	},

	fixMenuSize : function(e){
		var mainTarget = e.currentTarget;
		var isAlreadyFixed = $(mainTarget).data("alreadyFixed");
		if(isAlreadyFixed==1) return false; //fix once

		$(mainTarget).data("alreadyFixed",1);
		var menuItemContainer = $(mainTarget).next("."+this.o.subNavClass).css({
			left:""
		});
		var subNavContent = $(menuItemContainer).find("."+this.o.subMainClass);
		var topCol = $(subNavContent).children("."+this.o.subNavColClass).length;
		var bottomCol = $(menuItemContainer).find("."+this.o.grayColClass+" ."+this.o.subNavColClass).length;
		var mainColNb = Math.max(topCol,bottomCol);
		mainColNb = (mainColNb > 0) ? mainColNb : 0;
		var newItemClass = (mainColNb < 6) ? "subNav"+mainColNb+"Col" : this.o.colMaxSize;
		/*fix size subNav4Col*/
		$(menuItemContainer).removeClass("subNavFullWidth");
		$(subNavContent).addClass(newItemClass);
		this.calculatePosition(mainTarget, subNavContent);
	},

	calculatePosition : function(mainTarget,subnavContent){
		/*si la taille de la boite est supérieure à la longueur de la nav - longueur de la nav au point cliqué - compenser -left  */
		/*offset : relatif au document*/
		var mainNavleft = $("#"+this.o.mainNavID).offset().left;
		var mainNavWidth = $("#"+this.o.mainNavID).width(); //935
		var navItemLeft = $(mainTarget).offset().left;
		var subNavWidth = $(subnavContent).width();
		/*available*/
		var availableSpace = mainNavWidth - (navItemLeft - mainNavleft);
		if(subNavWidth > availableSpace)
		{
			var newLeft = subNavWidth - availableSpace - 25;
			$(subnavContent).parent(".subNav").css({
				left:"-"+newLeft+"px"
			});
		}
	}
};

var DiaporamaManager = {
    
	options : {
		prevBtnCls : "btnPrev",
		nextBtnCls : "btnNext",
		imgContainer : "imageContainer",
		imgDataContainer : "imgData",
		imgItemClass : "pictureBox",
		downloadList : "downloadList",
		minItem : 3,
		enableLightbox : true,
		lightBoxClass : "enableLightBox",
		linkMoreDownloadClass : "linkMoreDownload",
		lightBoxSettings : {
			imageLoading: '/fileadmin/templates/main/img/lightBox/lightbox-ico-loading.gif',
			imageBtnPrev: '/fileadmin/templates/main/img/lightBox/lightbox-btn-prev.gif',
			imageBtnNext: '/fileadmin/templates/main/img/lightBox/lightbox-btn-next.gif',
			imageBtnClose: '/fileadmin/templates/main/img/lightBox/lightbox-btn-close.gif',
			imageBlank: '/fileadmin/templates/main/img/lightBox/lightbox-blank.gif'
		}
	},
	widgetKey : null,
	currentPage : 1,
	selectedItem : 2,
	imgData: [],
	_init : function(){},

	_create: function(){
		this.o = this.options;
		this.el = this.element;
		/*setwidgetKey*/
		this.widgetKey = Math.floor(Math.random()*101531);
		/*data*/
		this.imgData = eval($(this.el).find(" ."+this.o.imgDataContainer).val());

		/*masquer la pagination*/
		if((this.imgData) && this.imgData.length < 2)
		{
			$(this.el).find("."+this.o.prevBtnCls).hide();
			$(this.el).find("."+this.o.nextBtnCls).hide();
		}
      
		/*updateImagePath*/
		this.updateImgPath();

		/*updateIds*/
		this.updateImgsId();

		/*lightBox*/
		if(this.o.enableLightbox) this.initLightBox();

		/*events*/
		this.bindEvents();
	},
	_setOption: function( key, value ) {
		this.options[key] = value;
		this._super( "_setOption", key, value );
	},


	updateImgPath : function(){
		var self = this;
		var links = $(this.el).find("."+this.o.lightBoxClass);
		$.each(links,function(i,link){
			var newMainImgPath = $(link).find(".resizedMainPhoto").attr("src");
			//update link path
			$(link).attr("href",newMainImgPath);
		});
	},

	zoom: function(image, path)
	{
		if(path=="false") return;
		/*videoCoverflow*/
		var videoUriPattern = /::videoCoverflow/;
		var isVideo = videoUriPattern.test(path);
		if(isVideo)
		{
			this.goToVideo(path);
			return;
		}
		/*album coverflow*/
		jQuery('<a class="enableFlashLightBox" title="'+image+'" href="'+path+'"></a>').appendTo("body");
		this.initFlashLighBox();
		$(".enableFlashLightBox").trigger("click");
		/*remove the close btn*/
		$("#lightbox-secNav-btnClose").attr("href","javascript:;").find("img").remove();
	},

	goToVideo : function(videoUri)
	{
		var videoUri = videoUri.replace("::videoCoverflow","");
		var videoDetails = $(".videoDetailsLinks").eq(0).attr("href");
		if(videoDetails.length==0) return;
		var videoDetailsLink = videoDetails.replace(".html","/title/"+videoUri+".html");
		document.location.href = "/"+videoDetailsLink;
	},

	initFlashLighBox : function()
	{
		$(".enableFlashLightBox").lightBox({
			imageLoading: '/fileadmin/templates/main/img/lightBox/lightbox-ico-loading.gif',
			imageBtnPrev: '/fileadmin/templates/main/img/lightBox/lightbox-btn-prev.gif',
			imageBtnNext: '/fileadmin/templates/main/img/lightBox/lightbox-btn-next.gif',
			imageBtnClose: '/fileadmin/templates/main/img/lightBox/lightbox-btn-close.gif',
			imageBlank: '/fileadmin/templates/main/img/lightBox/lightbox-blank.gif',
			closeCallback: function(){
				$(".enableFlashLightBox").remove();
			}
		});
	},


	initLightBox : function()
	{
		var items = $(this.el).find("."+this.o.lightBoxClass);
		$(this.el).find("."+this.o.lightBoxClass).lightBox(this.o.lightBoxSettings);
	},

	updateImgsId : function()
	{
		var self = this;
		var images = $(this.el).find("."+this.o.imgItemClass);
		$.each(images,function(i,imgItem){
			var oldKey = parseInt($(imgItem).attr("id").replace("pic_","")); //ne lancer qu'une fois
			$(imgItem).attr("id","pic_"+self.widgetKey+"_"+oldKey);
		});

	},

	bindEvents : function(){
		$(this.el).find("."+this.o.prevBtnCls).bind("click",$.proxy(this.prevBtnHandler,this));
		$(this.el).find("."+this.o.nextBtnCls).bind("click",$.proxy(this.nextBtnHandler,this));
		/*click on item*/
		$(this.el).find("."+this.o.imgItemClass).bind("click", $.proxy(this.clickOnImgHandler,this));
        
	},
	prevBtnHandler : function(e)
	{
		this.currentPage = this.currentPage - 1;
		var nextItems = this.getNextItems();
		this.showItems(nextItems);
		return false;
	},
	nextBtnHandler : function(e)
	{
		this.currentPage = this.currentPage + 1;
		var nextItems = this.getNextItems();
		this.showItems(nextItems);
		return false;
	},
	clickOnImgHandler : function(e)
	{
		if($(e.target).hasClass("linkMoreDownload")) return true;
		if(!this.o.enableLightbox) return true;
		var selectedImgId = parseInt($(e.currentTarget).attr("id").replace("pic_"+this.widgetKey+"_",""));
		this.showItemLinks(selectedImgId);
		return false;
	},

	getNextItems : function()
	{
		var nextPage = (this.currentPage > this.imgData.length)? 1: (this.currentPage <= 0)? this.imgData.length : this.currentPage;
		var nextItems = this.imgData[nextPage-1];
		this.currentPage = nextPage;
		return nextItems;
	},

	showItems : function(itemsToShow){
		//masquer toutes les images
		var self = this;
		this.hideAllImages();
		//afficher les image de la page suivante
		$.each(itemsToShow,function(i,picData){
			var itemsClass = i+1;
			var items = $("#pic_"+self.widgetKey+"_"+picData.uid);
			$("#pic_"+self.widgetKey+"_"+picData.uid).addClass("pictureBox"+itemsClass).show();
			if(itemsClass == 2){
				self.showItemLinks(picData.uid);
			}
		});
	},

	showItemLinks : function(selectedImgId)
	{
		/*masquer la selection précédente et picture legende*/
		$(this.el).find("#pic_"+this.widgetKey+"_"+this.selectedItem).removeClass("selected");
		$(this.el).find(".pictureLegend").hide();
		$(this.el).find("."+this.o.downloadList).hide();
		$(this.el).find("#downloadList_"+selectedImgId).show();
		$(this.el).find("#pic_"+this.widgetKey+"_"+selectedImgId).addClass("selected");
		/*show legend*/
		$("#pic_"+this.widgetKey+"_"+selectedImgId +" .pictureLegend").show();
		this.selectedItem = selectedImgId;
	},

	hideAllImages : function(){
		$(this.el).find("."+this.o.imgContainer+" ."+this.o.imgItemClass).removeClass("pictureBox1 pictureBox2 pictureBox3");
	}


};


var RateManager = {
	url : null,
	currentEl : null,
	options :{
		readOnlyRateClass : "readOnlyRate",
		readOnlyItemClass : "voteStar",
		rateAllowedClass : "enableRate",
		normalItemClass : "voteStar"
	},

	init : function(initOptions){
		this.options = $.extend(this.options,initOptions);
		this.o = this.options;
		this.enableReadOnlyRate();
		this.enableRate();
	},

	enableReadOnlyRate : function(){
		var allEls = $("."+this.o.readOnlyRateClass);
		var self = this;
		$.each(allEls,function(i,el){
			var itemId = $(el).attr("id");
			$("#"+itemId +" ."+self.o.readOnlyItemClass).rating({
				'readOnly':true
			});
		});
	},
	enableRate : function(){
		var allEls = $("."+this.o.rateAllowedClass);
		var self = this;
		$.each(allEls,function(i,el){
			var itemId = $(el).attr("id");
			var videoId = $(el).attr("videoid");
			var ajaxUrl = $(el).attr("ajaxUrl");
			var updateRateFunc = self.updateRate.call(self,videoId,ajaxUrl,el);
			$("#"+itemId +" ."+self.o.normalItemClass).rating({
				callback : updateRateFunc
			});
		});
	},
	handlerVote : function(response){
		if(!response) return false;
		var mainContainer = $(this.currentEl).parents("."+this.o.rateAllowedClass);
		var itemId = $(mainContainer).attr("id");
		var currentRate = $(mainContainer).attr("currentRate");
		var currentVote = parseInt($(mainContainer).find(".voteCtn").html());
		if(response.message.length != 0){
			//alert(response.message);
			$("#"+itemId +" ."+this.o.normalItemClass).rating("select",parseInt(currentRate));
		}else{
			$(mainContainer).find(".voteCtn").html(currentVote + 1);
		}
		$("#"+itemId +" ."+this.o.normalItemClass).rating("readOnly");
		return false;
	},

	updateRate : function(videoId, ajaxUrl,mainEl)
	{
		var videoId = videoId;
		var ajaxUrl = ajaxUrl;
		var mainEl = mainEl;
		var self = this;
		return function(userRate, el){
			var mainContainer = mainEl;
			if($(mainContainer).data('hasVoted')==1) return;
			$(mainContainer).data('hasVoted',1);
			self.currentEl = el;
			self.rateVideo(userRate,videoId, ajaxUrl);
		}
	},

	rateVideo : function(userRate,videoId,ajaxUrl){
		var self = this;
		var data = {};
		data.tx_lpwebtvcreator_videoplayerwithdetail = {};
		data.tx_lpwebtvcreator_videoplayerwithdetail.userRate = userRate;
		data.tx_lpwebtvcreator_videoplayerwithdetail.idVideo = videoId;

		$.ajax({
			url : ajaxUrl,
			data :data,
			success : $.proxy(self.handlerVote,self)
		});
	}
};



$(document).ready(function(){
	altran.load();
	MainMenuManager.init();
	RateManager.init();
});

/**
 * pretty Date
 * http://ejohn.org/files/pretty.js
 */
altran.prettyDate = {

	options :{
		prettyDateCls:'prettyDate',
		now :"Just now",
		oneMinuteAgo :"1 minute ago",
		oneHourAgo :"1 hour ago",
		yesterday :"YesterDay",
		daysAgo :"days ago",
		minutesAgo : "minutes ago",
		hoursAgo :"hours ago",
		weeksAgo :"weeks ago",
		prefix :""
	},

	init : function(userOptions){

		this.options = $.extend(this.options, userOptions);
		this.options.now = $("#"+this.options.now).html();
		this.options.oneMinuteAgo = $("#"+this.options.oneMinuteAgo).html();
		this.options.oneHourAgo = $("#"+this.options.oneHourAgo).html();
		this.options.yesterday = $("#"+this.options.yesterday).html();
		this.options.daysAgo = $("#"+this.options.daysAgo).html();
		this.options.minutesAgo = $("#"+this.options.minutesAgo).html();
		this.options.hoursAgo = $("#"+this.options.hoursAgo).html();
		this.options.weeksAgo = $("#"+this.options.weeksAgo).html();
		this.options.prefix = $("#"+this.options.prefix).html();

		this.o = this.options;
		var self = this;
		this.initPrettyDate();

		setInterval(function(){
			self.initPrettyDate();
		},10000);
	},

	initPrettyDate : function(){
		var self = this;
		var els = $("."+this.o.prettyDateCls);
		$.each(els,function(i, el){
			var prettyDate = self.prettyDate($(el).attr("title"));
			$(el).html(prettyDate);
		});
	},

	prettyDate : function(time){
		var messages = this.o;
		var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
		diff = (((new Date()).getTime() - date.getTime()) / 1000),
		day_diff = Math.floor(diff / 86400);
		if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
			return;

		return day_diff == 0 && (
			diff < 60 && messages.now ||
			diff < 120 && messages.oneMinuteAgo ||
			diff < 3600 && messages.prefix+' '+Math.floor( diff / 60 ) + ' '+messages.minutesAgo ||
			diff < 7200 && messages.oneHourAgo ||
			diff < 86400 && messages.prefix+' '+Math.floor( diff / 3600 ) + ' '+messages.hoursAgo) ||
		day_diff == 1 && messages.yesterday ||
		day_diff < 7 && messages.prefix+' '+day_diff + " "+messages.daysAgo ||
		day_diff < 31 && messages.prefix+' '+Math.ceil( day_diff / 7 ) + " "+messages.weeksAgo;
	}




};

altran.dialog = {
	blueTemplate : "<div classs='blueTemplate'></div>",
	yellowTemplate : '<div class="popupContainer">'
	+'<div class="popupHeader"><p class="altranDialogTitle">Title</p><a class="btnClose" href="javascript:;">Fermer</a></div>'
	+'<div class="popupContent">'
	+'</div>'
	+'</div>',

	overlay : "<div class='popupBackground'></div>",
	overlayCss : {
		position : "fixed",
		top : 0,
		left : 0,
		width : '100%',
		height: '100%',
		opacity : '0.5',
		zIndex : '10000'
	},

	isOpen : false,

	options : {
		enableResize : true,
		enableDraggable : true,
		maxHeight : 100,
		maxWidth : 100,
		minWidth: 100,
		minHeight : 100,
		modal : true,
		closeText : "Close",
		title :"popup title"
	},

	_create : function(){
		
		var options = this.options;
		var yellowTemplate = $(this.yellowTemplate).clone();
		yellowTemplate.find(".altranDialogTitle").html(options.title);
		yellowTemplate.find(".btnClose").html(options.closeText);
		this.uiDialog = yellowTemplate;
		$(yellowTemplate).find(".popupContent").css({
			padding:'2px'
		}).append(this.element)
		$(yellowTemplate).hide();
		$("body").append(yellowTemplate);
		/*bindEvents*/
		this._bindEvents();
		if(options.enableResize) $(yellowTemplate).resizable();
		if(options.enableDraggable) $(yellowTemplate).draggable({
			handle :'.popupHeader',
			cursor:'pointer'
		});
	},
	_init : function(){
		//console.log("inside init");
		if(!this._isOpen()) this.open();
	},

	open : function(){
		var options = this.options;
		if(options.modal){
			var screenHeight = $(document).height();
			this.overlay = $(this.overlay).css({
				height:screenHeight+"px"
			});
			$("body").append($(this.overlay));
		}
		var position = this._getDialogPosition();
		this.uiDialog.css({
			height : options.minHeight+'px',
			width : options.minWidth+'px',
			top : position.top,
			left : position.left,
			position: "absolute"
		}).show();
		this.isOpen = true;
		this._trigger("open",{
			ui : this.uiDialog
		});
	},
	
	_getDialogPosition : function()
	{
		/*permet de centrer*/
		var options = this.options;
		var height = options.minHeight;
		var width = options.minWidth;
		var windowWidth = document.documentElement.clientWidth;
		var windowHeight = document.documentElement.clientHeight;
		var popupHeight = height;
		var popupWidth = width;
		var top = windowHeight/2-popupHeight/2;
		var left = windowWidth/2-popupWidth/2;
		var scrollTop = (document.documentElement && document.documentElement.scrollTop) || window.pageYOffset || self.pageYOffset || document.body.scrollTop;
		var scrollLeft = (document.documentElement && document.documentElement.scrollLeft) || window.pageXOffset || self.pageXOffset || document.body.scrollLeft;
		left = left + scrollLeft;
		top = top + scrollTop;

        
		var position = {};
		position.top = top;
		position.left = left;
		return position;
	},

	_isOpen : function(){
		return  this.isOpen;
	},

	_bindEvents : function(){
		this.uiDialog.find(".btnClose").bind("click",$.proxy(this._close,this));
	},

	_close : function(){
		var options = this.options;
		this.uiDialog.hide();
		this.isOpen = false;
		if(options.modal) $(this.overlay).hide();
		//this._trigger("close");
		$(this.uiDialog).remove();
		$(this.overlay).remove();
	},

	destroy : function()
	{
        
	/*var self = this;
        self.uiDialog.unbind(".bntClose");
        $(self.uiDialog).remove();
        $(self.overlay).remove();*/
	}
};

/*commentManager*/
altran.commentsManager = {

	options :{
		newCommentCls : "addNewComment",
		relatedCommentCls : "addRelatedComment",
		commentItemCls : "commentItem",
		templateId : "commentTemplate",
		ajaxFieldId : "commentAjaxUrl",
		commentEditorId : "commentEditor",
		mainContainerId :"mainContainerComment",
		saveCommentBtn : "commentSubmitBtn",
		cancelCommentBtn : "commentCancelBtn",
		editFieldCls :"editField",
		editorFields : [{
			id:"commentNameField",
			check:"notEmpty"
		},{
			id:"commentEmailField",
			check:"email"
		},{
			id:"commentContentField",
			check:"notEmpty"
		}]
	},
	ajaxUrl : null,
	commentTemplate : null,
	editorTemplate : null,
	videoId : null,
	emailPattern : /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/,
	pCommentId : 0,

	init : function(userOptions){
		this.options = $.extend(userOptions,this.options);
		this.o = this.options;

		/*set ajaxUrl*/
		this.ajaxUrl = $('.commentsVideo:first').attr(this.o.ajaxFieldId);

		/*set commentTemplate*/
		this.commentTemplate = $("#"+this.o.templateId).clone();

		/*set commentEditorId*/
		this.editTemplate = $("#"+this.o.commentEditorId).clone();
		$("#"+this.o.commentEditorId).remove();

		/*clearFieldIfErrors*/
		$("."+this.o.editFieldCls).live("click",function(e){
			$(this).removeClass("fieldError");
		});

		/*set videoId*/
		this.videoId = $('.commentsVideo:first').attr("videoId");
		this.bindEvents();
	},
	bindEvents : function(){
		var self = this;
		$("."+this.o.relatedCommentCls).live('click',$.proxy(this.handleNewRelatedComment,this));
		$("."+this.o.newCommentCls).live('click',$.proxy(this.handleNewComment,this));
		$("#"+this.o.saveCommentBtn).live('click',$.proxy(this.saveComment,this));
		$("#"+this.o.cancelCommentBtn).live('click',function(e){
			if($("#editorCnt")) $("#editorCnt").html("");
			if($("#commentEditor")) $("#commentEditor").remove();
		});
	},

	checkFields : function(){
		var errors = [];
		var self = this;
		$.each(this.o.editorFields,function(i,field){
			if(field.check=="notEmpty")
			{
				var fieldVal = $("#"+field.id).val();
				if(fieldVal=="") errors.push({
					field:field.id,
					msg:""
				});
			}
			if(field.check=="email")
			{
				var emailVal = $("#"+field.id).val();
				if(self.emailPattern.test(emailVal) == false) errors.push({
					field:field.id,
					msg:""
				});
			}

		});
		return errors;
	},
	showErrors : function(errors)
	{
		$.each(errors,function(i,error){
			$("#"+error.field).addClass("fieldError");
		});
	},
	saveComment : function(e){
		/*check fields*/
		var errors = this.checkFields();
		if(errors.length >0){
			this.showErrors(errors);
			return false;
		}
		var self = this;
		var pCommentId =  this.pCommentId;
		data = {};
		data.tx_lpwebtvcreator_videoplayerwithdetail = {};
		data.tx_lpwebtvcreator_videoplayerwithdetail.idVideo = this.videoId;
		data.tx_lpwebtvcreator_videoplayerwithdetail.pCommentId = pCommentId;
		data.tx_lpwebtvcreator_videoplayerwithdetail.name = $("#commentNameField").val();
		data.tx_lpwebtvcreator_videoplayerwithdetail.email = $("#commentEmailField").val();
		data.tx_lpwebtvcreator_videoplayerwithdetail.content = $("#commentContentField").val();

		/*unbind once button clicked*/
		$("#"+this.o.saveCommentBtn).die();

		$.ajax({
			url : this.ajaxUrl,
			data : data,
			success : function(response){
				if(response.success)
				{
					if(pCommentId==0)
					{
						$("#editorCnt").before(response.comment);
						$("#editorCnt").html("");
					}
					else{
						$("#commentEditor").replaceWith(response.comment);
					}
					var currentNbCommentVal = parseInt($("#commentNb").html());
					$("#commentNb").html(currentNbCommentVal+1);
				}

			}
		});

	},

	showEditor : function(e){
		$("#"+this.o.saveCommentBtn).die().live('click',$.proxy(this.saveComment,this));
		this._cleanEditorsFields();
		if(!e){
			this.pCommentId = 0;
			$("#editorCnt").html("").append($(this.editTemplate).show());
		}
		else{
			var pCommentId = $(e.currentTarget).parents(".commentItem").attr("id");
			pCommentId = parseInt(pCommentId.replace("comment_",""));
			this.pCommentId = pCommentId;
			$(e.currentTarget).parents(".commentItem").after($(this.editTemplate).attr("pCommentId",pCommentId).show());
		}
	},

	_cleanEditorsFields : function()
	{
		$(this.editTemplate).find("#commentNameField").removeClass("fieldError").val("");
		$(this.editTemplate).find("#commentEmailField").removeClass("fieldError").val("");
		$(this.editTemplate).find("#commentContentField").removeClass("fieldError").val("");
	},

	handleNewRelatedComment : function(e){
		this.showEditor(e);
	},

	handleNewComment :function(e){
		this.showEditor();
	}

};

