
$(document).ready(function() 
    { 
        // Function that make SidebarTab to be easily 
        // hide/show with a nice and slow animation.
        $(".hideTable").click(function() 
        {
            $(document.getElementById('hideThis')).hide("slow");
            $(".hideTable").addClass("invisibleArea");
            $(".showTable").removeClass("invisibleArea");
        });  
        $(".showTable").click(function()
        {
            $(document.getElementById('hideThis')).show("slow");
            $(".showTable").addClass("invisibleArea");
            $(".hideTable").removeClass("invisibleArea");
        });
		
		// Function that make SidebarTab to be easily 
        // hide/show with a nice and slow animation.
        $(".hideLogin").click(function() 
        {
            $(document.getElementById('hideThisLogin')).hide("slow");
            $(".hideLogin").addClass("invisibleArea");
            $(".showLogin").removeClass("invisibleArea");
        });  
        $(".showLogin").click(function()
        {
            $(document.getElementById('hideThisLogin')).show("slow");
            $(".showLogin").addClass("invisibleArea");
            $(".hideLogin").removeClass("invisibleArea");
        });
        
		// Function that make SidebarTab to be easily 
        // hide/show with a nice and slow animation.
        $(".hideFolders").click(function() 
        {
            $(document.getElementById('hideFolders')).hide("slow");
            $(".hideFolders").addClass("invisibleArea");
            $(".showFolders").removeClass("invisibleArea");
        });  
        $(".showFolders").click(function()
        {
            $(document.getElementById('hideFolders')).show("slow");
            $(".showFolders").addClass("invisibleArea");
            $(".hideFolders").removeClass("invisibleArea");
        });
		
        //
        
         $(".hideTable2").click(function() 
        {
            $(document.getElementById('hideThis2')).hide("slow");
            $(".hideTable2").addClass("invisibleArea");
            $(".showTable2").removeClass("invisibleArea");
        });  
        $(".showTable2").click(function()
        {
            $(document.getElementById('hideThis2')).show("slow");
            $(".showTable2").addClass("invisibleArea");
            $(".hideTable2").removeClass("invisibleArea");
        });
        
        //
        
         $(".hideTable3").click(function() 
        {
            $(document.getElementById('hideThis3')).hide("slow");
            $(".hideTable3").addClass("invisibleArea");
            $(".showTable3").removeClass("invisibleArea");
        });  
        $(".showTable3").click(function()
        {
            $(document.getElementById('hideThis3')).show("slow");
            $(".showTable3").addClass("invisibleArea");
            $(".hideTable3").removeClass("invisibleArea");
        });
        
        //
        
         $(".hideTable4").click(function() 
        {
            $(document.getElementById('hideThis4')).hide("slow");
            $(".hideTable4").addClass("invisibleArea");
            $(".showTable4").removeClass("invisibleArea");
        });  
        $(".showTable4").click(function()
        {
            $(document.getElementById('hideThis4')).show("slow");
            $(".showTable4").addClass("invisibleArea");
            $(".hideTable4").removeClass("invisibleArea");
        });
        
        //
        
         $(".hideTable5").click(function() 
        {
            $(document.getElementById('hideThis5')).hide("slow");
            $(".hideTable5").addClass("invisibleArea");
            $(".showTable5").removeClass("invisibleArea");
        });  
        $(".showTable5").click(function()
        {
            $(document.getElementById('hideThis5')).show("slow");
            $(".showTable5").addClass("invisibleArea");
            $(".hideTable5").removeClass("invisibleArea");
        });
        
    });

$(document).ready(function() 
    { 
        $(".normalScreenButton").hide("fast");
        
        // Function that enable nice fullScreen 
        // Mode and NormalScreen Mode (with or
        // without Header & Sidebar).
        $(".fullScreenButton").click(function() 
        {
            $(document.getElementById('sideBarJs')).removeClass("sidebar").addClass("sideBarReduce");
            $(document.getElementById('header')).addClass("displayHeader");
            $(this).hide("fast");
            $(".normalScreenButton").show("fast");
        });     
        $(".normalScreenButton").click(function() 
        {
            $(document.getElementById('sideBarJs')).removeClass("sideBarReduce").addClass("sidebar");
            $(document.getElementById('header')).removeClass("displayHeader");
            $(this).hide("fast");
            $(".fullScreenButton").show("fast");
        });
    });
    

$(document).ready(function() 
    {   
        $('a.changeTheme').click(function()
        {
            $('.modalPopUp').removeClass('invisibleArea');
    });
    
    });


$(document).ready(function() 
    { 
        // Function that enable, when there is more than one checkbox
        // that is checked, to made the CheckboxBoxArea to be visible
        $(".class").click(function() 
        {
		$('#fixedArea').addClass("visibleArea");
        });            
    });



$(document).ready(function() 
    { 
        // Function that enable advanced
        // search box to appear.
        $(".advancedSearchBox").click(function() 
        {
            $(document.getElementById('footer')).removeClass("normalHeight").addClass("expandHeight");
            $(document.getElementById('fixedArea')).removeClass("normalHeight").addClass("expandHeight");
			$('.fixedSearchEngine').hide('slow');
			$('.fixedAreaLinks').hide('slow');
			$('.fixedAdvancedSearchEngine').show('slow');
			$('.fixedCloseFooterArea').show('slow');
        });
		$(".fixedCloseFooterExpand").click(function() 
        {
            $(document.getElementById('footer')).addClass("normalHeight").removeClass("expandHeight");
            $(document.getElementById('fixedArea')).addClass("normalHeight").removeClass("expandHeight");
			$('.fixedSearchEngine').show('slow');
			$('.fixedAreaLinks').show('slow');
			$('.fixedAdvancedSearchEngine').hide('slow');
			$('.fixedCloseFooterArea').hide('slow');
        });    
    });
	

// hover effect
$(document).ready(function() {
  $('div.menu-toggle h3').add('div.menu-toggle2 h3').hover(function() {
    $(this).addClass('hover');
  }, function() {
    $(this).removeClass('hover');
  });
});




