//Chrome || Safari browser.
$.browser.chrome    = $.browser.webkit && !!window.chrome;
$.browser.safari    = $.browser.webkit && !window.chrome;
$.browser.firefox   = $.browser.mozilla;

var stats,
camera,
scene,
projector,
renderer,
particleMaterial;

var SEPARATION = 200,
    AMOUNTX = 10,
    AMOUNTY = 10,
    particles, particle;

function resetCanvas () {
    cancelRequestAnimFrame(request);                

    planes              = null;
    plane               = null;
    scene               = null;
    group               = null;
    sphere              = null;
    
    camPos		= null;
    objectsPositions	= null;
    displayedPlanes     = null;
    
    groupRotation	= null;
    camRotation		= null;
    
    projector           = null;
    renderer            = null;
    container           = null;
    stats               = null;
    
    camAngle        	= null;
    camRatio            = null;
    camNear		= null;
    camFar		= null;
    camPosX		= null;
    camPosY		= null;
    camPosZ		= null;
    camRadius           = null;
    
    removeListeners ();
}
    
initVarsCanvas = function (){
    // internal vars
    container                           = $('#container');
    container.append('<div id="dummy"></div>');
    $('#dummy').css( {
        'position'  : 'absolute',
        'top'       : '0',
        'width'     : ieWW,
        'z-index'   :'11',
        'left'      : '0',
        'height'    :'100%',
        'overflow'  :'hidden'
    });
	
    planes              = [];
    camPos		= [];
    objectsPositions	= [];
    displayedPlanes     = [];
	
    xm                  = null;
        
    plane = {
        id		: 0,
        width		: 96,
        height		: 72,
        position    	: {
            x:0, 
            y:0, 
            z:0
        },
        geom		: null,
        material        : null,
        stroke		: null,
        plan 		: null,
        init		: function(doubleSided, category, tags, active, presta, title, miniature, activeTag, activeCat, activePresta, activeClassement, laureat, finaliste, participant, classement) {
            this.stroke  = new THREE.MeshNormalMaterial( {
                opacity: 1, 
                wireframe: true
            });
	
            this.activeMaterial = new THREE.MeshNormalMaterial({
                opacity: 0.85, 
                wireframe: false
            });
            
            this.geom                   = new THREE.PlaneGeometry(this.width, this.height);
            this.plan                   = new THREE.Mesh( this.geom, [this.activeMaterial, this.stroke ]);
            this.plan.doubleSided       = doubleSided;
            this.plan.category          = category;
            this.plan.laureat           = laureat;
            this.plan.finaliste         = finaliste;
            this.plan.participant       = participant;
            this.plan.classement        = classement;
            this.plan.tags              = tags;
            this.plan.presta            = presta;
            this.plan.title             = title;
            this.plan.miniature         = miniature;
            this.plan.active            = active;
            this.plan.activeTag         = activeTag;
            this.plan.activeCat         = activeCat;
            this.plan.activePresta      = activePresta;
            this.plan.activeClassement  = activeClassement;
//            console.log(this.geom)
        }
    };

		
    // Camera
    camAngle        	= 70;
    camRatio            = ieWW / ieWH;
    camNear		= 1;
    camFar		= 10000;
    camPosX		= 0;
    camPosY		= 0;
    camPosZ		= 1000;
    camRadius           = 300;
	
    // Rotations
    groupRotation		 = false;
    camRotation			 = false;
	
    // Navigateur
    mouseX 		= 0;
    mouseY 		= 0;
    windowHalfX         = ieWW / 2;
    windowHalfY         = ieWH / 2;
	
    // Rayons
    sphereRadius = 250; //Sphere radius
	
	
    // Objets 3D
    planeW = 96;
    planeH = 72;

    // Elements Graphiques
    if (ieWW < 1440) {
        closeProjectsSize   = 61;
    } else {
        closeProjectsSize   = 81;
    }
    
    navVisuelsSize      = 23;
    buteeProject        ='0';
    buteeLeftProject    ='0';
    
    activeMaterial = new THREE.MeshNormalMaterial({
        opacity: 0.8, 
        wireframe: false
    });
    
    inactiveMaterial = new THREE.MeshNormalMaterial({
        opacity: 0.1,
        wireframe: false
    });
    
    hiddenMaterial = new THREE.MeshBasicMaterial({
        opacity: 0,
        color  : '0xffffff',
        wireframe: false
    });
    
    strokeMaterial = new THREE.MeshNormalMaterial( {
        opacity: 1, 
        wireframe: true
    });
    
    laureatMaterial = new THREE.MeshBasicMaterial({
        opacity     :0.8, 
        wireframe   :false,
        map         :THREE.ImageUtils.loadTexture( 'images/obl-laureat-3d.png')
    });
        
    finalisteMaterial = new THREE.MeshBasicMaterial({
        opacity     :0.8, 
        wireframe   :false,
        map         :THREE.ImageUtils.loadTexture( 'images/obl-finaliste-3d.png')
    });
}   
 
initCanvas = function (){
    initVarsCanvas ();
    addListeners () ;
    addCanvas ();
    addList();
    animate ();
    attachScrollGroup ();
    getActiveAffichage (displayType);
    mapPlanes();
    releaseMenu(true);
    
}
	

function addCanvas() {
    // Camera Properties
    camera = new THREE.PerspectiveCamera( camAngle, camRatio, camNear, camFar );
    camera.position.x = camPosX;
    camera.position.y = camPosY;
    camera.position.z = camPosZ;
	
    // Scene Properties
    scene = new THREE.Scene();
	
    group  = new THREE.Object3D();
    sphere = new THREE.Mesh( new THREE.SphereGeometry( 50, 20, 20 ), new THREE.MeshNormalMaterial( {
        shading: THREE.SmoothShading, 
        opacity:0
    } ) );	


    for (var pi = 0; pi < projects.count; pi ++ ) {
        doubleSided = true;
        category        = projects[pi].category;
        tags            = projects[pi].tags;
        presta          = projects[pi].presta;
        title           = projects[pi].title;
        miniature       = projects[pi].miniature;
        
        
        finaliste       = projects[pi].finaliste;
        if (finaliste == '1'){
            finaliste = true;
        } else {
            finaliste = false;
        }
        
        laureat         = projects[pi].laureat;
        if (laureat == '1'){
            laureat = true;
        } else {
            laureat = false;
        }
        
        participant         = true;
        active              = true;
        activeTag           = true;
        activeCat           = true;
        activePresta        = true;
        activeClassement    = true;
        
        if(laureat == 1){
            classement = '2';
        } else if(finaliste == 1){
            classement = '1';
        } else if(finaliste == 0){
            classement = '0';
        } 

        
        
        plane.init(doubleSided, category, tags, active, presta, title, miniature, activeTag, activeCat, activePresta, activeClassement, laureat, finaliste, participant, classement);
        plane.id = pi;
        scene.add( plane.plan);
        displayedPlanes.push(true);
        planes.push( plane.plan );
        planes[pi].id = pi; // correction bug d'id 
        group.add( plane.plan );
    }
    
    projector = new THREE.Projector();
    scene.add( sphere );
    scene.add( group );	
    renderer = new THREE.CanvasRenderer();
    renderer.setSize( ieWW, ieWH );

    container.append( renderer.domElement );
//
//    stats = new Stats();
//    stats.domElement.style.position = 'absolute';
//    stats.domElement.style.top = '0px';
//    container.append( stats.domElement );

    $('canvas').attr('id','canvas');
    $('#container').append('<canvas id="canvas2" style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>');

}

/* _Listeners ---------------------------------------------------------------------*/
function addListeners () {
    $(document).bind( 'mousemove', onDocumentMouseOverRay);
    $(document).bind( 'mousemove', onDocumentMouseMove);
    $(document).bind( 'mousedown', onDocumentMouseDown);
}

function removeListeners () {
    $(document).unbind( 'mousemove', onDocumentMouseMove);
    $(document).unbind( 'mousemove', onDocumentMouseOverRay);
    $(document).unbind( 'mousedown', onDocumentMouseDown);
}


/* mapPlanes ---------------------------------------------------------------------*/
function mapPlanes() {
    if(!$.browser.safari && !$.browser.mozilla){
        for ( var i = 0; i < projects.count; i ++ ) {		
            // number
            var x = document.createElement( "canvas" );
            var xc = x.getContext( "2d" );
            x.width = 144;
            x.height = 108;
            xc.fillStyle = "white";
            xc.font = "11px GothamMedium";
            
            var strL = planes[i].title.length;
            var str  = planes[i].title;
            if(strL > 15){
                str = STR_wordwrap(str.toUpperCase(),15,"|").split('|');
                for (var line in str){
                    xc.fillText(str[line], 22, 18+(15*line)); // nom, x, y 
                }
            } else {
                var projectNumber = planes[i].title.toUpperCase();
                xc.fillText( projectNumber, 22, 18 ); // nom, x, y
            }

            
            var xm = new THREE.MeshBasicMaterial( {
                map: new THREE.Texture( x )
            });
            
            
            xm.map.needsUpdate = true;

            planes[i].materials[ 1 ] = xm;
            planes[i].doubleSided = true;
            planes[i].scale.x = -1;
            
            if(projects[i].finaliste == '1'){
                planes[i].materials[ 2 ] = finalisteMaterial;
            }
        
            if(projects[i].laureat == '1'){
                planes[i].materials[ 2 ] = laureatMaterial;
            }
            
            if(projects[i].finaliste == '0'){
                planes[i].materials[ 2 ] = hiddenMaterial;
            }
        }
    } 
}

/* Animate ---------------------------------------------------------------------*/
var request;

function animate(){
    request = requestAnimFrame(animate);
    render();
//    stats.update();
}


