(function($) {
    $.fn.mediathequeVideo = function (options) {
        var defaults = {
            width: false,
            heitht: false
        };

        var settings = $.extend(true, defaults, options);

        return this.each(function() {
            var mediatheque = $(this);
            var thematique = $('#thematique', mediatheque);
            var thematiqueCenter = $('#thematiqueCenter', thematique);
            var thematiqueList = $('#thematiqueList', thematiqueCenter);
            var thematiqueVideoList = $('#thematiqueVideoList', thematiqueCenter);
            var videoList = $('#videoList', mediatheque);
            var video = $('#video', mediatheque);
            var ajaxLoader = $("#thematiqueAjaxLoader", thematique);
            var isMoving = false;
            var loadFirstSousThema = true;
            var hasMoved = false;
	    	var currentPid = $("#currentPid");
	    	var currentLanguage = $("#currentLanguage");
			var loadFirstSousList = true;
	    	
	    	initComponents();

            function initComponents()
            {
            	if( currentLanguage.html() == 1 ) {
            		currentLanguage = 'en';
            	} else {
            		currentLanguage = 'fr';	
            	}
            	
                var ajaxLoaderImage = $('#thematiqueAjaxLoaderImage', ajaxLoader);

                ajaxLoader.css({
                    width: thematique.width(),
                    height: thematique.height()

                });
                ajaxLoaderImage.css({
                    marginLeft: thematiqueList.outerWidth(true) + (thematique.width() - thematiqueList.outerWidth(true)) / 2,
                    marginTop: thematique.height() / 2
                })
				
                $.get(currentLanguage+'/presse/mediatheque/mediatheque_ajax/categorie_video/?uid='+currentPid.html(), loadThematique);

                $('#videoHeader #thematiqueLink', mediatheque).click(thematiqueOpen);
                $('#thematiqueHeader #thematiqueFermer', thematique).click(thematiqueClose);
            }
            
            function loadPlayerVideoAndHtml5( videoInformationFlv, videoInformationMp4, videoInformationPoster ) {
		
            	 if (!$.browser.webkit || navigator.userAgent.indexOf("Chrome") != -1) {
                    jwplayer("video").setup({
                            flashplayer: "/typo3conf/ext/uz_tt_news_afvideo/swf/player.swf",
                            file: videoInformationFlv,
                            image: videoInformationPoster,
                            backcolor : "#FFFFFF",
                            width: "679px",
                            height: "382px",
                            skin: "/typo3conf/ext/uz_tt_news_afvideo/swf/skin/glow.zip",
							dock: "true",
							plugins: {
							       "gapro-1": {
							       		"gapro.accountid": "UA-5225712-2"
							       }
							},
                            levels: [
                                    { file: videoInformationFlv },
                                    { file: videoInformationMp4 }
                                ]
                    });
                }else{
				
					$("#video").html('<video src="'+videoInformationMp4+'" type="video/mp4" id="videoHtlm5" controls="controls" poster="'+videoInformationPoster+'" width="680" height="432">');

				}
            	
            	
            }

            function loadThematique(data)
            {
                var thematiqueListContent = $('<div class=\"thematique-list-container\">' + data + '</div>');
                var thematiqueListUp = $('<div class=\"thematique-list-up\"></div>');
                var thematiqueListDown = $('<div class=\"thematique-list-down\"></div>');
                thematiqueList.html('').append(thematiqueListUp).append(thematiqueListContent).append(thematiqueListDown);
                thematiqueListContent.css({
                    height: thematiqueCenter.height() - (thematiqueListUp.height() + thematiqueListDown.height())
                });

                $('li', thematiqueListContent).click(function(){
                    var index = $(this).index() % 2;
					var categorie = $(this).find("p:first").text();
                    $('li.selected', thematiqueListContent).removeClass('selected');
                    $(this).addClass('selected');
					loadFirstSousList = true;
                    $elementClic = $(this);
                    thematiqueVideoList.fadeOut('fast', function(){
                        ajaxLoader.show();                        
						$("h1:eq(1)").text(categorie);
                        $.get(currentLanguage+'/presse/mediatheque/mediatheque_ajax/galerie_video/?uid=' + $elementClic.find('.galerieVideoId').html(), loadThematiqueVideoList);
                    });
                });

                $('.thematique-list-up', thematiqueList).click(thematiqueListScrollUp);
                $('.thematique-list-down', thematiqueList).click(thematiqueListScrollDown);

                if (loadFirstSousThema){
                    $.get(currentLanguage+'/presse/mediatheque/mediatheque_ajax/galerie_video/?uid='+currentPid.html(), function(data){
						loadThematiqueVideoList(data);

						var parametresURL = getUrlVars();
						if(parametresURL['videoId']){
							var videoId = $(".video-list-container ul li .videoId:contains("+parametresURL['videoId']+")");
							var video = videoId.parent();
							var videoIndex = video.index();
							var isVideo = video.length>0;
							if(isVideo){
								//video.trigger("click")
								thematiqueClose();
								loadVisuel(video, videoIndex);
								setTimeout(function(){
									addFacebook(video);
								},1000);
							}else{
								loadVisuel($('.video-list-container ul li:first', videoList), 0);
								setTimeout(function(){
									addFacebook($('.video-list-container ul li:first', videoList));
								},1000);
							}
						}else{
							loadVisuel($('.video-list-container ul li:first', videoList), 0);
							setTimeout(function(){
								addFacebook($('.video-list-container ul li:first', videoList));
							},1000);

						}
					});
                    loadFirstSousThema = false;
                }
            }
			

            function loadThematiqueVideoList(data)
            {
				
                var videoListLi = $('li', data);
                var nbThumbByVisu = 12; //3*4
                var nbPager = Math.ceil(videoListLi.size() / nbThumbByVisu);
                var thematiqueVideoPager = $('<div class="thematique-video-pager"></div>');
                var i;
                for (i = 0; i < nbPager; ++i){
                    var link = $('<a href="#">●</a>')
                    if (i == 0)
                        link.addClass('selected');
                    thematiqueVideoPager.append(link);
                }

				if(loadFirstSousList){
						var thematiqueVideoListContainer = $('<div class="thematique-video-list-containter"></div>');
						var thematiqueVideoListContentUl = $('<div class="thematique-video-list-page"></div>');
						var thematiqueVideoListPage;
						for (i = 0; i < videoListLi.size(); ++i){
							if ((i % nbThumbByVisu) == 0){
								if (i != 0)
									thematiqueVideoListContentUl.append(thematiqueVideoListPage);
								thematiqueVideoListPage = $('<ul class="video-list-page-content"></ul>');
							}

								thematiqueVideoListPage.append($(videoListLi[i]));
						}


					thematiqueVideoListContentUl.append(thematiqueVideoListPage);

					thematiqueVideoListContainer.append(thematiqueVideoListContentUl);
					//$('.video-list-page-content', thematiqueVideoListContainer).css({width: thematiqueVideoList.width()});

					ajaxLoader.hide();
					thematiqueVideoList.html('').append(thematiqueVideoListContainer).append(thematiqueVideoPager);
					thematiqueVideoList.fadeIn('fast');
				}
                
                $('.video-list-page-content li',thematiqueVideoListContainer).click(function(){
					loadFirstSousList = false;
                    thematiqueClose();
                    var index = $(this).index() + ($(this).parent().index() * nbThumbByVisu);
					var isKeyWord = $(this).hasClass("keyWord");
					
					loadVisuelKeyWord($(this), $(this).index());
					
                    return (false);
                })
				
				$('.video-list-page-content li a').click(function(e){e.preventDefault();});
				

                $('.thematique-video-pager a', thematiqueVideoList).click(thematiqueVideoListPager);

				// videos zone
                var videoListContent = $('<div class="video-list-container">' + data + '</div>');
                var videoListUp = $('<div class=\"video-list-up\"></div>');
                var videoListDown = $('<div class=\"video-list-down\"></div>');
                videoList.html('').append(videoListUp).append(videoListContent).append(videoListDown);
				
				loadVisuel($('.video-list-container ul li:first', videoList), 0);
				
                videoListContent.css({
                    height: $("#videoCenter", mediatheque).height() - (videoListUp.height() + videoListDown.height())
                });

                $('.video-list-up', videoList).click(videoListScrollUp);
                $('.video-list-down', videoList).click(videoListScrollDown);

                $('ul', videoList).bind('mousedown', dragAndDrop);
                $('ul li', videoList).click(function(){
					var isKeyWord = $(this).hasClass("keyWord");
					var isPush = $(this).hasClass("push");
					if(!isPush){
						if (!hasMoved){
							loadVisuelKeyWord($(this), $(this).index());
						}
						hasMoved = false;
					}
                    return (false);
                });
				
				$('ul li a', videoList).click(function(e){e.preventDefault();});
				
				var liHeight = 0;
				var videoListLi = $('li', videoList);
				var i = 0;
				for (; i < videoListLi.size(); ++i)
					liHeight += $(videoListLi[i]).outerHeight(true);
				$('ul', videoList).css('height', liHeight);	
				// END videos zone
            }
	
			function loadThematiqueVideoListOnly (data) {
                var videoListLi = $('li', data);
                var nbThumbByVisu = 12; //3*4
                var nbPager = Math.ceil(videoListLi.size() / nbThumbByVisu);
                var thematiqueVideoPager = $('<div class="thematique-video-pager"></div>');
                var i;
                for (i = 0; i < nbPager; ++i){
                    var link = $('<a href="#">●</a>')
                    if (i == 0)
                        link.addClass('selected');
                    thematiqueVideoPager.append(link);
                }

						var thematiqueVideoListContainer = $('<div class="thematique-video-list-containter"></div>');
						var thematiqueVideoListContentUl = $('<div class="thematique-video-list-page"></div>');
						var thematiqueVideoListPage;
						for (i = 0; i < videoListLi.size(); ++i){
							if ((i % nbThumbByVisu) == 0){
								if (i != 0)
									thematiqueVideoListContentUl.append(thematiqueVideoListPage);
								thematiqueVideoListPage = $('<ul class="video-list-page-content"></ul>');
							}

								thematiqueVideoListPage.append($(videoListLi[i]));
						}
					
					if (( (i-1) % nbThumbByVisu) != 0)
					{
						thematiqueVideoListContentUl.append(thematiqueVideoListPage);
					}
					thematiqueVideoListContainer.append(thematiqueVideoListContentUl);
					//$('.video-list-page-content', thematiqueVideoListContainer).css({width: thematiqueVideoList.width()});

					ajaxLoader.hide();
					thematiqueVideoList.html('').append(thematiqueVideoListContainer).append(thematiqueVideoPager);
					thematiqueVideoList.fadeIn('fast');
                
                $('.video-list-page-content li',thematiqueVideoListContainer).click(function(){
					loadFirstSousList = false;
                    thematiqueClose();
                    var index = $(this).index() + ($(this).parent().index() * nbThumbByVisu);
					var isKeyWord = $(this).hasClass("keyWord");
					
					loadVisuelKeyWord($(this), $(this).index());
					
                    return (false);
                })
				
				$('.video-list-page-content li a').click(function(e){e.preventDefault();});
				

                $('.thematique-video-pager a', thematiqueVideoList).click(thematiqueVideoListPager);
			}
			
            function loadVisuel(liBlock, index)
            {
                var videoListUl = $('ul', videoList);
				
                $('li.active', videoListUl).removeClass('active');
                $('li:eq(' + index + ')', videoListUl).addClass('active');
                loadPlayerVideoAndHtml5(liBlock.find('.videoInformationFlv').html(), liBlock.find('.videoInformationMp4').html(), liBlock.find('.videoInformationPoster').html());
				
				addFacebook(liBlock);
				
                $('#videoHeader #videoTitle', mediatheque).html($('.description a', liBlock).html());

                var videoListContainer = $('.video-list-container', videoList);
                var videoListUl = $('ul', videoListContainer);
				
				var newMargin = 0;
				if (videoListUl.height() > videoListContainer.height()) {
							newMargin = (index) * $('li:first', videoListUl).outerHeight(true);
							if (newMargin + parseInt(videoListContainer.height()) >= videoListUl.height())
								newMargin = parseInt(videoListUl.height()) - parseInt(videoListContainer.height());
				}
                videoListUl.animate({marginTop: -newMargin}, 'fast');
            }
			

            function loadVisuelKeyWord(liBlock, index)
            {
				var uid = liBlock.find(".uid").text();
				var categorieInit = $("h1:eq(1)").text();
				var categorie = liBlock.find(".uid-title").text();
				var videoId = liBlock.find(".videoId").text();
				
				
				$("h1:eq(1)").text(categorie);
				$("#videoCenter > div").hide();
				
				$.get(currentLanguage+'/presse/mediatheque/mediatheque_ajax/galerie_video/?uid='+uid+"&videoId="+videoId, function(data){
					loadThematiqueVideoList(data);
					var liBlockNew = $("#videoList .videoId:contains("+videoId+")").parent();
					var indexNew = $("#videoList .videoId:contains("+videoId+")").parent().index();
					//alert(liBlockNew+" "+indexNew);
					if(categorie != categorieInit){
						$.get(currentLanguage+'/presse/mediatheque/mediatheque_ajax/galerie_video/?uid='+uid, function(data){
							loadThematiqueVideoListOnly(data);
							$(".liste-mediathek li.selected").removeClass("selected");
							$(".liste-mediathek li:has(p:contains('"+categorie+"'))").addClass("selected");
						});
					}
					loadVisuel(liBlockNew,indexNew);
					$("#videoCenter > div").fadeIn(400);

				});
				
            }
			
			function getUrlVars() {
				var vars = {};
				window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
					vars[key] = value;
				});
				return vars;
			}
			
			function shareOnFacebook(title,url,desc,image) {
				t=encodeURIComponent(title);
				d=encodeURIComponent(desc);
				u=encodeURIComponent(url);
				i=encodeURIComponent(image);
				share_url='http://www.facebook.com/sharer.php';
				share_url+='?s=100&p[title]='+t+'&p[url]='+u;
				share_url+='&p[images][0]='+i;
				share_url+='&t='+t;
				return share_url;

			//http://www.facebook.com/sharer/sharer.php?s=100&p[title]=Arriv%E9e+de+l%27+A380+%E0+Montr%E9al+%3A+A380+%E0+Montr%E9al&p[url]=http://client.projet.afcorporate.noven-dev.net/fr/presse/mediatheque/photos/la-flotte-air-france/airbus-a318/&p[images][0]=http%3A%2F%2Fclient.projet.afcorporate.noven-dev.net%2Ftypo3temp%2Fpics%2FAir_France_-9285_01_980x600_bg_w.JPG&t=Arriv%E9e+de+l%27+A380+%E0+Montr%E9al+%3A+A380+%E0+Montr%E9al
				
			}
			
			function addFacebook (el) {
				
				var container = $("#video_wrapper");
				var videoId = el.find(".videoId").text();
				var title = el.find(".description a").text();
				var url = "http://"+window.location.hostname+"/"+el.find(".categorie-url").text()+"?videoId="+videoId;
				if($.browser.msie && $.browser.version <8){
					var image = el.find("img").attr("src");
				}else{
					var image = "http://"+window.location.hostname+el.find("img").attr("src");
				}
				var link = shareOnFacebook(title,url,"",image);
				var facebook = $('<a href="'+link+'" target="_blank" class="fbk"><img src="/fileadmin/templates/tv/images/facebook-icon.png" /></a>');
				var hasFacebook = container.find(".fbk").length>0;
				
				if(hasFacebook){
					container.find(".fbk").remove();
				}
				container.append(facebook);
				
			}

            function thematiqueVideoListPager()
            {
                var index = $(this).index();
                var thematiqueVideoContainer = $('.thematique-video-list-containter', thematiqueVideoList);
                var thematiqueVideoContainerUl = $('.thematique-video-list-page', thematiqueVideoContainer);
                thematiqueVideoContainerUl.animate({marginLeft: -(parseInt(thematiqueVideoList.width()) * index)});
                $('.thematique-video-pager a.selected', thematiqueVideoList).removeClass('selected');
                $(this).addClass('selected');
                return (false);
            }

            function videoListScrollDown()
            {
                if (isMoving)
                    return (false);
                var videoListContainer = $('.video-list-container', videoList);
                var videoListUl = $('ul', videoListContainer);
                var marginTop = -parseInt(videoListUl.css('margin-top'));

                marginTop += $('li:first', videoListUl).outerHeight(true);
                if (marginTop + videoListContainer.height() <= videoListUl.height())
                {
                    isMoving = true;
                    videoListUl.animate({marginTop: -marginTop}, 'fast', function(){isMoving = false;});
                }
                return (false);
            }

            function videoListScrollUp()
            {
                if (isMoving)
                    return (false);
                var videoListContainer = $('.video-list-container', videoList);
                var videoListUl = $('ul', videoListContainer);
                var marginTop = -parseInt(videoListUl.css('margin-top'));

                marginTop -= $('li:first', videoListUl).outerHeight(true);
                if (marginTop >= 0)
                {
                    isMoving = true;
                    videoListUl.animate({marginTop: -marginTop}, 'fast', function(){isMoving = false;});
                }
                return (false);
            }

            function thematiqueListScrollDown()
            {
                if (isMoving)
                    return (false);
                var thematiqueContainer = $('.thematique-list-container', thematiqueList);
                var thematiqueUl = $('ul', thematiqueContainer);
                var marginTop = -parseInt(thematiqueUl.css('margin-top'));

                marginTop += $('li:first', thematiqueUl).outerHeight(true);
				//-5px height fix
                if (marginTop + thematiqueContainer.height() - 5 <= thematiqueUl.height())
                {
                    isMoving = true;
                    thematiqueUl.animate({marginTop: -marginTop}, 40, function(){isMoving = false;});
                }
                return (false);
            }

            function thematiqueListScrollUp()
            {
                if (isMoving)
                    return (false);
                var thematiqueContainer = $('.thematique-list-container', thematiqueList);
                var thematiqueUl = $('ul', thematiqueContainer);
                var marginTop = -parseInt(thematiqueUl.css('margin-top'));

                marginTop -= $('li:first', thematiqueUl).outerHeight(true);
                if (marginTop >= 0)
                {
                    isMoving = true;
                    thematiqueUl.animate({marginTop: -marginTop}, 40, function(){isMoving = false;});
                }
                return (false);
            }

            function thematiqueOpen()
            {
            	$("#video").hide();
                thematique.css({height: 0, width: 0, marginLeft: parseInt(mediatheque.width()) + parseInt(mediatheque.css('margin-left')), display: 'block'});

                thematique.animate({height: mediatheque.height(), width: mediatheque.width(), marginLeft: parseInt(mediatheque.css('margin-left'))}, 'fast');
            }

            function thematiqueClose()
            {
            	$("#video").show();
                thematique.animate({height: 0, width: 0, marginLeft: mediatheque.width()},
                'fast', function(){
                    thematique.css({display:'none'});
                });
            }
            function dragAndDrop(event)
            {
                var slider = $(this);
                var container = $(this).parent();
                
                if (!isMoving)
                {
                    var start = event.pageY;
                    var waitingForEffect = false;

                    $('html').bind('mousemove', function (event) {
                        if (!waitingForEffect)
                        {
                            waitingForEffect = true;
                            var effectTimer = setInterval(function() {
                                waitingForEffect = false;
                                clearInterval(effectTimer);
                            }, 50);
                            if (parseInt(event.pageY - start) != 0)
                            {
                                isMoving = true;
                                slider.animate({
                                    marginTop: parseInt(slider.css('margin-top')) + parseInt(event.pageY - start)
                                    },
                                50, function() {
                                    isMoving = false;
                                });
                                hasMoved = true;
                            }
                            start = event.pageY;
                            return ;
                        }
                    });

                    $('html').bind('mouseup', function () {
                        $('html').unbind('mouseup');
                        $('html').unbind('mousemove');
			if (!hasMoved)
			    return;
                        var tempTimer = setInterval(function () {
                        if (!isMoving)
                            {
                                isMoving = true;
                                var sliderPosition = -parseInt(slider.css('margin-top'));
                                var sliderLiHeight = parseInt($('li:first', slider).outerHeight(true));

                                if (sliderPosition < 0) sliderPosition = 0;
                                if ((sliderPosition + container.height()) > slider.height()) sliderPosition = slider.height() - container.height();
                                
                                var sliderPositionFloatingPart = sliderPosition - (parseInt(sliderPosition / sliderLiHeight) * sliderLiHeight);
                                sliderPosition = (parseInt(sliderPosition / sliderLiHeight) * sliderLiHeight);
                                if (sliderPositionFloatingPart > (sliderLiHeight / 2))
                                    sliderPosition += sliderLiHeight;
                                if ((sliderPosition + container.height()) > slider.height()) sliderPosition = slider.height() - container.height();

                                slider.animate({marginTop: -parseInt(sliderPosition)}, 50, function(){
                                    isMoving = false;
                                    clearInterval(tempTimer);
                                });
                            }
                        }, 100);
                    });
                }
                return (false);
            }
        });
    }
})(jQuery);