// independently show and hide
$(document).ready(function() {
  $('div.menu-toggle:eq(0) > div').hide();  
  $('div.menu-toggle:eq(0) > h4').click(function() {
    $(this).next().slideToggle('fast');
  });
});


$(document).ready(function() {
    $('#formUpload').ajaxForm({
		
       beforeSubmit:clearOutput,
       success: writeOutput
    });
});	
	
	
	// pre-submit callback
	function clearOutput(a, f, o) {
		o.url="/uploader/_do",
		o.method ="POST",
	    o.dataType = 'html';
		$('#loadingUp').slideDown('fast');
	    //$('#data-content').html('Submitting form...');
	}
	
	// success callback
	function writeOutput(data) {
	    var $out = $('#data-content');
	    //$out.html('Form success handler received: <strong>' + typeof data + '</strong><br /><br />');
	
	    if (typeof data == 'object' && data.nodeType)
	        data = elementToString(data.documentElement, true);
	    else if (typeof data == 'object')
	        data = objToString(data);
	
	    $out.html( data );
        $('#loadingUp').slideUp('slow');
	}


/*--- BUBBLE INFO START ---*/
$(function () {
        $('.bubbleInfo').each(function () {
            var distance = 10;
            var time = 250;
            var hideDelay = 0.2;

            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({
                        top: -90,
                        left: -33,
                        display: 'block'
                    }).animate({
                        top: '-=' + distance + 'px',
                        opacity: 1
                    }, time, 'swing', function() {
                        beingShown = false;
                        shown = true;
                    });
                }

                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;
            });
        });
    });
/*--- BUBBLE INFO END ---*/


/*--- FILES HELPERS START ---*/
setMoveFolder = function(folder_id){
    $('#moveFolder').attr("value", folder_id);
	return false;
}

formMoveFolder = function () {
    $.ajax({
        url: "/folder/move",
        type: "GET",
        data: $('form#formMoveFolder').formToArray(true),
        dataType : "json",      
        
        beforeSend: function(){
        return php.beforeSend();
        },
        
        success: function(data, textStatus){
            return php.success(data, textStatus);
        },
        
        error: function (xmlEr, typeEr, except) {
            return php.error(xmlEr, typeEr, except);
        },
        
        // Handle the complete event
        complete: function (XMLHttpRequest, textStatus) {
            return php.complete(XMLHttpRequest, textStatus);
        }
    });
    return false;
}


formMoveFile = function () {
    $.ajax({
        url: "/file/moveOneFile",
        type: "GET",
        data: $('form#formMoveFile').formToArray(true),
        dataType : "json",      
        
        beforeSend: function(){
            return php.beforeSend();
        },
        
        success: function(data, textStatus){
            return php.success(data, textStatus);
        },
        
        error: function (xmlEr, typeEr, except) {
            return php.error(xmlEr, typeEr, except);
        },
        
        // Handle the complete event
        complete: function (XMLHttpRequest, textStatus) {
            return php.complete(XMLHttpRequest, textStatus);
        }
    });
    return false;
}

formDelFile = function () {
    $.ajax({
        url: "/file/delOneFile",
        type: "GET",
        data: $('form#formDelFile').formToArray(true),
        dataType : "json",      
        
        beforeSend: function(){
            return php.beforeSend();
        },
        
        success: function(data, textStatus){
            return php.success(data, textStatus);
        },
        
        error: function (xmlEr, typeEr, except) {
            return php.error(xmlEr, typeEr, except);
        },
        
        // Handle the complete event
        complete: function (XMLHttpRequest, textStatus) {
            return php.complete(XMLHttpRequest, textStatus);
        }
    });
    return false;
}

php.beforeSend = function (){
 $('#loading').slideDown('fast');
 $('#loadingDel').slideDown('fast');
}

php.complete = function (){
 $('#loading').slideUp('slow');
 $('#loadingDel').slideUp('slow');
}

php.error = function (){
    //alert("Oops, something goes wrong");
}


php.messages.callBack = function (msg, params){
 alert ( msg);
}

/*--- FILE HELPERS END ---*/

/*--- RAPID SEARCH START ---*/
function lookup(inputString) {
	$('#searchSpinner').show();
    if(inputString.length == 0) {
		
        // Hide the suggestion box.
        $('#suggestions').hide();
		$('#searchSpinner').hide();
    } else {
		
        $.post("/search/_do", {queryString: ""+inputString+""}, function(data){
            if(data.length >0) {
                $('#suggestions').show();
                $('#autoSuggestionsList').html(data);
                $('#searchSpinner').hide();
            }
        });
    }
} // lookup

function fill(thisValue) {
	
    $('#searchSpinner').hide();
    $('#inputString').val(thisValue);
   $('#suggestions').hide();
}
/*--- RAPID SEARCH END ---*/
/*--- FOLDER HELPERS START ---*/