/* Render ----------------------------------------------------------------------*/
function render() {
    TWEEN.update();
    for(var i=0; i < projects.count+2; i++) {
        if( groupRotation == true) {
            scene.objects[ i ].lookAt( sphere.position );
        }
    }
	
	
    if( groupRotation == true) {
        group.rotation.x = group.rotation.x + Math.sin( new Date().getTime() * 0.0007 ) * 0.05;
        group.rotation.y = group.rotation.y + Math.sin( new Date().getTime() * 0.0003 ) * 0.4;
    }
    
    if( camRotation == true) {
        camera.position.x += ( mouseX - camera.position.x ) * 0.01;
        camera.position.z += ( mouseX - camera.position.x ) * 0.005;
        camera.position.y += ( -mouseY - camera.position.y )* 0.01;
    }
    
    camera.lookAt( scene.position );
    renderer.render( scene, camera );
}

/* Scrolls ----------------------------------------------------------------------*/
function attachScrollGroup () {
    hookEvent('dummy', 'mousewheel', onDocumentMouseScroll);
    
}

function onDocumentMouseScroll (e) {	
    scrolling = true;
    e = e ? e : window.event;
    var raw = e.detail ? e.detail : e.wheelDelta;
    if($.browser.mozilla){
        raw = -raw;
    }
    cancelEvent(e);
    scrollWheel(raw);
}

function scrollWheel (raw) {
    raw = parseInt(raw);
    groupRotation = false;
    group.rotation.y = group.rotation.y - (raw/360);
    setTimeout("attachScrollGroup()", 50);
}


/* Move mouse ---------------------------------------------------------------*/		
function onDocumentMouseMove(event) {
    mouseX = ( event.clientX - windowHalfX ) * 5;
    mouseY = ( event.clientY - windowHalfY ) * 5;
}

/* Interactivity ---------------------------------------------------------------*/
function onDocumentMouseDown( event ) {
    event.preventDefault();
    var vector = new THREE.Vector3( ( event.clientX / ieWW ) * 2 - 1, - ( event.clientY / ieWH ) * 2 + 1, 0.5 );
    projector.unprojectVector( vector, camera );
	
    var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );
	
    var intersects = ray.intersectObjects( planes );

    
    if ( intersects.length > 0 ) {	
        obj   = intersects[ 0 ].object;	
        objPos = camPos[obj.id]
        objPos = objPos.split(':');
        objPosX = objPos[0];
        objPosY = objPos[1];
        objPosZ = objPos[2];
	
        // Project Name
        projects.id = intersects[ 0 ].object.id;
        
        loadProjectInterface ();
        
        planes[oldRayid].geometry.vertices[0].position.x = - 48;
        planes[oldRayid].geometry.vertices[0].position.y =   36;
        planes[oldRayid].geometry.vertices[1].position.x =   48;
        planes[oldRayid].geometry.vertices[1].position.y =   36;
        planes[oldRayid].geometry.vertices[2].position.x = - 48;
        planes[oldRayid].geometry.vertices[2].position.y = - 36;
        planes[oldRayid].geometry.vertices[3].position.x =   48;
        planes[oldRayid].geometry.vertices[3].position.y = - 36;
        
        if ($.browser.safari || $.browser.mozilla){
            planes[oldRayid].materials[ 1 ] = activeMaterial;
        }
    }	
}
var oldRayid = 0;
/* Interactivity ---------------------------------------------------------------*/
function onDocumentMouseOverRay( event ) {
    event.preventDefault();
    var vector = new THREE.Vector3( ( event.clientX / ieWW ) * 2 - 1, - ( event.clientY / ieWH ) * 2 + 1, 0.5 );
    projector.unprojectVector( vector, camera );
	
    var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );
	
    var intersects = ray.intersectObjects( planes );

    if ( intersects.length > 0 ) {	

        planes[oldRayid].geometry.vertices[0].position.x = - 48;
        planes[oldRayid].geometry.vertices[0].position.y =   36;
        planes[oldRayid].geometry.vertices[1].position.x =   48;
        planes[oldRayid].geometry.vertices[1].position.y =   36;
        planes[oldRayid].geometry.vertices[2].position.x = - 48;
        planes[oldRayid].geometry.vertices[2].position.y = - 36;
        planes[oldRayid].geometry.vertices[3].position.x =   48;
        planes[oldRayid].geometry.vertices[3].position.y = - 36;
        
        if ($.browser.safari || $.browser.mozilla){
            planes[oldRayid].materials[ 1 ] = activeMaterial;
        }
        
        obj   = intersects[ 0 ].object;	
        objPos = camPos[obj.id];
        objPos = objPos.split(':');
        objPosX = objPos[0];
        objPosY = objPos[1];
        objPosZ = objPos[2];
	
        // Project Name
        projects.id = intersects[ 0 ].object.id;
        var x = document.createElement( "canvas" );
        var xc = x.getContext( "2d" );
        x.width = 144;
        x.height = 108;
        xc.fillStyle = "white";
        xc.font = "11px GothamMedium";
            
        var strL = planes[projects.id].title.length;
        var str  = planes[projects.id].title;
        if(strL > 15){
            str = STR_wordwrap(str.toUpperCase(),15,"|").split('|');
            for (var line in str){
                xc.fillText(str[line], 22, 18+(15*line)); // nom, x, y
            }
        } else {
            var projectNumber = planes[projects.id].title.toUpperCase();
            xc.fillText( projectNumber, 22, 18 ); // nom, x, y
        }

            
        var xm = new THREE.MeshBasicMaterial( {
            map: new THREE.Texture( x )
        });

        if ($.browser.safari || $.browser.mozilla){
            planes[obj.id].materials[ 1 ]   = xm;
            planes[obj.id].scale.x          = -1;
        }
        
        
        oldRayid = obj.id;

        planes[obj.id].geometry.vertices[0].position.x = - 72;
        planes[obj.id].geometry.vertices[0].position.y =   54
        planes[obj.id].geometry.vertices[1].position.x =   72;
        planes[obj.id].geometry.vertices[1].position.y =   54;
        planes[obj.id].geometry.vertices[2].position.x = - 72;
        planes[obj.id].geometry.vertices[2].position.y = - 54;
        planes[obj.id].geometry.vertices[3].position.x =   72;
        planes[obj.id].geometry.vertices[3].position.y = - 54;

        

    } else {
        planes[oldRayid].geometry.vertices[0].position.x = - 48;
        planes[oldRayid].geometry.vertices[0].position.y =   36;
        planes[oldRayid].geometry.vertices[1].position.x =   48;
        planes[oldRayid].geometry.vertices[1].position.y =   36;
        planes[oldRayid].geometry.vertices[2].position.x = - 48;
        planes[oldRayid].geometry.vertices[2].position.y = - 36;
        planes[oldRayid].geometry.vertices[3].position.x =   48;
        planes[oldRayid].geometry.vertices[3].position.y = - 36;
        
        if ($.browser.safari || $.browser.mozilla){
            planes[oldRayid].materials[ 1 ] = activeMaterial;
        }
    }
}


/* Load Interface ------------------------------------------------------------------*/
function loadProjectInterface () {
    pauseRotations ();
    pauseAllPlanes ();
    removeListeners();
    releaseMenu(false);
    planesToCam (obj, objPosX, objPosY, objPosZ);
    $('body').append('<div id="projectInterface" style="width:100%; height:100%; position:absolute; z-index:150; "></div>');
    setTimeout("loadProjectsContent()"  , 1500);
    setTimeout("loadZoneVisuels()"      , 1600);
    setTimeout("addProjectsContent()"   , 1900);	
}

function loadProjectInterface2d () {
    $('body').append('<div id="projectInterface" style="width:100%; height:100%; position:absolute; z-index:150; "></div>');
    releaseMenu(false);
    setTimeout("listToCam()"  , 20);
    setTimeout("loadProjectsContent()"  , 800);
    setTimeout("loadZoneVisuels()"      , 1100);
    setTimeout("addProjectsContent()"   , 1400);
}

var unloadVisuelsInterval = '';

function unloadProjectInterface () {
    unloadVisuelsInterval = setInterval('unloadZoneVisuels()', 20);
    intervalCount = 0;
    releaseMenu(true);
    setTimeout("removeProjectsContent()", 400);
    setTimeout("planesToInit ()"        , 800);
    setTimeout("resumeRotations ()"     , 800);
    setTimeout("addListeners ()"        , 800);
    setTimeout("resumePlanes ()"        , 800);
}

function unloadProjectInterface2d () {
    unloadVisuelsInterval = setInterval('unloadZoneVisuels()', 20);
    intervalCount = 0;
    listToInit();
    releaseMenu(true);
    setTimeout("removeProjectsContent()", 800);	
}

/* loadZoneVisuels ------------------------------------------------------------------*/
function loadZoneVisuels () {
    clearTimeout('loadZoneVisuels');
    step = 0;
    scrollCount = 0;
    intervalCount = 0;
    visuelCurrentAngle = [];
    visuelTargetAngle  = [];
    limitDown = true;
    limitUp = false;
    var vimage  = [];
    var vtarget = [];
    
    computeSize ();
    
    $('#projectInterface').append('<div id="visuels" style="z-index:55; position:absolute; width:100%; height:100%;">&nbsp;</div>');

    for(var i=0;i<imagesArr.length; i++) {
        $("#visuels").append('<div id="hideVisuel-'+i+'"></div><div id="visuel-'+i+'"></div>');
		
        var adV = -45 * i;
		
        // angle radians
        var aV = adV * (Math.PI/180);
		
        // rayon
        var rV = ieWW/2 + ieWW/4 ;
		
        var aS = (rV * Math.cos(aV)) - vW / 2 - ieWW/4; // x - adjacent side
        var oS = Math.round((rV * Math.sin(aV)) + vT); // y - opposite side

		
        $("#visuel-"+i).rotate(adV);
         
        $("#visuel-"+i).attr('data-adV',adV);
        $("#visuel-"+i).css({
            'position'  :'absolute',
            'width'     :vW,
            'height'    :vH+'px',
            'z-index'   :'50',
            'background':'white',
            'opacity'   :'0',
            'left'      :aS+'px',
            'top'       :oS+'px',
            'overflow'  :'hidden'
        });
        $("#hideVisuel-"+i).css({
            'position'  :'absolute',
            'width'     :0,
            'height'    :vH+'px',
            'z-index'   :'51',
            'background':'black',
            'opacity'   :'1',
            'left'      :aS+'px',
            'top'       :oS+'px',
            'overflow'  :'hidden'
        });
        
        $('#hideVisuel-'+i).delay(200).animate({
            width   : vW,
            left    : aS+'px'
        },500, 'easeInSine', function () {
            $(this).delay(100).animate({
                width   : 0
            },500, 'easeOutExpo');
        });
        
        
        $('#visuel-'+i).delay(700).animate({
            'opacity' : 1
        },500, 'easeInSine');

       
        vimage.push('upload/projects/'+imagesArr[i]);
        vtarget.push('visuel-' +i);
        
        if(i == imagesArr.length-1){
            preload.loadimage(vimage, vtarget, vW, vH);
        }
    }
}

