$(function() {
 	var media;
    $("#vform").validate();
	$(".multiFR").MultiFile({ 
   		accept:'mp4|jpg', STRING: { 
    		remove:'Supprimer', 
	    	selected:'Séléctionné: $file', 
    		denied:'Extension invalide $ext!', 
    		duplicate:'Fichier déjà séléctionné:\n$file!' 
	   } 
   }); 
	

$('.plus').click (function () {
 if ($(this).attr ('src') == 'img/plus.png')
 {
 $(this).attr ('src', 'img/minus.png');
 $(this).nextAll(".content").slideDown ('slow');
 }
 else
 {
 $(this).nextAll(".content").slideUp ('slow');
 $(this).attr ('src', 'img/plus.png');
 }
 }); 

	$(".selectPhotograph").change (function () { $(this).parent().submit(); });
	
	$(".addComment").click(function() {
		var src = $('.galleria .active img').attr('src');
		var id = src.split('/');
        id = id[1].split('-')[0];
		$('#commentBoxMedia').attr('src', src);
        $('#idMedia').attr('value', id);
		$("#commentBoxExplication").val('');
		$('#commentBackground').slideDown('slow');
	});

 	$(".download").click(function() {
		var photos = new Array ();
		$(".downloadList").children().each(function () {
        	photos.push ($(this).attr('src').split('/').pop());
        });
		
		$.ajax({
           type: "POST",
           url: "ajax.php",
           data: "action=download&photos="+photos.join(":"),
           success: function(msg){
				 $(".downloadList").html (' <span class="toDownload">' +
    			 	'<a href="'+msg+'" class="download" title="Telecharger l\'archive">'+
                        '<img src="img/downloadBig.png" alt="telecharger le contenu" class="imgLien imgBlock"/>' +
						'Télécharger mes photos' +
                    '</a>'+
                    '</span>');
           }
        });
    });

 	$(".downloadAllLink").click(function() {
      $(".downloadAll").html ('');
	  $(".downloadList").html (' <span class="toDownload">' +
		    '<img src="img/zip.png" alt="Création de l\'archive" class="imgLien imgBlock"/>' +
			'Création de l\'archive en cours' +
		  '</a>'+
          '</span>');
      var location = document.location.href;
	  var id = location.substring (location.lastIndexOf("-") + 1, location.lastIndexOf(".html"));
      $.ajax({
           type: "POST",
           url: "ajax.php",
           data: "action=downloadAll&idAlbum="+id,
           success: function(msg){
                 $(".downloadList").html (' <span class="toDownload">' +
                    '<a href="'+msg+'" class="download" title="Telecharger l\'archive">'+
                        '<img src="img/downloadBig.png" alt="telecharger le contenu" class="imgLien imgBlock"/>' +
                        'Télécharger mes photos' +
                    '</a>'+
                    '</span>');
           }
        });
    });


	$("#addUserComment").click(function() {
		$('.commentsDiv').html ('<img src="img/load.gif" alt="chargement" style="margin-top:120px;"/>');
		$.ajax({
           type: "POST",
           url: "ajax.php",
           data: "action=userComment&explication="+$("#commentBoxExplication").val()+"&media="+$("#idMedia").attr("value"),
           success: function(msg){
		   		msg = msg.split (":");
                var label = 'Commentaire';
                if (msg[0] == '1')
                   label += 's';
                $('.commentsLabel').html (label);
                $('.commentsDiv').html (msg[1]);
                $('.commentsDiv').jScrollPane({animateTo:true, animateInterval:50, animateStep:5, scrollbarWidth:5, dragMaxHeight:40});
				$('#commentBackground').slideUp ('slow');
           }
        });
		return false;
	});

	$('.draggable')
	.bind( 'dragstart', function( event ){
		$.dropManage({ mode: $('#mode').val() });
		media = $( this );
		return $( this ).clone()
		.addClass('dragBox')
		.appendTo( this.parentNode )
	})
	.bind( 'drag', function( event ){
		$( event.dragProxy ).css({ top:event.offsetY, left:event.offsetX });
	})
	.bind( 'dragend', function( event ){
		$( event.dragProxy ).fadeOut("slow");
	});

	$('div.toolsAction')
	.bind( 'dropstart',function(){
		$( this ).toggleClass('toolsActionHover');
	})
	.bind( 'dropend', function( event ){
		$( this ).toggleClass('toolsActionHover');
	});

	$('div.toolsActionDelete')
	.bind( 'drop', function (event) {
		var id = media.attr('src').split('/');
		id = id[1].split('-')[0];
		$.ajax({
		   type: "POST",
		   url: "ajax.php",
		   data: "action=delete&id="+id,
		   success: function(msg){
			 media.remove();
	 		 $(".dragBox").remove ();
		   }
		});
	});

	$('div.toolsActionEdit')
	.bind( 'drop', function (event) {
	   	var id = media.attr('src').split('/');
       	id = id[1].split('-')[0];
		$('#commentBoxMedia').attr('src', media.attr('src'));
		$('#idMedia').attr('value', id);
		$.ajax({
		   type: "POST",
		   url: "ajax.php",
		   data: "action=setExplication&id="+id,
		   success: function(msg){
		   	$('#commentBoxExplication').val (msg);
		   }
		});
		$('#commentBackground').slideDown ('slow');
	});

	 $('div.toolsActionFavorite')
        .bind( 'drop', function (event) {
            $('.notice').remove ();
			$('.toDownload').remove ();
			var add = true;
			$(".downloadList").children().each(function () {
				if ($(this).attr('src') == $('.dragBox').attr('src'))
				{
					add = false;
				}
			});
			if (add)
	            $('.downloadList').append ('<img src="'+$('.dragBox').attr('src')+'"  class="imgToDownload"/>');
         });


	$('.closeButton').click(function () {
		$('#commentBackground').slideUp ('slow');
	});


	$('div.toolsActionDelete')
	.bind( 'drop', function (event) {
		var id = media.attr('src').split('/');
		id = id[1].split('-')[0];
		$.ajax({
		   type: "POST",
		   url: "ajax.php",
		   data: "action=delete&id="+id,
		   success: function(msg){
			 media.remove();
	 		 $(".box").remove ();
		   }
		});
	});

	$('.gallery_demo_unstyled').addClass('gallery_demo'); // adds new class name to maintain degradability
    $('ul.gallery_demo').galleria({
		history   : true, // activates the history object for bookmarking, back-button etc.
		clickNext : true, // helper for making the image clickable
		insert    : '#main_image', // the containing selector for our main image
		onImage   : function(image,caption,thumb) { // let's add some image effects for demonstration purposes
				
			// fade in the image & caption
			image.css('display','none').fadeIn(800);
			caption.css('display','none').fadeIn(800);
				
			// fetch the thumbnail container
			var _li = thumb.parents('li');
				
			// fade out inactive thumbnail
			_li.siblings().children('img.selected').fadeTo(500,0.3);
				
			// fade in active thumbnail
			thumb.fadeTo('fast',1).addClass('selected');
				
			// add a title for the clickable image
			image.attr('title','Next image >>');
		},
		onThumb : function(thumb) { // thumbnail effects goes here
				
			// fetch the thumbnail container
			var _li = thumb.parents('li');
			
			// if thumbnail is active, fade all the way.
			var _fadeTo = _li.is('.active') ? '1' : '0.3';
			
			// fade in the thumbnail when finnished loading
			thumb.css({display:'none',opacity:_fadeTo}).fadeIn(500);
			
			// hover effects
			thumb.hover(
			function() { thumb.fadeTo('fast',1); },
			function() { _li.not('.active').children('img').fadeTo('fast',0.3); } // don't fade out if the parent is active
			)
		}
   });

	
	$('.bubbleInfo').each(function () {
            var distance = 10;
            var time = 250;
            var hideDelay = 5;

            var hideDelayTimer = null;

            var beingShown = false;
            var shown = false;
            var trigger = $('.trigger', this);
            var info = $('.popup', this).css('opacity', 0);


            $([trigger.get(0), info.get(0)]).mouseover(function () {
                if (hideDelayTimer) clearTimeout(hideDelayTimer);
                if (beingShown || shown) {
                    // don't trigger the animation again
                    return;
                } else {
                    // reset position of info box
                    beingShown = true;

                    info.css({
                        display: 'block'
                    }).animate({
                        //top: '-=' + distance + 'px',
                        opacity: 1
                    }, time, 'swing', function() {
                        beingShown = false;
                        shown = true;
                    });
					
					var id = $(this).children ().attr("id").substr (5);
					info.css({
                       top: (document.getElementById("popup"+id).clientHeight - 30) * -1,
                       left: -10
                    });
                }

                return false;
            }).mouseout(function () {
                if (hideDelayTimer) clearTimeout(hideDelayTimer);
                hideDelayTimer = setTimeout(function () {
                    hideDelayTimer = null;
                    info.animate({
                        top: '-=' + distance + 'px',
                        opacity: 0
                    }, time, 'swing', function () {
                        shown = false;
                        info.css('display', 'none');
                    });

                }, hideDelay);

                return false;
            });
        });

});