(function($){
    var updateUpDown = function(sortable){
		//alert(sortable.id);
        $('dl:not(.ui-sortable-helper)', sortable)
            .removeClass('first').removeClass('last')
            .find('.up, .down').removeClass('disabled').end()
            .filter(':first').addClass('first').find('.up').addClass('disabled').end().end()
            .filter(':last').addClass('last').find('.down').addClass('disabled').end().end();
    };
    
    var moveUpDown = function(){
        var link = $(this),
            dl = link.parents('dl'),
            prev = dl.prev('dl'),
            next = dl.next('dl');
    
        if(link.is('.up') && prev.length > 0)
            dl.insertBefore(prev);
    
        if(link.is('.down') && next.length > 0)
            dl.insertAfter(next);
    
        updateUpDown(dl.parent());
    };
    
    var addItem = function(){
        var sortable = $(this).parents('.ui-sortable');
		var parent_id = this.parentNode.parentNode.parentNode.id;
		//alert ( parent_id);
        //var options = '<span class="options"><a class="up">up</a><a class="down">down</a></span>';
		//var options = '';
        //var tpl = '<dl class="sort"><dt>{name}' + options + '</dt><dd>{desc}</dd></dl>';
        //var html = tpl.replace(/{name}/g, 'Nouveau').replace(/{desc}/g, '<img src="/public/images/fr_FR/lx/ico/prefs.png" alt="préférences"/>');
        
		$.post("/folder/_createFolder", {parent_id: ""+parent_id+""}, function(data){
            if(data.length >0) {
                //$('#containerCats').append(data);
				sortable.append(data).sortable('refresh').find('a.up, a.down').bind('click', moveUpDown);
				updateFolders();
            }
        });
		
        //sortable.append(html).sortable('refresh').find('a.up, a.down').bind('click', moveUpDown);
		refreshUserFolder();
		updateUpDown(sortable);

    };
    
	
	
    var emptyTrashCan = function(item){
		//alert(item[0].id);
		folder_id = item[0].id;
		$.post("/folder/_trashFolder", {folder_id: ""+folder_id+""}, function(data){
            if(data.length >0) {
				//alert(data);
				item.remove();
				refreshUserFolder();
                return true;
				
            }
        });
        
    };
    
	var moveToTrash = function(){
		//alert(this.id);
		folder_id = this.id;
		var folder_container = $(this).parents('.sort');
		$.post("/folder/_trashFolder", {folder_id: ""+folder_id+""}, function(data){
            if(data.length >0) {
				//alert(data);
				//window.location.reload(true);
				folder_container.hide();
				refreshUserFolder();
				updateFolders();
                return true;
				
            }
        });
        
    };
	
    var sortableChange = function(e, ui){
        if(ui.sender){
            //var w = ui.element.width();
            //ui.placeholder.width(w);
            //ui.helper.css("width",ui.element.children().width());
        }
    };
    
	var updateFolder = function(cat_id, folder_id){
		$.post("/folder/_moveFolder", {parent_id: ""+cat_id+"", folder_id: ""+folder_id+""}, function(data){
            if(data.length >0) {
                return true;
            }
			refreshUserFolder();
        });
	}
	
    var sortableUpdate = function(e, ui){
        if(ui.element[0].id == 'trashcanFolder'){
            emptyTrashCan(ui.item);
        } else {
		   updateFolder(ui.element[0].id, ui.item[0].id);
           updateUpDown(ui.element[0]);
            if(ui.sender)
                updateUpDown(ui.sender[0]);
        }
    };
    
	var addCat = function(){
        var sortable = $(this).parents('#containerCats');
        $.post("/folder/_createCat", {}, function(data){
            if(data.length >0) {
                $('#containerCats').prepend(data);
				refreshUserFolder();
				updateFolders();
            }
        });
		
		
    };
	
	var delCat = function(){
        var sortable = $(this).parents('#containerCats');
		var container = $(this).parents('.ui-sortable');
		var cat_container = this.parentNode.parentNode.parentNode;
		var cat_id = cat_container.id;
		//alert (cat_id);
        $.post("/folder/_delCat", {cat_id: ""+cat_id+""}, function(data){
			if(data.length >0) {
				if(data == "ok"){
				    container.hide();	
				}
				else{
				    alert(data);	
				}
				refreshUserFolder();
                updateFolders();
            }
        });
        
        
    };
	
    $(document).ready(function(){
		$('a.addCat').bind('click', addCat);
		$('a.delFolder').bind('click', moveToTrash);
        updateFolders();
    });
    
	var updateFolders = function(){
		var els = ['.category'];
        var $els = $(els.toString());
        
        $('h2', $els.slice()).append('<span class="options"><a class="del">Supprimer la catégorie</a><a class="add">Ajouter un dossier</a></span>');
        //$('dt', $els).append('<span class="options"><a class="up">up</a><a class="down">down</a></span>');
        
        $('a.add').bind('click', addItem);
		$('a.del').bind('click', delCat);
		$('a.delFolder').bind('click', moveToTrash);
        //$('a.up, a.down').bind('click', moveUpDown);
		
        $els.each(function(){
            updateUpDown(this);
        });
        
        $els.sortable({
            items: '> dl',
            handle: 'dt',
            cursor: 'move',
            //cursorAt: { top: 2, left: 2 },
            opacity: 0.5,
            //helper: 'clone',
            appendTo: 'body',
            //placeholder: 'clone',
            //placeholder: 'placeholder',
            connectWith: els,
            start: function(e,ui) {
                ui.helper.css("width", ui.item.width());
            },
            change: sortableChange,
            update: sortableUpdate
        });
    
	}
	var refreshUserFolder = function(){
    $.post("/menu/userFolder", {}, function(data){
            if(data.length >0) {
                $('div#user_menu').html(data);
            }
        });
    }
	
    $(window).bind('load',function(){
        /*setTimeout(function(){
            $('#overlay').fadeOut(function(){
                $('body').css('overflow', 'auto');
            });
        }, 0);*/
		$('#overlay').css('display', 'none');
    });
})(jQuery);
/*--- FOLDER HELPERS END ---*/