/* unloadZoneVisuels ------------------------------------------------------------------*/

oldStep     = 0;
hiStep      = 0;
hiStep_i    = 4;
function unloadZoneVisuels () {
    var speed = 1.4;
    for(var i=0;i<imagesArr.length; i++) {
        if( intervalCount == 0) {
            visuelCurrentAngle[i]  = parseInt($("#visuel-"+i).attr('data-adV'));
            visuelTargetAngle[i]   = 0;
            if(visuelCurrentAngle[i] < 0) {
                d = -1;
            } else {
                d = 1;
            }
            steps = d*(visuelCurrentAngle[i] / 45);
            if( steps > hiStep ) {
                hiStep = steps;
                hiStep_i = i;
                dd = -d;
            }
        }
		
	
        Distance = visuelTargetAngle[i] - visuelCurrentAngle[i];
        newDistance = Distance / speed ;
        visuelCurrentAngle[i] = visuelTargetAngle[i] - newDistance;
		
		
        // angle radians
        var aRad = visuelCurrentAngle[i] * (Math.PI/180);
		
        // rayon
        var rV = ieWW/2 + ieWW/4;

        // Calcul des nouvelles positions x & y à partir du nouvel angle
        var vLeft = (rV * Math.cos(aRad)) - vW / 2 - ieWW/4; // x - adjacent side
        var vTop = (rV * Math.sin(aRad)) + vT; // y - opposite side
		
        // Rotation du visuel à partir du nouvel angle
        $("#visuel-"+i).rotate(visuelCurrentAngle[i]);
        $('#visuel-'+i+' img').animate({
            'opacity':0
        },0,"easeOutSine");
        
        // Positionnement css du visuel
        $("#visuel-"+i).css({
            'left':vLeft+'px',
            'top':vTop+'px'
        });
		

    }
    
    var deleteVisuels = function (){
        for(i=0;i<imagesArr.length; i++) {
            $('#visuel-'+i).remove();
            $('#hideVisuel-'+i).remove();   
            $('#visuels').remove();
        }
    }
    
    if( visuelTargetAngle[hiStep_i] - dd*(visuelCurrentAngle[hiStep_i]) < 0.2 ) {
        clearInterval(unloadVisuelsInterval);
        intervalCount = 0;
        console.log('cleared Interval');
        for(i=0;i<imagesArr.length; i++) {
            $('#visuel-'+i).delay(50*i).animate({
                'opacity':0
            },200,"easeOutSine");
            setTimeout(function() {deleteVisuels()} ,800)
        }
    }
    intervalCount ++;
}


/* Scroll Visuels ------------------------------------------------------------------*/

function initScrollVisus (d){
    var scrollInterval = '';
    var speed = 1.4;
    var increaseAngle = 45;
    if(d == 1){
        if(limitUp != true ){
            //clearInterval(scrollInterval);
            step ++;
            scrollInterval = setInterval (function () {
                scrollVisus(d, increaseAngle, speed, scrollInterval);
            }, 20);        
        } else {
//            console.log('limitUP') 
        }
    } else {
        if(limitDown != true ){
            //clearInterval(scrollInterval);
            step --;
            scrollInterval = setInterval (function () {
                scrollVisus(d, increaseAngle, speed, scrollInterval);
            }, 20);
        } else {
//            console.log('limitDOWN')
        }
    }
}



function controlVisus (){
    if(step != 0) {
        console.log('down start');
        $('#addArrow_NavT_Embed').removeClass('inactive');
        $('#addArrow_NavT_Embed').css({
            'opacity':1
        });
    } else {
        console.log('down stop');
        $('#addArrow_NavT_Embed').css({
            'opacity':0.2
        });
        $('#addArrow_NavT_Embed').addClass('inactive');
    }
    
    if (step != imagesArr.length-1){
//        console.log('up start');
        $('#addArrow_NavB_Embed').css({
            'opacity':1
        });
        $('#addArrow_NavB_Embed').removeClass('inactive');
    } else {
//        console.log('up stop');
        $('#addArrow_NavB_Embed').css({
            'opacity':0.2
        });
        $('#addArrow_NavB_Embed').addClass('inactive');
    }
}

function scrollVisus (d, increaseAngle, speed, scrollInterval) {
    controlVisus(step);
    
    for (var i=0; i < imagesArr.length; i++ ) {
        var visuel = $("#visuel-"+i);
        if( intervalCount == 0) {
            visuelCurrentAngle[i]  = parseInt(visuel.attr('data-adV'));
            visuelTargetAngle[i]  = visuelCurrentAngle[i] + (increaseAngle * d);
        }
		
		
        Distance = visuelTargetAngle[i] - visuelCurrentAngle[i];
        newDistance = Distance / speed ;
        visuelCurrentAngle[i] = visuelTargetAngle[i] - newDistance;
		
        // on cale au pixel
        if( d*(visuelTargetAngle[i] - visuelCurrentAngle[i]) < 0.1 ) {
            visuelCurrentAngle[i] = visuelTargetAngle[i];
            visuel.attr('data-adV',visuelTargetAngle[i]);
            clearInterval(scrollInterval);
            intervalCount = -1;
			
            if(step == imagesArr.length-1) {
                limitUp = true;
            }
			
            if(step == 0) {
                //                $('#addArrow_NavT_Embed').css({'opacity':0.2});
                //                $('#addArrow_NavT_Embed').addClass('inactive');
                limitDown = true;
            }
			
            if (step != 0) {
                //                $('#addArrow_NavT_Embed').removeClass('inactive');
                //                $('#addArrow_NavT_Embed').css({'opacity':1});
                limitDown = false;
            }
			
            if (step != imagesArr.length-1) {
                //                $('#addArrow_NavB_Embed').css({'opacity':1});
                //                $('#addArrow_NavB_Embed').addClass('inactive');
                limitUp = false;
            }
        }
		
		
        // angle radians
        var aRad = visuelCurrentAngle[i] * (Math.PI/180);
        //
        // rayon
        var rV = (ieWW/2) + (ieWW/4);
		
        // Calcul des nouvelles positions x & y à partir du nouvel angle
        var vLeft = Math.round((rV * Math.cos(aRad)) - (vW / 2) - (ieWW/4)); // x - adjacent side
        var vTop  = Math.round((rV * Math.sin(aRad)) + vT); // y - opposite side
		
        // Rotation du visuel à partir du nouvel angle
        visuel.rotate(visuelCurrentAngle[i]);
//    visuel.css({'-webkit-transform': visuelCurrentAngle[i]});
        
        // Positionnement css du visuel
        visuel.css({
            'left':parseInt(vLeft,10)+'px',
            'top':parseInt(vTop,10)+'px'
        });
       
		
    }	
	
    intervalCount ++;
}


/* loadProjectsContent -----------------------------------------------------------------*/
function loadProjectsContent () {
    var i           = projects.id;
    title           = projects[i].title;
    
    var regPipe     = new RegExp('[|]', 'gi');
    title           = title.replace(regPipe," ");
    //console.log(title);
    
    url             = projects[i].url;
    shortUrl        = projects[i].url;
    projectText     = projects[i].projectText;
    agency          = projects[i].agency;
    agencyText      = projects[i].agencyText;
    agencyUrl       = projects[i].agencyUrl;
    shortAgencyUrl  = projects[i].agencyUrl;   
    category        = projects[i].category;
    categoryName    = projectCategories[parseInt(category)];
    tag             = projects[i].tags;
    tagName         = projectTags[parseInt(tag)];
    images          = projects[i].images;
    finaliste       = projects[i].finaliste;
    laureat         = projects[i].laureat;
    
    imagesArr       = images.split(';');
}