/*--- INPLACE EDITOR START ---*/
(function($) {

    $.fn.editable = function(target, options) {
    
        var settings = {
            target     : target,
            name       : 'value',
            id         : 'id',
            type       : 'text',
            width      : 'auto',
            height     : 'auto',
            event      : 'click',
            onblur     : 'cancel',
            loadtype   : 'GET',
            loadtext   : 'Loading...',
            placeholder: 'Click to edit',
            loaddata   : {},
            submitdata : {}
        };
        
        if(options) {
            $.extend(settings, options);
        }
    
        /* setup some functions */
        var plugin   = $.editable.types[settings.type].plugin || function() { };
        var submit   = $.editable.types[settings.type].submit || function() { };
        var buttons  = $.editable.types[settings.type].buttons 
                    || $.editable.types['defaults'].buttons;
        var content  = $.editable.types[settings.type].content 
                    || $.editable.types['defaults'].content;
        var element  = $.editable.types[settings.type].element 
                    || $.editable.types['defaults'].element;
        var reset    = $.editable.types[settings.type].reset 
                    || $.editable.types['defaults'].reset;
        var callback = settings.callback || function() { };
        
        /* add custom event if it does not exist */
        if  (!$.isFunction($(this)[settings.event])) {
            $.fn[settings.event] = function(fn){
                return fn ? this.bind(settings.event, fn) : this.trigger(settings.event);
            }
        }
          
        /* TODO: remove this when form is displayed */
        $(this).attr('title', settings.tooltip);
        
        settings.autowidth  = 'auto' == settings.width;
        settings.autoheight = 'auto' == settings.height;

        return this.each(function() {

            /* save this to self because this changes when scope changes */
            var self = this;  
                   
            /* inlined block elements lose their width and height after first edit */
            /* save them for later use as workaround */
            var savedwidth  = $(self).width();
            var savedheight = $(self).height();
            
            /* if element is empty add something clickable (if requested) */
            if (!$.trim($(this).html())) {
                $(this).html(settings.placeholder);
            }
            
            $(this)[settings.event](function(e) {

                /* prevent throwing an exeption if edit field is clicked again */
                if (self.editing) {
                    return;
                }

                /* figure out how wide and tall we are, saved width and height */
                /* are workaround for http://dev.jquery.com/ticket/2190 */
                if (0 == $(self).width()) {
                    //$(self).css('visibility', 'hidden');
                    settings.width  = savedwidth;
                    settings.height = savedheight;
                } else {
                    if (settings.width != 'none') {
                        settings.width = 
                            settings.autowidth ? $(self).width()*1.5  : settings.width*1.5;
                    }
                    if (settings.height != 'none') {
                        settings.height = 
                            settings.autoheight ? $(self).height() : settings.height;
                    }
                }
                //$(this).css('visibility', '');
                
                /* remove placeholder text, replace is here because of IE */
                if ($(this).html().toLowerCase().replace(/;/, '') == 
                    settings.placeholder.toLowerCase().replace(/;/, '')) {
                        $(this).html('');
                }
                                
                self.editing    = true;
                self.revert     = $(self).html();
                $(self).html('');

                /* create the form object */
                var form = $('<form/>');
                
                /* apply css or style or both */
                if (settings.cssclass) {
                    if ('inherit' == settings.cssclass) {
                        form.attr('class', $(self).attr('class'));
                    } else {
                        form.attr('class', settings.cssclass);
                    }
                }

                if (settings.style) {
                    if ('inherit' == settings.style) {
                        form.attr('style', $(self).attr('style'));
                        /* IE needs the second line or display wont be inherited */
                        form.css('display', $(self).css('display'));                
                    } else {
                        form.attr('style', settings.style);
                    }
                }

                /* add main input element to form and store it in input */
                var input = element.apply(form, [settings, self]);

                /* set input content via POST, GET, given data or existing value */
                var input_content;
                
                if (settings.loadurl) {
                    var t = setTimeout(function() {
                        input.disabled = true;
                        content.apply(form, [settings.loadtext, settings, self]);
                    }, 100);

                    var loaddata = {};
                    loaddata[settings.id] = self.id;
                    if ($.isFunction(settings.loaddata)) {
                        $.extend(loaddata, settings.loaddata.apply(self, [self.revert, settings]));
                    } else {
                        $.extend(loaddata, settings.loaddata);
                    }
                    $.ajax({
                       type : settings.loadtype,
                       url  : settings.loadurl,
                       data : loaddata,
                       async : false,
                       success: function(result) {
                          window.clearTimeout(t);
                          input_content = result;
                          input.disabled = false;
                       }
                    });
                } else if (settings.data) {
                    input_content = settings.data;
                    if ($.isFunction(settings.data)) {
                        input_content = settings.data.apply(self, [self.revert, settings]);
                    }
                } else {
                    input_content = self.revert; 
                }
                content.apply(form, [input_content, settings, self]);

                input.attr('name', settings.name);
        
                /* add buttons to the form */
                buttons.apply(form, [settings, self]);
         
                /* add created form to self */
                $(self).append(form);
         
                /* attach 3rd party plugin if requested */
                plugin.apply(form, [settings, self]);

                /* focus to first visible form element */
                $(':input:visible:enabled:first', form).focus();

                /* highlight input contents when requested */
                if (settings.select) {
                    input.select();
                }
        
                /* discard changes if pressing esc */
                input.keydown(function(e) {
                    if (e.keyCode == 27) {
                        e.preventDefault();
                        //self.reset();
                        reset.apply(form, [settings, self]);
                    }
                });

                /* discard, submit or nothing with changes when clicking outside */
                /* do nothing is usable when navigating with tab */
                var t;
                if ('cancel' == settings.onblur) {
                    input.blur(function(e) {
                        //t = setTimeout(self.reset, 500);
                        t = setTimeout(function() {
                            reset.apply(form, [settings, self]);
                        }, 500);
                    });
                } else if ('submit' == settings.onblur) {
                    input.blur(function(e) {
                        form.submit();
                    });
                } else if ($.isFunction(settings.onblur)) {
                    input.blur(function(e) {
                        settings.onblur.apply(self, [input.val(), settings]);
                    });
                } else {
                    input.blur(function(e) {
                      /* TODO: maybe something here */
                    });
                }

                form.submit(function(e) {

                    if (t) { 
                        clearTimeout(t);
                    }

                    /* do no submit */
                    e.preventDefault(); 
            
                    /* call before submit hook. if it returns false abort submitting */
                    if (false !== submit.apply(form, [settings, self])) { 
                      
                      /* check if given target is function */
                      if ($.isFunction(settings.target)) {
                          var str = settings.target.apply(self, [input.val(), settings]);
                          $(self).html(str);
                          self.editing = false;
                          callback.apply(self, [self.innerHTML, settings]);
                          /* TODO: this is not dry */                              
                          if (!$.trim($(self).html())) {
                              $(self).html(settings.placeholder);
                          }
                      } else {
                          /* add edited content and id of edited element to POST */
                          var submitdata = {};
                          submitdata[settings.name] = input.val();
                          submitdata[settings.id] = self.id;
                          /* add extra data to be POST:ed */
                          if ($.isFunction(settings.submitdata)) {
                              $.extend(submitdata, settings.submitdata.apply(self, [self.revert, settings]));
                          } else {
                              $.extend(submitdata, settings.submitdata);
                          }
                          
                          /* quick and dirty PUT support */
                          if ('PUT' == settings.method) {
                              submitdata['_method'] = 'put';
                          }

                          /* show the saving indicator */
                          $(self).html(settings.indicator);
                          $.post(settings.target, submitdata, function(str) {
                              $(self).html(str);
                              self.editing = false;
                              callback.apply(self, [self.innerHTML, settings]);
                              /* TODO: this is not dry */                              
                              if (!$.trim($(self).html())) {
                                  $(self).html(settings.placeholder);
                              }
                          });
                      }
                      
                    }
                     
                    return false;
                });
            });
            
            /* privileged methods */
            this.reset = function() {
                $(self).html(self.revert);
                self.editing   = false;
                if (!$.trim($(self).html())) {
                    $(self).html(settings.placeholder);
                }
            }            
        });

    };


    $.editable = {
        types: {
            defaults: {
                element : function(settings, original) {
                    var input = $('<input type="hidden">');                
                    $(this).append(input);
                    return(input);
                },
                content : function(string, settings, original) {
                    $(':input:first', this).val(string);
                },
                reset : function(settings, original) {
                  original.reset();
                },
                buttons : function(settings, original) {
                    var form = this;
                    if (settings.submit) {
                        /* if given html string use that */
                        if (settings.submit.match(/>$/)) {
                            var submit = $(settings.submit).click(function() {
                                if (submit.attr("type") != "submit") {
                                    form.submit();
                                }
                            });
                        /* otherwise use button with given string as text */
                        } else {
                            var submit = $('<button type="submit">');
                            submit.html(settings.submit);                            
                        }
                        $(this).append(submit);
                    }
                    if (settings.cancel) {
                        /* if given html string use that */
                        if (settings.cancel.match(/>$/)) {
                            var cancel = $(settings.cancel);
                        /* otherwise use button with given string as text */
                        } else {
                            var cancel = $('<button type="cancel">');
                            cancel.html(settings.cancel);
                        }
                        $(this).append(cancel);

                        $(cancel).click(function(event) {
                            //original.reset();
                            if ($.isFunction($.editable.types[settings.type].reset)) {
                                var reset = $.editable.types[settings.type].reset;                                                                
                            } else {
                                var reset = $.editable.types['defaults'].reset;                                
                            }
                            reset.apply(form, [settings, original]);
                            return false;
                        });
                    }
                }
            },
            text: {
                element : function(settings, original) {
                    var input = $('<input>');
                    if (settings.width  != 'none') { input.width(settings.width);  }
                    if (settings.height != 'none') { input.height(settings.height); }
                    /* https://bugzilla.mozilla.org/show_bug.cgi?id=236791 */
                    //input[0].setAttribute('autocomplete','off');
                    input.attr('autocomplete','off');
                    $(this).append(input);
                    return(input);
                }
            },
            textarea: {
                element : function(settings, original) {
                    var textarea = $('<textarea>');
                    if (settings.rows) {
                        textarea.attr('rows', settings.rows);
                    } else {
                        textarea.height(settings.height);
                    }
                    if (settings.cols) {
                        textarea.attr('cols', settings.cols);
                    } else {
                        textarea.width(settings.width);
                    }
                    $(this).append(textarea);
                    return(textarea);
                }
            },
            select: {
               element : function(settings, original) {
                    var select = $('<select>');
                    $(this).append(select);
                    return(select);
                },
                content : function(string, settings, original) {
                    if (String == string.constructor) {      
                        eval ('var json = ' + string);
                        for (var key in json) {
                            if (!json.hasOwnProperty(key)) {
                                continue;
                            }
                            if ('selected' == key) {
                                continue;
                            } 
                            var option = $('<option>').val(key).append(json[key]);
                            $('select', this).append(option);    
                        }
                    }
                    /* Loop option again to set selected. IE needed this... */ 
                    $('select', this).children().each(function() {
                        if ($(this).val() == json['selected'] || 
                            $(this).text() == original.revert) {
                                $(this).attr('selected', 'selected');
                        };
                    });
                }
            }
        },

        /* Add new input type */
        addInputType: function(name, input) {
            $.editable.types[name] = input;
        }
    };

})(jQuery);

/*--- INPLACE EDITOR END ---*/
/*--- INSIDER WINDOW START ---*/
var GB_DONE = false;
var GB_HEIGHT = 400;
var GB_WIDTH = 400;

function GB_show(caption, url, height, width) {
    try {
  GB_HEIGHT = height || 400;
  GB_WIDTH = width || 400;
  if(!GB_DONE) {
    $("body")
      .append("<div id='GB_overlay'></div><div id='GB_window'>"
        + "<div id='pop_head'><div id='pop_head_titre'><span id='GB_caption'></span></div><div id='pop_head_close'><a href='#'><img src='public/images/fr_FR/lx_m6_pro/theme_global/but/close.png' alt='' class='close_img'/></a></div></div></div>");
    $("#GB_window img").click(GB_hide);
    $("#GB_overlay").click(GB_hide);
    $(window).resize(GB_position);
    GB_DONE = true;
  }

  $("#GB_frame").remove();
  
  $("#GB_window").append("<iframe id='GB_frame' src='"+url+"'></iframe>");
  //$("#GB_window").append("<div id='GB_caption'></div>");
  $("#GB_caption").html(caption);
  $("#GB_overlay").show();
  GB_position();

  if(GB_ANIMATION)
    $("#GB_window").slideDown("slow");
  else
    $("#GB_window").show();
    } catch(e) {
        alert( e );
    }
}

function GB_hide() {
  $("#GB_window,#GB_overlay").hide();
}