function addProjectsContent () {
	
    var i = projects.id;    
    var regPipe = new RegExp('[|]', 'gi');
    title     = title.replace(regPipe," ");
    //console.log(title);
    var projectInterface = $('#projectInterface');    
    projectInterface.append('<div id="projectId"><div>PROJET '+i+'</div></div>');
/**/    projectInterface.append('<div id="projectTitle"><div style="position: absolute; bottom: -31px; margin-bottom:10px;">'+title.toUpperCase()+'<div id="agency"><div>PAR '+agency.toUpperCase()+'</div></div></div></div>');
//    projectInterface.append('<div id="agency"><div>PAR '+agency.toUpperCase()+'</div></div>');
    projectInterface.append('<div id="projectCategory"><div>'+categoryName.toUpperCase()+'</div></div>');
    projectInterface.append('<div id="projectTag"><div>'+tagName.toUpperCase()+'</div></div>');	    
    projectInterface.append('<div id="projectRating"><div></div></div>');
    
    var hSpace = 36;
    var headingFont  = 'GothamLight';
    var infoFont     = 'standard0758';
    var textFont     = 'GothamMedium';
    
    if(planes[i].laureat){
        $('#projectRating').css({
            'position'           :'absolute',
            'width'              :'0px',
            'height'             :'123px',
            'z-index'            :'109',
            'display'            :'block',
            'left'               :vL + vW - 123+'px',
            'top'                :vT + 'px',
            'overflow'           :'hidden'
        });
        
        $('#projectRating').delay(800).animate({
            'width':'123px'
        },300,'easeOutSine');
        
        $('#projectRating div').css({
            'background'         :'url(images/obl-laureat-large.png) no-repeat',
            'position'           :'absolute',
            'width'              :'123px',
            'height'             :'123px'
        });
    } else if(planes[i].finaliste){
        $('#projectRating').css({
            'position'           :'absolute',
            'width'              :'0px',
            'height'             :'123px',
            'z-index'            :'109',
            'display'            :'block',
            'left'               :vL + vW - 123+'px',
            'top'                :vT + 'px',
            'overflow'           :'hidden'
        });
        
        $('#projectRating').delay(800).animate({
            'width':'123px'
        },300,'easeOutSine');
        
        $('#projectRating div').css({
            'background'         :'url(images/obl-finaliste-large.png) no-repeat',
            'position'           :'absolute',
            'width'              :'123px',
            'height'             :'123px'
        });
    }
    
    // Css
    $('#projectTitle').css({
        'position'      :'absolute',
        'font-size'     :30/fontRatio+'px',
        'z-index'       :'120',
        'font-family'   :headingFont, 
        'color'         :'white',
        'width'         :vW,
        'height'        :hSpace,
        'left'          :vL,
        'top'           :vT - 180,
        'opacity'       :'0',
        'overflow'      :'visible'
    });
    $('#agency').css({
/*        'position'      :'absolute',
        'font-size'     :30/fontRatio+'px',
        'z-index'       :'120',
        'font-family'   :headingFont, 
*/        'color'         :siteGreyColor
/*        'width'         :vW,
        'height'        :hSpace,
        'left'          :vL,
        'top'           :vT + 16,
        'opacity'       :'0',
        'overflow'      :'hidden'
*/    });
    $('#projectId').css({
        'position'      :'absolute',
        'font-size'     :'8px',
        'font-family'   :infoFont,
        'color'         :'white',
        'width'         :vW,
        'height'        :hSpace,
        'left'          :vL,
        'top'           :vT + vH + 160,
        'opacity'       :'0',
        'z-index'       :'121',
        'overflow'      :'hidden'
    });
    $('#projectCategory').css({
        'position'      :'absolute',
        'font-size'     :'8px',
        'font-family'   :infoFont, 
        'color'         :siteGreyColor,
        'width'         :vW/2,
        'height'        :hSpace,
        'left'          :vL,
        'top'           :vT + vH + 175,
        'opacity'       :'0',
        'z-index'       :'121',
        'overflow'      :'hidden'
    });
    $('#projectTag').css({
        'position'      :'absolute',
        'font-size'     :'8px',
        'font-family'   :infoFont, 
        'color'         :siteGreyColor,
        'width'         :vW/2,
        'height'        :hSpace,
        'left'          :vL,
        'top'           :vT + vH + 190,
        'opacity'       :'0',
        'z-index'       :'121',
        'overflow'      :'hidden'
    });	
	
	
    // Animation
    $('#projectTitle').animate ({
        'top':vT - 100/fontRatio,
        'opacity':1
    },450,'easeOutQuad');
    $('#agency').delay(100).animate({
        'top':vT - 64/fontRatio,
        'opacity':1
    },350,'easeOutQuad');
    $('#projectId').delay(200).animate ({
        'top':vT + vH + 105/fontRatio,
        'opacity':1
    },200,'easeOutSine');
    $('#projectCategory').delay(300).animate ({
        'top':vT + vH + 120/fontRatio,
        'opacity':0.5
    },150,'easeOutSine');
    $('#projectTag').delay(400).animate ({
        'top':vT + vH + 135/fontRatio,
        'opacity':0.5
    },100,'easeOutSine');
    
    
    // RegisterElements
    addLink ('#projectInterface', 'Visiter', url, '40', '120', vH + vT + 20, vL, '#ffffff', '#ffffff', 25, 7, '120', '1', false, false);
    addLink ('#projectInterface', 'Infos', addProjectsInfos, '40', '40', vH + vT + 20, vL + 130, siteMainColor, '#ffffff', 0, 0,  '100', '1', true, true);
    if(canvasDisplay == '3d'){
        addClose('#projectInterface', closeProjectsSize, 50, vL + vW - 40, unloadProjectInterface);   
    } else {
        addClose('#projectInterface', closeProjectsSize, 50, vL + vW - 40, unloadProjectInterface2d);
    }
    
    addArrow_NavB ('#projectInterface', 24, 9, vT + vH + 30, vL + vW - 40, function (){
        initScrollVisus(1);
    }, 110);
    addArrow_NavT ('#projectInterface', 24, 9, vT + vH + 30, vL + vW - 80, function (){
        initScrollVisus(-1);
    }, 110);
    
    addArrowNav_L('#projectInterface', 35, vT + vH/2-18, vL - 40, function (){
        controlNavProjects('prev');
    },110);
    
    addArrowNav_R('#projectInterface', 35, vT + vH/2-18, vL + vW + 22, function (){
        controlNavProjects('next');
    },110);
    controlNavProjects();
    controlVisus();
    
}

controlNavProjects = function (sens){
        var displayedPlanesPos = [];
        for(var i=0;i<planes.length;i++){
            if(displayedPlanes[i] == true){
                displayedPlanesPos.push(i);
            }
        }
        for(i=0;i<displayedPlanesPos.length;i++){
            if(parseInt(projects.id) == parseInt(displayedPlanesPos[i])){
                var prevpos     = displayedPlanesPos[i-1];
                var nextpos    = displayedPlanesPos[i+1];
            }
        }
    if(sens == 'prev'){
        projects.id     = prevpos;
        unloadVisuelsInterval = setInterval('unloadZoneVisuels()', 20);
        setTimeout("loadZoneVisuels()", 3000);
        setTimeout("updateProjectsContent ()", 700);
    } else if(sens == 'next') {
        projects.id     = nextpos;
        unloadVisuelsInterval = setInterval('unloadZoneVisuels()', 20);
        setTimeout("loadZoneVisuels()", 3000);
        setTimeout("updateProjectsContent ()", 700);
    }
    
    for(i=0;i<displayedPlanesPos.length;i++){
        if(parseInt(projects.id) == parseInt(displayedPlanesPos[i])){
            if(i == 0){
                $('#ArrowNav_L_Embed').css({'opacity':'0.2'});
                $('#ArrowNav_L_Embed').addClass('inactive');
            } else if(i == displayedPlanesPos.length-1){
                $('#ArrowNav_R_Embed').css({'opacity':'0.2'});
                $('#ArrowNav_R_Embed').addClass('inactive');
            } else {
                $('#ArrowNav_R_Embed').removeClass('inactive');
                $('#ArrowNav_L_Embed').removeClass('inactive');
                $('#ArrowNav_R_Embed').css({'opacity':'1'});
                $('#ArrowNav_L_Embed').css({'opacity':'1'});
            }
        }
    }
}

updateProjectsContent = function (){
    loadProjectsContent ();
    var i            = projects.id;
    var hSpace       = 36;
    var headingFont  ='GothamLight';
    var infoFont     ='standard0758';
    var textFont     ='GothamMedium';
    
    $('#projectId').empty().append('<div>PROJET '+i+'</div>');    
/**/    $('#projectTitle').empty().append('<div style="position: absolute; bottom: -31px; margin-bottom:10px;">'+title.toUpperCase()+'<div id="agency"><div>PAR '+agency.toUpperCase()+'</div></div></div>');
//    $('#agency').empty().append('<div>PAR '+agency.toUpperCase()+'</div>');
    $('#projectCategory').empty().append('<div>'+categoryName.toUpperCase()+'</div>');
    $('#projectTag').empty().append('<div>'+tagName.toUpperCase()+'</div>');
    
    $('#projectRating').empty().append('<div></div>');

    if(planes[i].laureat){
        $('#projectRating').css({
            'position'           :'absolute',
            'width'              :'0px',
            'height'             :'123px',
            'z-index'            :'109',
            'display'            :'block',
            'left'               :vL + vW - 123+'px',
            'top'                :vT + 'px',
            'overflow'           :'hidden'
        });
        
        $('#projectRating').delay(800).animate({
            'width':'123px'
        },300,'easeOutSine');
        
        $('#projectRating div').css({
            'background'         :'url(images/obl-laureat-large.png) no-repeat',
            'position'           :'absolute',
            'width'              :'123px',
            'height'             :'123px'
        });
    } else if(planes[i].finaliste){
        $('#projectRating').css({
            'position'           :'absolute',
            'width'              :'0px',
            'height'             :'123px',
            'z-index'            :'109',
            'display'            :'block',
            'left'               :vL + vW - 123+'px',
            'top'                :vT + 'px',
            'overflow'           :'hidden'
        });
        
        $('#projectRating').delay(800).animate({
            'width':'123px'
        },300,'easeOutSine');
        
        $('#projectRating div').css({
            'background'         :'url(images/obl-finaliste-large.png) no-repeat',
            'position'           :'absolute',
            'width'              :'123px',
            'height'             :'123px'
        });
    }
    
    
    
    // Css
    $('#projectTitle').css({
        'position'      :'absolute',
        'font-size'     :30/fontRatio+'px',
        'z-index'       :'120',
        'font-family'   :headingFont, 
        'color'         :'white',
        'width'         :vW,
        'height'        :hSpace,
        'left'          :vL,
        'top'           :vT - 180,
        'opacity'       :'0',
        'overflow'      :'visible'
    });
    
    $('#agency').css({
/*        'position'      :'absolute',
        'font-size'     :30/fontRatio+'px',
        'z-index'       :'120',
        'font-family'   :headingFont, 
*/        'color'         :siteGreyColor
/*        'width'         :vW,
        'height'        :hSpace,
        'left'          :vL,
        'top'           :vT + 16,
        'opacity'       :'0',
        'overflow'      :'hidden'
*/    });
    $('#projectId').css({
        'position'      :'absolute',
        'font-size'     :'8px',
        'font-family'   :infoFont,
        'color'         :'white',
        'width'         :vW,
        'height'        :hSpace,
        'left'          :vL,
        'top'           :vT + vH + 160,
        'opacity'       :'0',
        'z-index'       :'121',
        'overflow'      :'hidden'
    });
    $('#projectCategory').css({
        'position'      :'absolute',
        'font-size'     :'8px',
        'font-family'   :infoFont, 
        'color'         :siteGreyColor,
        'width'         :vW/2,
        'height'        :hSpace,
        'left'          :vL,
        'top'           :vT + vH + 175,
        'opacity'       :'0',
        'z-index'       :'121',
        'overflow'      :'hidden'
    });
    $('#projectTag').css({
        'position'      :'absolute',
        'font-size'     :'8px',
        'font-family'   :infoFont, 
        'color'         :siteGreyColor,
        'width'         :vW/2,
        'height'        :hSpace,
        'left'          :vL,
        'top'           :vT + vH + 190,
        'opacity'       :'0',
        'z-index'       :'121',
        'overflow'      :'hidden'
    });	
    
    
    // Animation
    $('#projectTitle').animate ({
        'top':vT - 100/fontRatio,
        'opacity':1
    },450,'easeOutQuad');
    $('#agency').delay(100).animate({
        'top':vT - 64/fontRatio,
        'opacity':1
    },350,'easeOutQuad');
    $('#projectId').delay(200).animate ({
        'top':vT + vH + 105/fontRatio,
        'opacity':1
    },200,'easeOutSine');
    $('#projectCategory').delay(300).animate ({
        'top':vT + vH + 120/fontRatio,
        'opacity':0.5
    },150,'easeOutSine');
    $('#projectTag').delay(400).animate ({
        'top':vT + vH + 135/fontRatio,
        'opacity':0.5
    },100,'easeOutSine');
    
    $('#embedLink-Visiter').remove();
    $('#embedLink-Infos').remove();
    $('#addArrow_NavT_Embed').remove();
    $('#addArrow_NavB_Embed').remove();
    
    
    // RegisterElements
    addLink ('#projectInterface', 'Visiter', url, '40', '120', vH + vT + 20, vL, '#ffffff', '#ffffff', 25, 7, '120', '1', false, false);
    addLink ('#projectInterface', 'Infos', addProjectsInfos, '40', '40', vH + vT + 20, vL + 130, siteMainColor, '#ffffff', 0, 0,  '100', '1', true, true);
    

    addArrow_NavB ('#projectInterface', 24, 9, vT + vH + 30, vL + vW - 40, function (){
        initScrollVisus(1);
    }, 110);
    addArrow_NavT ('#projectInterface', 24, 9, vT + vH + 30, vL + vW - 80, function (){
        initScrollVisus(-1);
    }, 110);
    
    controlVisus();
}

function removeProjectsContent () {
	
    var i = projects.id;
    var projectInterface = $('#projectInterface');    
    
    // Animation
    $('#projectTitle').animate ({
        'width':0
    },350,'easeOutSine', function(){
        $(this).remove ()
    });
    $('#projectRating').animate({
        'width':'0px'
    },300,'easeOutSine');
    $('#agency').delay(100).animate({
        'width':0
    },350,'easeOutSine', function(){
        $(this).remove ()
    });
    $('#projectId').delay(200).animate ({
        'width':0
    },250,'easeOutSine', function(){
        $(this).remove ()
    });
    $('#projectCategory').delay(250).animate ({
        'width':0
    },200,'easeOutSine', function(){
        $(this).remove ()
    });
    $('#projectTag').delay(300).animate ({
        'width':0
    },150,'easeOutSine', function(){
        $(this).remove ();
        projectInterface.remove();
    });
    
}

function addProjectsInfos () {

    var i = projects.id;
    var margin = 40;
    var projectInterface = $('#projectInterface');
    
    projectInterface.append('<div id="projectInfos"></div>');
    var projectInfos = $('#projectInfos');
    projectInfos.css({
        'position'      :'absolute',
        'z-index'       :'110',
        'width'         : vW / 3,
        'left'          : 0,
        'height'        :'100%',
        'background'    : siteMainDarkColor,
        'color'         :'white',
        'font-family'   :'GothamLight',
        'font-size'     :'11px',
        'line-height'   :'15px',
        'opacity'       :'0',
        'background-image':'url(images/pattern-scrollBars.png)'
    });
    
    projectInfos.animate({
        'width' : vW + margin * 4 + vL
    },500,'easeOutExpo');
    projectInfos.css({
        'opacity':'0.92'
    });
    
    projectInfos.append('<div id="hideProjectInfosL"></div><div id="projectInfosL"><span>LE PROJET</span>'+ projectText +'<a href="'+url+'" target="_blank">Site Projet</a></div>');
    projectInfos.append('<div id="hideProjectInfosR"></div><div id="projectInfosR"><span>L\'AGENCE</span>'+ agencyText +'<a href="'+agencyUrl+'" target="_blank">Site Agence</a></div>');
    var projectInfosL  = $('#projectInfosL');
    var projectInfosR  = $('#projectInfosR');
    var hideL = $('#hideProjectInfosL');
    var hideR = $('#hideProjectInfosR');
    
    
    $('#projectInfos span').css({
        'clear'         :'both',
        'font-family'   :'GothamMedium',
        'font-size'     :'15px',
        'display'       :'block',
        'height'        :'45px',
        'color'         :siteGreyColor
    });
    
    $('#projectInfos a').css({
        'display'           :'block',
        'height'            :'30px',
        'clear'             :'both',
        'padding-top'       :'20px',
        'color'             :siteMainColor,
        'text-decoration'   :'underline'
    });
    
    hideR.css ({
        'position'  :'absolute',
        'width'     : ((vW + margin * 4)/2)-margin,
        'left'      : vL,
        'top'       : vT + 30,
        'height'    :'100%',
        'overflow'  :'hidden',
        'opacity'   :'1',
        'background':siteMainDarkColor,
        'z-index'   :'121',
        'background-image':'url(images/pattern-scrollBars.png)'
    })

    hideL.css ({
        'position'  :'absolute',
        'width'     : ((vW + margin * 4)/2)-margin,
        'left'      :(vW + margin * 4)/2 + vL,
        'top'       : vT + 30,
        'height'    :'100%',
        'background':siteMainDarkColor,
        'overflow'  :'hidden',
        'opacity'   :'1',
        'z-index'   :'121',
        'background-image':'url(images/pattern-scrollBars.png)'
    })
    
    projectInfosR.css({
        'position'  :'absolute',
        'width'     : ((vW + margin * 4)/2)-margin,
        'left'      : vL,
        'top'       : vT + 30,
        'height'    :'100%',
        'color'     :'white'
    });
    
    projectInfosL.css({
        'position'  :'absolute',
        'width'     :((vW + margin * 4)/2)-margin,
        'left'      :(vW + margin * 4)/2 + vL,
        'top'       : vT + 30,
        'height'    :'100%',
        'color'     :'white'
    });
    
    hideL.delay(400).animate({
        'width' : 0
    },500,'easeOutExpo');
    hideR.delay(550).animate({
        'width' : 0
    },500,'easeOutExpo');

    addLink ('#projectInfos', 'X', removeProjectsInfos, '40', '40', vH + vT +20, vL + 130, siteMainColor, '#ffffff', 0, 0,  '121', '1', true, true);    
}

function removeProjectsInfos () {
    var margin = 40;
    var projectInfos = $('#projectInfos');
    var hideL = $('#hideProjectInfosL');
    var hideR = $('#hideProjectInfosR');
    
    hideL.animate({
        'width' : vW / 2 - margin
    },500,'easeOutExpo');
    hideR.delay(150).animate({
        'width' : vW / 2 - margin
    },500,'easeOutExpo');
    projectInfos.delay(400).animate({
        'width' : 0
    },500,'easeOutExpo', function () {
        projectInfos.remove ();
    });
    
} 

/* planesToCam -----------------------------------------------------------------*/
function planesToCam (obj, objPosX, objPosY, objPosZ) {

    for (var i= obj.id; i>= 0; i-- ) {	
        var nx = (planes[i].position.x);
        var ny = (planes[i].position.y);
        var nz = (planes[i].position.z);
        objectsPositions.push(nx+'_'+ny+'_'+nz);
		
        var time = 400;
        var delay = 30 * i;
	
		
        var tweenHead	= new TWEEN.Tween(planes[obj.id-i].position)
        .to( {
            x: objPosX, 
            y: objPosY, 
            z: objPosZ
        }, time)
        .delay(delay)
        .easing( TWEEN.Easing.Quintic.EaseOut).start();
		
        var tweenSuite	= new TWEEN.Tween(planes[obj.id-i].rotation)
        .to( {
            x: 0, 
            y:0, 
            z:0
        }, time/3)
        .delay((delay)+100)
        .easing( TWEEN.Easing.Quintic.EaseOut).start();
		
        var tweenGroup	= new TWEEN.Tween(group.rotation)
        .to( {
            x: 0, 
            y:0, 
            z:0
        }, time*4)
        .easing( TWEEN.Easing.Quintic.EaseOut).start();
        
        var tweenCam = new TWEEN.Tween(camera.position)
        .to( {
            x: 0, 
            y: 0,
            z:1200
        }, time*4)
        .easing( TWEEN.Easing.Quintic.EaseOut).start();
		
        tweenHead.start();
        tweenSuite.start();
        tweenGroup.start();
        tweenCam.start();

        setTimeout(function () {hidePlanes(obj)},2200);
        camera.lookAt( obj.position );
    }
}
/* planesToInit -----------------------------------------------------------------*/
function planesToInit () {
	
    for (var i= obj.id; i>= 0; i-- ) {
        values = objectsPositions[i].split('_');
        var px = values[0];
        var py = values[1];
        var pz = values[2];
		
        new TWEEN.Tween(planes[objectsPositions.length - 1 - i].position ).to( {
            x: px,
            y: py,
            z: pz
        }, 450+(10*i) )
		
        .easing( TWEEN.Easing.Sinusoidal.EaseInOut).start();
    }
    objectsPositions = [];
}