function GB_position() {
  var de = document.documentElement;
  var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
    //$("#GB_window").css({width:GB_WIDTH+"px",height:GB_HEIGHT+"px",left: ((w - GB_WIDTH)/2)+"px" });
	$("#GB_window").css({marginLeft: '-' + parseInt((GB_WIDTH / 2),10) + 'px', width: GB_WIDTH + 'px'});
    if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
        $("#GB_window").css({marginTop: '-' + parseInt((GB_HEIGHT / 2),10) + 'px'});
    }

  $("#GB_frame").css("height",GB_HEIGHT - 32 +"px");
}
/*--- INSIDER WINDOW END ---*/


/*--- HIGHLIGHT FILE START --*/

function highlightDocument(document_id){
	$.post("/file/_highlight", {document_id: ""+document_id+""}, function(data){

			if(data.length >0) {
                if(data == "1"){
                    $('#document_'+document_id).addClass("highlightFile");   
                }
				else if(data == "0"){
                    $('#document_'+document_id).removeClass("highlightFile");   
                }
                else{
                    alert(data);    
                }
            }
        });
}

/*--- HIGHLIGHT FILE END --*/



/*--- RESTORE FILE START --*/

function restoreFile(document_id){
    $.post("/file/restoreFromTrash", {document_id: ""+document_id+""}, function(data){
            if(data.length >0) {
                $('#data-content').html(data);
				refreshUserFolder();
            }
        });
}

/*--- RESTORE FILE END --*/
/*--- REFRESH USER FOLDERS START --*/
function refreshUserFolder(){
    $.post("/menu/userFolder", {}, function(data){
            if(data.length >0) {
                $('div#user_menu').html(data);
            }
        });
}
/*--- REFRESH USER FOLDERS END --*/
/*--- REFRESH LAST DESCRIPTION START --*/
function refreshLastDesc(name){
    $.post("/file/_lastDesc", {}, function(data){
        if(data.length >0) {
                $('td#'+name).html(data);
            }
        });
}
/*--- REFRESH LAST DESCRIPTION END --*/
/*--- REFRESH LAST NATURE START --*/
function refreshLastNature(name){
    $.post("/file/_lastNature", {}, function(data){
        if(data.length >0) {
                $('td#'+name).html(data);
            }
        });
}
/*--- REFRESH LAST NATURE END --*/
/*--- TABS START ---*/
$(function () {
    var tabContainers = $('div.tabs > div');
    tabContainers.hide().filter(':first').show();
    
    $('div.tabs ul.tabNavigation a').click(function () {
        tabContainers.hide();
        tabContainers.filter(this.hash).show();
        $('div.tabs ul.tabNavigation a').removeClass('selected');
        $(this.hash+'_tab').addClass('selected');
        return false;
    }).filter(':first').click();
});

function displayTab(tab_id){
	var tabContainers = $('div.tabs > div');
    tabContainers.hide().filter(':first').show();
	
	tabContainers.hide();
    tabContainers.filter(tab_id).show();
    $('div.tabs ul.tabNavigation a').removeClass('selected');
    $(tab_id+"_tab").addClass('selected');
    return false;
	
}
$(document).ready(function() {
    	displayTab('#fourth');
});

/*--- TABS END ---*/

/*--- ADVANCED SEARCH START ---*/

$(document).ready(function() {
    $('#advancedSearchForm').ajaxForm({
        
       beforeSubmit:prepareSearch,
       success: writeSearch
    });
}); 
    
    
    // pre-submit callback
    function prepareSearch(a, f, o) {
        o.url="/space/advancedSearch",
        o.method ="POST",
        o.dataType = 'html';
        $('#loadingSearch').slideDown('fast');
    }
    
    // success callback
    function writeSearch(data) {
		
        var $out = $('#data-content');
    
        if (typeof data == 'object' && data.nodeType)
            data = elementToString(data.documentElement, true);
        else if (typeof data == 'object')
            data = objToString(data);
    
        $out.html( data );
        $('#loadingSearch').slideUp('slow');
    }

/*--- ADVANCED SEARCH END ---*/

/*--- PRO SEARCH START ---*/

$(document).ready(function() {
    $('#proSearchForm').ajaxForm({
       
       beforeSubmit:prepareProSearch,
       success: writeProSearch
    });
}); 
    
    
    // pre-submit callback
    function prepareProSearch(a, f, o) {
		
        o.url="/search/proSearch",
        o.method ="POST",
        o.dataType = 'html';
        $('#loadingSearch').slideDown('fast');
    }
    
    // success callback
    function writeProSearch(data) {
        var $out = $('#data-content');
        if (typeof data == 'object' && data.nodeType)
            data = elementToString(data.documentElement, true);
        else if (typeof data == 'object')
            data = objToString(data);
        $out.html( data );
        $('#loadingSearch').slideUp('slow');
    }

/*--- PRO SEARCH END ---*/

/*--- IMAGE REFLEXION START ---*/
jQuery.fn.reflect = function(settings) {
    settings = jQuery.extend({
        height: 0.5,
        opacity: 0.5,
        inline: false
    }, settings);
    
    this.each( function() {
        var rheight = null;
        var ropacity = null;
        
        if (settings["inline"])
        {
            var classes = this.className.split(' ');
            for (j=0;j<classes.length;j++) {
                if (classes[j].indexOf("rheight") == 0) {
                    settings["height"] = classes[j].substring(7)/100;
                } else if (classes[j].indexOf("ropacity") == 0) {
                    settings["opacity"] = classes[j].substring(8)/100;
                }
            }
        }

        jQuery.Reflection.add(this, settings);
        
    })
    return this;
}

jQuery.Reflection = {
    
    add: function(image, options) {
        jQuery.Reflection.remove(image);
            
        try {
            var d = document.createElement('div');
            var p = image;
            
            var classes = p.className.split(' ');
            var newClasses = '';
            for (j=0;j<classes.length;j++) {
                if (classes[j] != "reflect") {
                    if (newClasses) {
                        newClasses += ' '
                    }
                    
                    newClasses += classes[j];
                }
            }

            var reflectionHeight = Math.floor(p.height*options['height']);
            var divHeight = Math.floor(p.height*(1+options['height']));
            
            var reflectionWidth = p.width;
            
            if (document.all && !window.opera) {
                /* Copy original image's classes & styles to div */
                d.className = newClasses;
                p.className = 'reflected';
                
                d.style.cssText = p.style.cssText;
                p.style.cssText = 'vertical-align: bottom';
            
                var reflection = document.createElement('img');
                reflection.src = p.src;
                reflection.style.width = reflectionWidth+'px';
                
                reflection.style.marginBottom = "-"+(p.height-reflectionHeight)+'px';
                reflection.style.filter = 'flipv progid:DXImageTransform.Microsoft.Alpha(opacity='+(options['opacity']*100)+', style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy='+(options['height']*100)+')';
                
                d.style.width = reflectionWidth+'px';
                d.style.height = divHeight+'px';
                p.parentNode.replaceChild(d, p);
                
                d.appendChild(p);
                d.appendChild(reflection);
            } else {
                var canvas = document.createElement('canvas');
                if (canvas.getContext) {
                    /* Copy original image's classes & styles to div */
                    d.className = newClasses;
                    p.className = 'reflected';
                    
                    d.style.cssText = p.style.cssText;
                    p.style.cssText = 'vertical-align: bottom';
            
                    var context = canvas.getContext("2d");
                
                    canvas.style.height = reflectionHeight+'px';
                    canvas.style.width = reflectionWidth+'px';
                    canvas.height = reflectionHeight;
                    canvas.width = reflectionWidth;
                    
                    d.style.width = reflectionWidth+'px';
                    d.style.height = divHeight+'px';
                    p.parentNode.replaceChild(d, p);
                    
                    d.appendChild(p);
                    d.appendChild(canvas);
                    
                    context.save();
                    
                    context.translate(0,image.height-1);
                    context.scale(1,-1);
                    
                    context.drawImage(image, 0, 0, reflectionWidth, image.height);
    
                    context.restore();
                    
                    context.globalCompositeOperation = "destination-out";
                    var gradient = context.createLinearGradient(0, 0, 0, reflectionHeight);
                    
                    gradient.addColorStop(1, "rgba(255, 255, 255, 1.0)");
                    gradient.addColorStop(0, "rgba(255, 255, 255, "+(1-options['opacity'])+")");
        
                    context.fillStyle = gradient;
                    if (navigator.appVersion.indexOf('WebKit') != -1) {
                        context.fill();
                    } else {
                        context.fillRect(0, 0, reflectionWidth, reflectionHeight*2);
                    }
                }
            }
        } catch (e) {
        }
    },
    
    remove : function(image) {
        if (image.className == "reflected") {
            image.className = image.parentNode.className;
            image.parentNode.parentNode.replaceChild(image, image.parentNode);
        }
    }
}
$(document).ready(function() {
            $('img.reflect').each(function(){
                $(this).load( 
                    function(){ 
                        $(this).reflect({height: 0.3, opacity: 0.6} );
                    } 
                );
            });
        });

/*--- IMAGE REFLEXION END ---*/
/*--- MAGIC BAR START---*/
function fixed_bottom(select,offS){
    return Number(-offS+document.documentElement.clientHeight-select.offsetHeight+document.documentElement.scrollTop+document.body.scrollTop)+'px';
}