function computeSize (obj) {
    var rect = ((((camRadius - sphereRadius)*ieWH)/camAngle)*32);
    var ratio = 50;
    vW = projects[projects.id].visuels.width = Math.ceil(rect / ratio) + 1;
    vH = projects[projects.id].visuels.height = Math.ceil((vW * 3)/4) + 1;
    vL = projects[projects.id].visuels.left = (ieWW - vW) / 2;
    vT = projects[projects.id].visuels.top = (ieWH - vH) / 2;
}


/* Reorganize Spirale---------------------------------------------------------------*/		
function reorganizeSpirale(gR, cR) {
    groupRotation = gR;
    camRotation = cR;
	
    var counter = 0;
    var angle = 0;
    var increase = Math.PI * 2 / (projects.count/2);
    for ( var i = 0; i < projects.count; i ++ ) {
        if(planes[i].activeTag &&  planes[i].activeCat && planes[i].activePresta && planes[i].activeClassement){
            var nx = Math.round(420 * Math.cos( angle ));
            var ny = Math.round((counter*10)-50) - 200;
            var nz = Math.round(420 * Math.sin( angle ));
            angle += increase;

            new TWEEN.Tween(planes[i].position ).to( {
                x: nx,
                y: ny,
                z: nz
            }, 300+(10*i) )
            .delay(20*i)
            .easing( TWEEN.Easing.Sinusoidal.EaseInOut).start();


            var h = Math.sqrt(Math.pow(nx,2)+Math.pow(nz,2));

            camx = 0;
            camy = 0;
            camz = 1050;

            camPos.push(camx+':'+camy+':'+camz);
            counter++;
        }
    }
}
/* Reorganize Random---------------------------------------------------------------*/		
function reorganizeRandom(gR, cR) {
    groupRotation = gR;
    camRotation   = cR;
    
    //var counter = 0;
    for ( var i = 0; i < projects.count; i ++ ) {
        if(planes[i].activeTag &&  planes[i].activeCat && planes[i].activePresta && planes[i].activeClassement){
            new TWEEN.Tween(planes[i].position).to( {
                x: Math.random() * 2000 - 1000,
                y: Math.random() * 2000 - 1000,
                z: Math.random() * 2000 - 1000
            }, 300+(5*i) )
            .easing( TWEEN.Easing.Sinusoidal.EaseIn).start();
			
            new TWEEN.Tween(planes[i].rotation).to( {
                x: Math.random() * 360 * ( Math.PI / 180 ),
                y: Math.random() * 360 * ( Math.PI / 180 )
            }, 350+(10*i) )
            .easing( TWEEN.Easing.Quintic.EaseIn).start();
			
            camx = 0;
            camy = 0;
            camz = 1050;
			
			
            camPos.push(camx+':'+camy+':'+camz);
        // counter++;
        }
    }
	
}


/* Reorganize Liste---------------------------------------------------------------*/		
function reorganizeListe(gR, cR) {
    groupRotation = gR;
    camRotation   = cR;
    
    var counter = 0;
    decounter = 0;
    for ( var i = 0; i < projects.count; i ++ ) {
        if(planes[i].activeTag &&  planes[i].activeCat && planes[i].activePresta && planes[i].activeClassement){
            new TWEEN.Tween(planes[i].position).to( {
                x: Math.random() * 10000 - 5000,
                y: Math.random() * 10000 - 5000,
                z: Math.random() * 10000 - 5000
            }, 300+(5*i) )
            .easing( TWEEN.Easing.Sinusoidal.EaseIn).start();
			
            new TWEEN.Tween(planes[i].rotation).to( {
                x: Math.random() * 360 * ( Math.PI / 180 ),
                y: Math.random() * 360 * ( Math.PI / 180 )
            }, 350+(10*i) )
            .easing( TWEEN.Easing.Quintic.EaseIn).start();
			
            camx = 0;
            camy = 0;
            camz = 1050;
            
            camPos.push(camx+':'+camy+':'+camz);
            
            itemsbyLines    = 7;
            linesCount      = projects.count / itemsbyLines;
            var fullW       = ieWW - $('#leftColumn').width() -  $('#getRightColumn').width() - marginL * 3;
            var fullH       = Math.round($('#timelineAgenda').offset().top);
        
            listiW = Math.round(fullW / itemsbyLines);
            listiH = Math.round(fullH / (projects.count /itemsbyLines)) ;
        
            var moduloW = fullW - (itemsbyLines * listiW);
        
            var leftStart = $('#leftColumn').offset().left + $('#leftColumn').width() + marginL * 3 + moduloW;
            
            var lCount = Math.floor((i-decounter)/itemsbyLines);
        
            var iL = leftStart + listiW*(i-decounter-(itemsbyLines*lCount));
            var iT = 0 + lCount * listiH + 6;
            
            $('#listDiv-'+i).delay((i-decounter)*10).animate({
                'top'       : iT,
                'left'      : iL,
                'opacity'   : 1
            },300,'easeOutQuint');
            $('#listDiv-'+i).css({
                'z-index': '140'
            });
            $('#liste2d').css({
                'opacity':'1'
            });
            
            if(!$('#liste2d').hasClass('loaded')){
                //$('#listDiv-'+i).stop();
                $('#listDiv-'+i).delay((i-decounter)*10).animate({
                    'width'     : listiW
                },300,'easeOutExpo', function (){
                    $('#liste2d').addClass('loaded');
                });
            }
            
            counter++;
        } else {
            //$('#listDiv-'+i).stop();
            $('#listDiv-'+i).animate({
                'opacity'       : 0
            },300,'easeOutQuint');
            $('#listDiv-'+i).css({
                'z-index': '1'
            });
            $('#listDiv-'+i).delay((i-decounter)*10).animate({
                'width'     : listiW
            },300,'easeOutExpo', function (){
                if(decounter == projects.count-1 ){
                    $('#liste2d').addClass('loaded');
                }
            });
                       
            decounter ++;
        }
    }
    
    $('canvas').animate({
        'opacity':'0'
    },1500, 'easeOutExpo');
}


addList = function () {
    $('#container').append('<div id="liste2d"></div>');
    for ( var i = 0; i < projects.count; i ++ ) {
        var title = planes[i].title;
        var regPipe = new RegExp('[|]', 'gi');
        title     = title.replace(regPipe," ");
        $('#liste2d').append('<div id="listDiv-'+i+'" data-id="'+i+'" class="listDiv"><div class="title">'+title+'<br /><span>'+projects[i].agency+'</span></div><div class="mini"><img src="upload/projects/miniatures/'+planes[i].miniature+'"/></div><span class="rating" id="rating-'+i+'"></span></div>');
        itemsbyLines = 7;
        linesCount   = projects.count / itemsbyLines;
        var fullW = ieWW - $('#leftColumn').width() -  $('#getRightColumn').width() - marginL * 3;
        var fullH = Math.round($('#timelineAgenda').offset().top);
        
        listiW = Math.round(fullW / itemsbyLines);
        listiH = Math.round(fullH / (projects.count /itemsbyLines)) ;
        
        var moduloW = fullW - (itemsbyLines * listiW);
        var moduloH = fullH - ((projects.count /itemsbyLines)*listiH);
        var allPadding  =  4;
        var paddR = allPadding;
        var paddL = allPadding*2.5;
        var paddT = allPadding*2;
        
        var leftStart = $('#leftColumn').offset().left + $('#leftColumn').width() + marginL * 3 + moduloW;
        
        $('#rating-'+i).css({
            'border':'none'
        });
        
        if(planes[i].laureat){
            $('#rating-'+i).css({
                'background'   :'url(images/obl-laureat.png) no-repeat',
                'position'           :'absolute',
                'width'              :'74px',
                'height'             :'74px',
                'top'                :listiH - 74,
                'z-index'            :'150',
                'display'            :'block',
                'border'             :'none'
            });
        } else if(planes[i].finaliste){
            $('#rating-'+i).css({
                'background'   :'url(images/obl-finaliste.png) no-repeat',
                'position'           :'absolute',
                'width'              :'74px',
                'height'             :'74px',
                'top'                :listiH - 74,
                'z-index'            :'150',
                'display'            :'block',
                'border'             :'none'
            });
        }
        
        if(i < itemsbyLines) {
            var iL = leftStart + listiW*i;
            var iT = 0 + moduloH;
            var pT = paddT - moduloH;
        } else {
            iL = $('#listDiv-'+(i - itemsbyLines)).offset().left;
            iT = $('#listDiv-'+(i - itemsbyLines)).offset().top + listiH;
            pT = paddT;
        }
        
        $('#liste2d').css({
            'position'  :'absolute',
            'left'      : 0,
            'top'       : 0,
            'opacity'   : 0
        })
        
        
        $('#listDiv-'+i).css({
            'position'      :'absolute',
            'top'           : iT,
            'left'          : iL,
            'width'         : 0,
            'height'        : listiH,
            'z-index'       : 100,
            'overflow'      :'hidden',
            'cursor'        :'pointer',
            'border-bottom' :'1px dotted '+siteMainDarkColor,
            'border-right'  :'1px dotted '+siteMainDarkColor
        });
        
        $('#listDiv-'+i+' .title').css({
            'font-size'     :'8px',
            'font-family'   :'GothamMedium',
            'color'         :'white',
            'width'         : listiW-(paddR + paddL),
            'height'        : listiH-paddT,
            'padding-right' : paddR,
            'padding-left'  : paddL,
            'padding-top'   : pT,
            'opacity'       :'1',
            'position'      :'absolute',
            'z-index'       :'101',
            'line-height'   :'12px'
        });
        
        $('#listDiv-'+i+' .title span').css({
            'color'         :siteGreyColor,
            'font-size'     :'8px',
            'font-family'   :'GothamMedium',
            'padding'       :'0',
            'border'        :'none',
            'position'      :'absolute',
            'width'         :'auto',
            'display'       :'block'
        });
        
        $('#listDiv-'+i+' .mini').css({
            'width'             : listiW,
            'height'            : listiH,
            'position'          :'absolute',
            'z-index'           :'102',
            //'background'        :'#'+Math.floor(Math.random()*16777215).toString(16),
            'opacity'           :i*0.005,
            'background'        : 'white'
        });
        
        $('#listDiv-'+i+' .mini img').css({
            'width'         : (listiW + 6),
            'position'      :'absolute',
            'top'           :'-3px',
            'opacity'       :'0',
            'left'          :'-3px'
        });
        
        $('#listDiv-'+i).attr('data-iT', iT);
        $('#listDiv-'+i).attr('data-iL', iL);
        $('#listDiv-'+i+' .mini').attr('data-alpha', i*0.005 )
        
        $('#listDiv-'+i).click(function() {
            // Deselect
            $('#listDiv-'+projects.id+' .mini img').removeClass('selected');
            var alpha = $('#listDiv-'+projects.id+' .mini').attr('data-alpha');
            $('#listDiv-'+projects.id+' .mini img').animate({
                'opacity':'0'
            },200,'easeOutSine');
            $('#listDiv-'+projects.id+' .mini').animate({
                'opacity':alpha
            },500,'easeOutQuint');
            
            
            // Select
            var self = $(this).attr('id');
            var selfImg = $('#'+self+' .mini img');
            var selfImgDiv = $('#'+self+' .mini');
            selfImg.animate({
                'opacity':'1'
            },300,'easeOutSine'); 
            selfImgDiv.animate({
                'opacity':'1'
            },300,'easeOutQuint');
            
            $(this).addClass('selected');
            projects.id = $(this).attr('data-id');
            if(!scrollList){
                loadProjectInterface2d ();
                scrollList = true;
            } else {
                unloadVisuelsInterval = setInterval('unloadZoneVisuels()', 20);
                setTimeout("loadZoneVisuels()", 1500);
                setTimeout("updateProjectsContent ()", 700);
            }
        });
    }
    
    $('.listDiv').hover(function(){
        var idHover = $(this).attr('id');
        var idHoverImg = $('#'+idHover+' .mini img');
        var idHoverImgDiv = $('#'+idHover+' .mini');
        idHoverImgDiv.animate({
            'opacity':'1'
        },300,'easeOutSine'); 
        idHoverImg.animate({
            'opacity':'1'
        },300,'easeOutQuint');
  
    }, function (){
        var idHover         = $(this).attr('id');
        var idHoverImg      = $('#'+idHover+' .mini img');
        var idHoverImgDiv   = $('#'+idHover+' .mini');
        var alpha           = $('#'+idHover+' .mini').attr('data-alpha');
        if(!$(this).hasClass('selected')){
            idHoverImgDiv.animate({
                'opacity':alpha
            },500,'easeOutQuint'); 
            idHoverImg.animate({
                'opacity':'0'
            },400,'easeOutQuint');
        }
    });
}

listToCam = function (){
    var dPi     = 0;
    listVerticalLeft = 0;
    for ( var i = 0; i < projects.count; i ++) {
        var divTop  = 0;
        var lC      = parseInt(linesCount);
        var pC      = parseInt(projects.count-decounter);
        var pI      = parseInt(projects.id);
        var lH      = parseInt(listiH);
        listVerticalLeft = $('#listDiv-0').offset().left + ( listiW * (itemsbyLines-1));
        if(displayedPlanes[i]){
            
            if(pI < Math.floor(lC/2)){
                divTop  = ( lH * dPi ) - (lH  * (pI - pI));
            } else if(pI >= pC - Math.floor(lC/2)) {
                divTop  = ( lH * dPi ) - (lH  * (pI - (lC-(pC - pI))));
            } else {
                divTop  = ( lH * dPi ) - (lH  * (pI - Math.floor(lC/2)));
            }

            $('#listDiv-'+i).delay(dPi*10).animate({
                'left'      : listVerticalLeft,
                'top'       : divTop
            },400,'easeOutQuad');
            
            dPi ++;
        }
    }
    
    
    $('#liste2d').parent().parent().parent().css({
        'z-index':'140'
    });
    $('#projectInterface').css({
        'width': $('#listDiv-0').offset().left
        });
//    console.log('dPi'+dPi+'---'+'displayedPlanes.length'+displayedPlanes.length)
    if(dPi > projects.count / itemsbyLines){
        $(document).bind( 'mousemove', onListMouseMove);
    }
}


listToInit = function () {
    var dPi     = 0;
    scrollList = false;
    for ( var i = 0; i < projects.count; i ++) {
        if(displayedPlanes[i]){
            var iT = $('#listDiv-'+dPi).attr('data-iT');
            var iL = $('#listDiv-'+dPi).attr('data-iL');

            $('#listDiv-'+i).delay(1300+(20*i)).animate({
                'top'       : iT,
                'left'      : iL
            },300,'easeOutExpo');

            if($('#listDiv-'+i).hasClass('selected')){
                $('#listDiv-'+i).removeClass('selected');
                var idHover         = $('#listDiv-'+i).attr('id');
                var idHoverImg      = $('#'+idHover+' .mini img');
                var idHoverImgDiv   = $('#'+idHover+' .mini');
                var alpha           = $('#'+idHover+' .mini').attr('data-alpha');
                idHoverImgDiv.animate({
                    'opacity':alpha
                },500,'easeOutQuint'); 
                idHoverImg.animate({
                    'opacity':'0'
                },400,'easeOutQuint');
            }
            dPi++; 
        }
    }
    
    $('#liste2d').parent().parent().parent().css({
        'z-index':'10'
    });
    $(document).unbind( 'mousemove', onListMouseMove);
}

/* Move mouse ---------------------------------------------------------------*/		
function onListMouseMove(event) {
    var buteeBottom     = parseInt($('#timelineAgenda').css('margin-top'),10)*(-1);
    var itemsDisplayed  = projects.count / itemsbyLines;
    var totalHeight     = (listiH * (projects.count - decounter - itemsDisplayed));
    var heightDisplayed = ieWH-buteeBottom;
    var deltaRatio      = totalHeight / heightDisplayed;
    
    var buteeRight      = listVerticalLeft + listiW;
    var buteeLeft       = listVerticalLeft;
    var dPi             = 0;
    
    mouseY              = ((event.clientY - (heightDisplayed / 2)) * deltaRatio);
    
    if((event.clientY > 0 && event.clientY < heightDisplayed) && (event.clientX > buteeLeft && event.clientX < buteeRight) ){
        for ( var i = 0; i < projects.count; i ++) {
            if(displayedPlanes[i]){
                $('#listDiv-'+i).css({
                    'top': - mouseY + (listiH*dPi) - totalHeight/2
                });
                dPi++;
            }
        }
    }
}

hideList = function () {
    for ( var i = 0; i < projects.count; i ++ ) {        
        $('#listDiv-'+i).delay(20*i).animate({
            'width'     : 0
        },300,'easeOutSine');
    }
    $('#liste2d').delay((projects.count*20)+300).animate({
        'opacity':'0'
    });
    $('#liste2d').removeClass('loaded');
    $('canvas').delay(1500).animate({
        'opacity':'1'
    },500, 'easeOutExpo');
}

/* Parse Tags ---------------------------------------------------------------*/	
function parseTags (tagId) {
    for ( var m = 0; m < projects.count; m ++ ) {
        if(planes[m].tags == tagId && firstClickTags == false){
            if(planes[m].activeTag){
                planes[m].activeTag = false;
                new TWEEN.Tween(planes[m].position).to( {
                    x: Math.random() * 6000 - 3000,
                    y: Math.random() * 6000 - 3000,
                    z: Math.random() * 6000 - 3000
                }, 300+(5*m) )
                .easing( TWEEN.Easing.Sinusoidal.EaseIn).start();
                               
                displayedPlanes[m] = false;
                pausePlanes (m);

            } else if((!planes[m].activeTag && planes[m].activeCat && planes[m].activePresta)){
                
                planes[m].activeTag = true;
                
                displayedPlanes[m] = true;
                remapPlanes(m);
                
            } else if((!planes[m].activeTag && !planes[m].activeCat && !planes[m].activePresta ) ||
                (!planes[m].activeTag && !planes[m].activeCat && planes[m].activePresta)||
                (!planes[m].activeTag && planes[m].activeCat && !planes[m].activePresta)) {
                
                planes[m].activeTag = true;
                new TWEEN.Tween(planes[m].position).to( {
                    x: Math.random() * 4000 - 2000,
                    y: Math.random() * 4000 - 2000,
                    z: Math.random() * 4000 - 2000
                }, 300+(5*m))
                .easing( TWEEN.Easing.Sinusoidal.EaseIn).start();
            
                displayedPlanes[m] = false;
                pausePlanes (m);
            }
        } else if(planes[m].tags != tagId && firstClickTags == true){
            if(planes[m].activeTag){
                planes[m].activeTag = false;
                new TWEEN.Tween(planes[m].position).to( {
                    x: Math.random() * 6000 - 3000,
                    y: Math.random() * 6000 - 3000,
                    z: Math.random() * 6000 - 3000
                }, 300+(5*m) )
                .easing( TWEEN.Easing.Sinusoidal.EaseIn).start();
                displayedPlanes[m] = false;
                pausePlanes (m);

            } else if((!planes[m].activeTag && planes[m].activeCat && planes[m].activePresta)){
                
                planes[m].activeTag = true;
                
                displayedPlanes[m] = true;
                remapPlanes(m);
                
            } else if((!planes[m].activeTag && !planes[m].activeCat && !planes[m].activePresta ) ||
                (!planes[m].activeTag && !planes[m].activeCat && planes[m].activePresta)||
                (!planes[m].activeTag && planes[m].activeCat && !planes[m].activePresta)) {
                
                planes[m].activeTag = true;
                new TWEEN.Tween(planes[m].position).to( {
                    x: Math.random() * 4000 - 2000,
                    y: Math.random() * 4000 - 2000,
                    z: Math.random() * 4000 - 2000
                }, 300+(5*m))
                .easing( TWEEN.Easing.Sinusoidal.EaseIn).start();
            
                displayedPlanes[m] = false;
                pausePlanes (m);
            }
        } 
    }
//    console.log(displayedPlanes);
    getActiveAffichage ();
}