/* Une fois la page chargÃ©e */
$(document).ready(function(){
    $("#magicmenu").show();
    
    /* On active la position "fixed" selon les navgateurs */
    if ($.browser.msie) {
        if($.browser.version == "6.0"){
            $("#magicmini").hide();
            $("#magicmaxi").hide();
            $("#magicbox").css('position', 'absolute');
        }else if($.browser.version == "7.0"){
            $("#magicbox").css('position', 'fixed');
            $("#magicmini").hide();
            $("#magicmaxi").hide();         
        }
    }else{
        $("#magicbox").css('position', 'fixed');
        $("#magicmini").hide();
        $("#magicmaxi").hide();
    }
    
    /* Clic sur le bouton [Close] */
    $(".magic1").click(function () {
        $.cookie('selectmenu','close');
        $("#magiccontent").slideUp("slow",function(){
            $("#magicmaxi").hide();
            $("#magicmini").hide();
            $(this).show();
        });
        toggleselect(this);
        return false;
    });
    
    /* Clic sur le bouton [Light] */
    $(".magic3").click(function () {
        $.cookie('selectmenu','light');
        if($("#magicmini").css("display") == "none" && $("#magicmaxi").css("display") == "none"){
            $("#magiccontent").hide();
            $("#magicmini").show();
        }
        if($("#magiccontent").css("display") == "none"){
            $("#magicmaxi").hide();
            $("#magiccontent").slideDown("slow");
        } else if($("#magicmaxi").css("display") == "block"){
            $("#magicmaxi").slideUp("slow");
        }
        toggleselect(this);
        return false;
    });
    
    /* Clic sur le bouton [Full] */
    $(".magic2").click(function () {
        $.cookie('selectmenu','full');
        if($("#magicmini").css("display") == "none" && $("#magicmaxi").css("display") == "none"){
            $("#magiccontent").hide();
            $("#magicmini").show();
        }
        if($("#magiccontent").css("display") == "none"){
            $("#magicmaxi").show();
            $("#magiccontent").slideDown("slow");
        } else if($("#magicmaxi").css("display") == "none"){
            $("#magicmaxi").slideDown("slow");
        }
        toggleselect(this);
        return false;
    });

    /* OpacitÃ© de 80% sur le contenu via javascript car par hack css Ã§a fait buguer ie6 */
    $("#magiccontent").fadeTo("fast", 0.6);
    
    /* Bidouillage monstrueux pour onglet selectionnÃ© car addClass ne fonctionne pas (et Ã§a m'enerve !) */
    $("#magicmenu ul li a").each(function(i){
        $(this).fadeTo("fast", 0.6);
        this.colback = $(this).css('background-color');
        this.tempcol = false;
        $(this).hover(function(){
            $(this).css('background-color', $("#magiccontent").css('background-color'))
        },function(){
            if(this.tempcol){
                $(this).css('background-color', $("#magiccontent").css('background-color'));
                
            }else{
                $(this).css('background-color', this.colback);
            }
        });
    });
    function toggleselect(ele){
        $("#magicmenu ul li a").each(function(i){
            $(this).css('background-color', this.colback);
            this.tempcol = false;
        });
        $(ele).css('background-color', $("#magiccontent").css('background-color'));
        ele.tempcol = true;
    }
    
    /* Cookies section */
    if($.cookie('selectmenu')){
        if($.cookie('selectmenu') == "full"){
            $("#magicmini").show();
            $("#magicmaxi").show();
            $(".magic2").each(function () {toggleselect(this);});
        }else if($.cookie('selectmenu') == "light"){
            $("#magicmini").show();
            $(".magic3").each(function () {toggleselect(this);});
        }else if($.cookie('selectmenu') == "close"){
            $(".magic1").each(function () {toggleselect(this);});
        }
    }else{
        $("#magicmini").show();
        toggleselect("#magicmenu .magic3");
    }
});
/*--- MAGIC BAR END ---*/
/*--- MULTIPLE CHECKBOX/ACTION START---*/
$(document).ready(function(){
	function checkAll(id, pID){
		$("input[@id=" + pID + "][type='checkbox']").attr('checked', $('#' + id).is(':checked'));
		
	}
	
	function getChecked(id)
	{
	    if (!isCheckedById(id))
	    {
	        //alert ("Veuillez choisir un ou plusieurs documents");
	        return false;
	    }
	    else
	    {
	        listValue = "";
	        $("input[@id="+id+"]:checked").each(function(){
	            listValue = listValue+$(this).attr('value')+';';
	        });
	        
	        return listValue;
	    }               
	}
	
	function isCheckedById(id)
	{
	    var checked = $("input[@id="+id+"]:checked").length;
	    if (checked == 0)
	    {
	        return false;
	    }
	    else
	    {
	        return true;
	    }
	}
	
    $(".document_check").click(function () {
        $("#docid").val(getChecked("document_check"));
		if(isCheckedById("document_check")){
			if($("#magicmini").css("display") == "none" && $("#magicmaxi").css("display") == "none"){
	            //$("#magiccontent").hide();
                $("#magicmini").slideDown("slow");
	            $("#magicmini").show();
				return true;
	        }
	        if($("#magiccontent").css("display") == "none"){
	            $("#magicmaxi").hide();
	            $("#magiccontent").slideDown("slow");
				return true;
	        }
			
		}
		if(!isCheckedById("document_check")){
            $("#magiccontent").slideUp("slow",function(){
	            $("#magicmaxi").hide();
	            $("#magicmini").hide();
	            $(this).show();
				return false;
	        });
        }
		
    });
	
	$(".multiHighlight").click(function () {
		checkedDoc = getChecked("document_check").split(';');
		i = 0;
		$.post("/file/_multiHighlight", {documents: ""+getChecked("document_check")+""}, function(data){
            if(data.length >0) {
				
				for(checkedDoc, i=0; stop; i++){
					
	                if(data == "1"){
	                    $('#document_'+checkedDoc[i]).addClass("highlightFile");   
	                }
	                else if(data == "0"){
	                    $('#document_'+checkedDoc[i]).removeClass("highlightFile");   
	                }
					stop = !(checkedDoc[i].length < i);
				}
            }
        });
	});
	

	
	$(".showMultiMove").click(function () {
		$.post("/menu/getUserFolderList", {}, function(data){
            $("#magicmaxi").html(data);
			
        });
        $("#magicmaxi").show();
		
    });
	

	$(".multiTrash").click(function(){
	    $.post("/file/trashFiles",  {documents: ""+getChecked("document_check")+""}, function(data){
			$('#data-content').html(data);
		});
	});

	
	$("#checkAllDoc").click(function(){
	   	checkAll("checkAllDoc","document_check");
		$("#docid").val(getChecked("document_check"));
		if(isCheckedById("document_check")){
            if($("#magicmini").css("display") == "none" && $("#magicmaxi").css("display") == "none"){
                //$("#magiccontent").hide();
                $("#magicmini").slideDown("slow");
                $("#magicmini").show();
                return true;
            }
            if($("#magiccontent").css("display") == "none"){
                $("#magicmaxi").hide();
                $("#magiccontent").slideDown("slow");
                return true;
            }
        }
        if(!isCheckedById("document_check")){
            $("#magiccontent").slideUp("slow",function(){
                $("#magicmaxi").hide();
                $("#magicmini").hide();
                $(this).show();
                return false;
            });
        }
		
	});
	
});

/*--- MULTIPLE CHECBOX/ACTION END ---*/



/* *** RECHARGEMENT DE BLOC *** */
var currentMainUrl;

// chargement de la div
function loadMain(url) {
	if(!setLoading('#dMainRight'))
		return;
	$('#dMainRightIframe').hide();		
	$("#top-content").html("");
	$('#dMainRight').show();
	$('#dMainRight').load(url);
	$('#data-content').load(url);
	currentMainUrl = url;
}

// chargement de l'iframe principale
function loadMainIframe(url, height) {
	if(!setLoading('#dMainRight'))
		return;	
	$('#dMainRight').hide();
	$("#top-content").html("");
	$('#dMainRightIframe').show();
	$('#mainRightIframe')[0].style.height = height;
	$('#mainRightIframe')[0].src = url;
	currentMainUrl = url;	
}


function refreshMain() {
	if (currentMainUrl)
		loadMain(currentMainUrl);	
}


/* *** CONTROLE DES APPELS AJAX *** */
var isLoading = false;
function setLoading(id) {
	if (isLoading) {
		alert('La page est en cours de chargement, merci de patienter');
		return false;
	}		
	//isLoading = true;
	$(id).html('<div style="position:absolute;width:300px;background:#ccc;border:solid 2px #666;padding:10px;color:white;text-align:center;font-weight:bold;"><img src="/public/images/fr_FR/loading1.gif" height="10" width="10" /> loading ...</div>' + $(id).html());
	return true;
}