/* Parse Classement ---------------------------------------------------------------*/	
function parseClassement (classementId) {
    for ( var m = 0; m < projects.count; m ++ ) {
        if(classementId == 0){
            if(!planes[m].laureat && !planes[m].finaliste && !planes[m].participant){
                planes[m].activeClassement = false;
                new TWEEN.Tween(planes[m].position).to( {
                    x: Math.random() * 6000 - 3000,
                    y: Math.random() * 6000 - 3000,
                    z: Math.random() * 6000 - 3000
                }, 300+(5*m) )
                .easing( TWEEN.Easing.Sinusoidal.EaseIn).start();
                               
                displayedPlanes[m] = false;
                pausePlanes (m);
            } else {
                planes[m].activeClassement = true;
                if(planes[m].activeTag && planes[m].activeCat && planes[m].activePresta ){
                    displayedPlanes[m] = true;
                    remapPlanes(m);
                } else {
                    displayedPlanes[m] = false;
//                    remapPlanes();  
                    pausePlanes (m);
                }
            }
            
        } else if (classementId == 1){
            if(!planes[m].laureat && !planes[m].finaliste){
                planes[m].activeClassement = false;
                new TWEEN.Tween(planes[m].position).to( {
                    x: Math.random() * 6000 - 3000,
                    y: Math.random() * 6000 - 3000,
                    z: Math.random() * 6000 - 3000
                }, 300+(5*m) )
                .easing( TWEEN.Easing.Sinusoidal.EaseIn).start();
                               
                displayedPlanes[m] = false;
                pausePlanes (m);
            } else {
                planes[m].activeClassement = true;
                if(planes[m].activeTag && planes[m].activeCat && planes[m].activePresta ){
                    displayedPlanes[m] = true;
                    remapPlanes(m);
                } else {
                    displayedPlanes[m] = false;
//                    remapPlanes();  
                    pausePlanes (m);
                }
            }
        } else if (classementId == 2){
            if(!planes[m].laureat){
                planes[m].activeClassement = false;
                new TWEEN.Tween(planes[m].position).to( {
                    x: Math.random() * 6000 - 3000,
                    y: Math.random() * 6000 - 3000,
                    z: Math.random() * 6000 - 3000
                }, 300+(5*m) )
                .easing( TWEEN.Easing.Sinusoidal.EaseIn).start();
                               
                displayedPlanes[m] = false;
                pausePlanes (m);
            } else {
                planes[m].activeClassement = true;
                if(planes[m].activeTag && planes[m].activeCat && planes[m].activePresta ){
                    displayedPlanes[m] = true;
                    remapPlanes(m);
                } else {
                    displayedPlanes[m] = false;
//                    remapPlanes();  
                    pausePlanes (m);
                }
            }
        } 
    }
    getActiveAffichage ();
}
/* Parse Cats ---------------------------------------------------------------*/	
function parseCategories (catId) {    
    for ( var m = 0; m < projects.count; m ++ ) {
        if(planes[m].category == catId ){
            if(planes[m].activeCat){
                planes[m].activeCat = false;
                new TWEEN.Tween(planes[m].position).to( {
                    x: Math.random() * 4000 - 2000,
                    y: Math.random() * 4000 - 2000,
                    z: Math.random() * 4000 - 2000
                }, 300+(5*m) )
                .easing( TWEEN.Easing.Sinusoidal.EaseIn).start();
                 
                displayedPlanes[m] = false;
                pausePlanes (m);
            } else if((!planes[m].activeCat && planes[m].activeTag && planes[m].activePresta)  ) {
                planes[m].activeCat = true;
                
                displayedPlanes[m] = true;
                remapPlanes(m);
                
            } else if((!planes[m].activeCat && !planes[m].activeTag && !planes[m].activePresta)||
                (!planes[m].activeCat && !planes[m].activeTag && planes[m].activePresta) || 
                (!planes[m].activeCat && planes[m].activeTag && !planes[m].activePresta)) {
                planes[m].activeCat = true;
                new TWEEN.Tween(planes[m].position).to( {
                    x: Math.random() * 4000 - 2000,
                    y: Math.random() * 4000 - 2000,
                    z: Math.random() * 4000 - 2000
                }, 300+(5*m))
                .easing( TWEEN.Easing.Sinusoidal.EaseIn).start();
                displayedPlanes[m] = false;
                pausePlanes (m);
            }
        }
    }
    getActiveAffichage ();
}

/* Parse Prestataires ---------------------------------------------------------------*/	
function parsePrestataires (prestaId) {
    for ( var m = 0; m < projects.count; m ++ ) {
        if(planes[m].presta == prestaId){
            if(planes[m].activePresta){
                planes[m].activePresta = false;
                new TWEEN.Tween(planes[m].position).to( {
                    x: Math.random() * 4000 - 2000,
                    y: Math.random() * 4000 - 2000,
                    z: Math.random() * 4000 - 2000
                }, 300+(5*m) )
                .easing( TWEEN.Easing.Sinusoidal.EaseIn).start();
                displayedPlanes[m] = false;
                pausePlanes (m);
                
            } else if ((!planes[m].activePresta && planes[m].activeTag && planes[m].activeCat)){
                planes[m].activePresta = true;
                
                displayedPlanes[m] = true;
                remapPlanes(m);
                
            } else if((!planes[m].activePresta && !planes[m].activeCat && !planes[m].activeTag) ||
                (!planes[m].activePresta && !planes[m].activeTag && planes[m].activeCat)||
                (!planes[m].activePresta && planes[m].activeTag && !planes[m].activeCat)) {
                planes[m].activePresta = true;
                new TWEEN.Tween(planes[m].position).to( {
                    x: Math.random() * 4000 - 2000,
                    y: Math.random() * 4000 - 2000,
                    z: Math.random() * 4000 - 2000
                }, 300+(5*m))
                .easing( TWEEN.Easing.Sinusoidal.EaseIn).start();

                displayedPlanes[m] = false;
                pausePlanes (m);
            }
        }
    }
    getActiveAffichage ();
}

/* Pause Planes ---------------------------------------------------------------*/	
function pausePlanes (i) {
        if ($.browser.safari || $.browser.mozilla){
            planes[i].materials[ 0 ] = inactiveMaterial;
            planes[i].materials[ 1 ] = inactiveMaterial;
        } else {
            planes[i].materials[ 0 ] = inactiveMaterial;
            planes[i].materials[ 1 ].opacity = 0;
            planes[i].materials[ 2 ].opacity = 0;            
        }        
}

/* Pause Planes ---------------------------------------------------------------*/	
function pauseAllPlanes () {
    for ( var i = 0; i < projects.count; i ++ ) {
        if ($.browser.safari || $.browser.mozilla){
            planes[i].materials[ 0 ] = inactiveMaterial;
            planes[i].materials[ 1 ].opacity = 0;
        } else {
            planes[i].materials[ 0 ] = inactiveMaterial;
            planes[i].materials[ 1 ].opacity = 0;
            planes[i].materials[ 2 ].opacity = 0;            
        }       
    }
}

/* Resume Planes ---------------------------------------------------------------*/	
function resumePlanes () {
    for ( var i = 0; i < projects.count; i ++ ) {           
        planes[i].materials[ 0 ] = activeMaterial;
        planes[i].materials[ 1 ].opacity = 0.8;
        if(!$.browser.safari && !$.browser.mozilla){
            if(projects[i].finaliste != '0') {
                planes[i].materials[ 2 ].opacity = 0.8;
            }
        }
    }
    new TWEEN.Tween(camera.position)
    .to( {
        x: 0, 
        y: 0,
        z:1000
    }, 500)
    .easing( TWEEN.Easing.Quintic.EaseOut).start();
}

/* Resum Planes ---------------------------------------------------------------*/	
function remapPlanes (i) {
        planes[i].materials[ 0 ] = activeMaterial;
        planes[i].materials[ 1 ].opacity = 1;
        if(!$.browser.safari && !$.browser.mozilla){
            if(projects[i].finaliste != '0'){
                planes[i].materials[ 2 ].opacity = 0.8;
            }
        }
}

/* Hide Planes ---------------------------------------------------------------*/	
function hidePlanes (obj) {
    for (var i= obj.id; i>= 0; i-- ) {
        planes[i].materials[ 0 ] = hiddenMaterial;
    }
}

/* Pause Rotations ---------------------------------------------------------------*/
function pauseRotations () {
    groupRotation = false;
    camRotation   = false;
}

/* resume Rotations ---------------------------------------------------------------*/
function resumeRotations () {
    groupRotation = true;
    camRotation   = true;
}


function STR_wordwrap(string ,longueur ,texte_separation) {
    var j = 0;
    for(var i = 0; i < string.length; i++){
        if(j == longueur){
            if(string[i] == " "){
                string = string.replaceAt(i,texte_separation);
            }else{
                for(var k = i; k > 0; k--){
                    if(string[k] == " "){
                        string = string.replaceAt(k,texte_separation);
                        break;
                    }
                }
            }
            j = 0;
        }
        j++;
    }
    return string;
}

String.prototype.replaceAt=function(index, chara) {

    return this.substr(0, index) + chara + this.substr(index+chara.length);
}
