var stats;

var camera, scene, renderer;
var group;

var targetRotation = 0;
var targetRotationOnMouseDown = 0;

var mouseX = 0;
var mouseXOnMouseDown = 0;

var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;

var id_anim = 0;

var container = document.getElementById('noodle');

var tailleCarre = 500; //dans le cas ou container a une taille fixe et carre
if (screen.height > 500 && screen.width > 500) {
    tailleCarre = 500;
//    document.getElementById("info").innerHTML += " PAS COOL "+ container.offsetHeight + " " + container.offsetWidth; 
}
else if (screen.height > 300 && screen.width > 300) {
    tailleCarre = 300;
//    document.getElementById("info").innerHTML += " OK " + container.offsetHeight + " " + container.offsetWidth; 
}
else
    tailleCarre = 200;

var turnIsSet; //par defaut : possible ou non de tourner la figure manuellement

$("head").append('<script type="text/javascript" src="./js/ext/build/three.js"></script>');
$("head").append('<script type="text/javascript" src="./js/ext/renderers/Projector.js"></script>');
$("head").append('<script type="text/javascript" src="./js/ext/renderers/Detector.js"></script>');

/*
 * dots : tableau de tableau (pour chaque point : x, y, z)
 * renderer : webGL, SVG ou Canvas
 * forme : bubble ou line
 * sphereOn : afficher les speres rouge et bleue ou non
 * rotation : est ce que on peut tourner manuellement
 * axes : fleches de repere
 * bck : couleur de fond
 */
function init(dots, choix_renderer, forme, sphereOn, palette, rotation, axes, bck) {

    if (forme === "tube" || forme === "line" || forme === "superTube" || forme === "metalTube") {
        $("head").append('<script type="text/javascript" src="./js/draw/noodle.js"></script>');
        $("head").append('<script type="text/javascript" src="./js/ext/curves/NURBSCurve.js"></script>');
        $("head").append('<script type="text/javascript" src="./js/ext/curves/NURBSUtils.js"></script>');
    }
    if (forme === "bubble" || forme === "superTube") {
        $("head").append('<script type="text/javascript" src="./js/draw/skyBox.js"></script>');
    }

    $("head").append('<script type="text/javascript" src="./js/draw/' + forme + '.js"></script>');
//    $.getScript(forme+".js");

//    include('js/draw/'+forme+'.js');
    turnIsSet = rotation;

    if (rotation) {
        startTurn();
    }

    var params = dots;
    var NB_POINTS = 12;

//    camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 1000);
    camera = new THREE.PerspectiveCamera(50, 1, 1, 1000);
//    camera.position.set(0, 200, 500); //3e param = plus il est petit, plus la camera proche de la figure
    camera.position.set(0, 100, 500);

    scene = new THREE.Scene();

    group = new THREE.Group();
//    group.position.y = 200;

    scene.add(group);

//arrow helper
    if (axes) {
        createArrow();
    }

    var couleurs = palette;

    if (forme.slice(0, 8) === "pastille") {
        forme = "pastille";
    }

    if (!Detector.webgl && choix_renderer === "web") {
        // alert("Your computer does not support webGL, sorry !");
		// var txt = $("#div_txt").text();
		$("#div_txt").text("Your computer does not support webGL, sorry !");
        choix_renderer = "canvas";
    }

    //Choix du renderer
    switch (choix_renderer) {
        case 'web':
            $("head").append('<script type="text/javascript" src="./js/ext/renderers/WebGLRenderer.js"></script>');
            renderer = new THREE.WebGLRenderer({antialias: true, alpha: true});
            break;
        case 'svg':
            $("head").append('<script type="text/javascript" src="./js/ext/renderers/SVGRenderer.js"></script>');
            renderer = new THREE.SVGRenderer({antialias: true, alpha: true});
            break;
        case 'canvas':
        default :
            $("head").append('<script type="text/javascript" src="./js/ext/renderers/CanvasRenderer.js"></script>');
            renderer = new THREE.CanvasRenderer({antialias: true, alpha: true});
            break;
    }

    //appelle de la fonction pour dessiner, voir fichier draw.js
//    window[forme](dots, couleurs);
    draw(dots, couleurs, 12, 2);

    //DEBUT spheres
    if (sphereOn) {
        var geometry = new THREE.SphereGeometry(8, 8, 8);
        var geometry2 = new THREE.SphereGeometry(8, 8, 8);
        var material = new THREE.MeshBasicMaterial({color: 0x7e53935});
        var materialSphere = new THREE.MeshBasicMaterial({color: 0x42A5F5});

        var sphere = new THREE.Mesh(geometry, material);
        var sphere2 = new THREE.Mesh(geometry2, materialSphere);
        sphere.position.set(0, 100 - group.position.y, 0); //boule rouge
        sphere2.position.set(0, 100 - group.position.y, 180); //boule bleue

        group.add(sphere, sphere2);
    }
    //FIN spheres

    //DEBUT lumiere
    var directionalLight = new THREE.DirectionalLight(0xffffff, 0.3);
    directionalLight.position.set(0, 0, 1);
    scene.add(directionalLight);
    //FIN lumiere

    //couleur fond
    if (bck) {
        renderer.setClearColor(bck);
    }

    renderer.setPixelRatio(window.devicePixelRatio);

    renderer.setSize(tailleCarre, tailleCarre);

    container.appendChild(renderer.domElement);

//    container.addEventListener('mousedown', onDocumentMouseDown, false);
//    container.addEventListener('touchstart', onDocumentTouchStart, false);
//    container.addEventListener('touchmove', onDocumentTouchMove, false);

    window.addEventListener('resize', onWindowResize, false);


}



function onWindowResize() {

//    windowHalfX = window.innerWidth / 2;
//    windowHalfY = window.innerHeight / 2;
//
//    camera.aspect = window.innerWidth / window.innerHeight;
//    camera.updateProjectionMatrix();
//
//    renderer.setSize(window.innerWidth, window.innerHeight);

    renderer.setSize(tailleCarre, tailleCarre);

    render();

}

//

function onDocumentMouseDown(event) {

    if (id_anim == 0) {
        animate();
    }

    event.preventDefault();

    document.addEventListener('mousemove', onDocumentMouseMove, false);
    document.addEventListener('mouseup', onDocumentMouseUp, false);
    document.addEventListener('mouseout', onDocumentMouseOut, false);

    mouseXOnMouseDown = event.clientX - windowHalfX;
    targetRotationOnMouseDown = targetRotation;

}

function onDocumentMouseMove(event) {

    mouseX = event.clientX - windowHalfX;

    targetRotation = targetRotationOnMouseDown + (mouseX - mouseXOnMouseDown) * 0.02;

}

function onDocumentMouseUp(event) {

    document.removeEventListener('mousemove', onDocumentMouseMove, false);
    document.removeEventListener('mouseup', onDocumentMouseUp, false);
    document.removeEventListener('mouseout', onDocumentMouseOut, false);

}

function onDocumentMouseOut(event) {

    document.removeEventListener('mousemove', onDocumentMouseMove, false);
    document.removeEventListener('mouseup', onDocumentMouseUp, false);
    document.removeEventListener('mouseout', onDocumentMouseOut, false);

}

function onDocumentTouchStart(event) {

    if (id_anim == 0) {
        animate();
    }

    if (event.touches.length == 1) {

        event.preventDefault();

        mouseXOnMouseDown = event.touches[ 0 ].pageX - windowHalfX;
        targetRotationOnMouseDown = targetRotation;

    }

}

function onDocumentTouchMove(event) {

    if (event.touches.length == 1) {

        event.preventDefault();

        mouseX = event.touches[ 0 ].pageX - windowHalfX;
        targetRotation = targetRotationOnMouseDown + (mouseX - mouseXOnMouseDown) * 0.05;

    }

}

function animate() {

    id_anim = requestAnimationFrame(animate);

    render();
    // stats.update();

}

function render() {

    group.rotation.y += (targetRotation - group.rotation.y) * 0.05;
    renderer.render(scene, camera);

}

function turn(degre) {

    var radians = Math.PI * degre / 180;

    if (id_anim != 0) {
        cancelAnimationFrame(id_anim);
        id_anim = 0;
    }

    group.rotation.y = radians;

    renderer.render(scene, camera);

}

function showAngle() {
    alert("Angle de group : " + group.rotation.y * 180 / Math.PI);
}

function setTurn() {
    if (turnIsSet) {
        stopTurn();
    }
    else {
        startTurn();
    }
    turnIsSet = !turnIsSet;
}

function startTurn() {
    container.addEventListener('mousedown', onDocumentMouseDown, false);
    container.addEventListener('touchstart', onDocumentTouchStart, false);
    container.addEventListener('touchmove', onDocumentTouchMove, false);
}

function stopTurn() {
    container.removeEventListener('mousedown', onDocumentMouseDown, false);
    container.removeEventListener('touchstart', onDocumentTouchStart, false);
    container.removeEventListener('touchmove', onDocumentTouchMove, false);
}

//arrow helper pour indiquer le sens de la figure
function createArrow() {
    var dir = new THREE.Vector3(0, 1, 0);
    var origin = new THREE.Vector3(0, -100, 0);
    var length = 400;
    var hex = 0xFF0000;
    var headLenght = 30;
    var headWidth = 20;

    var arrowHelper = new THREE.ArrowHelper(dir, origin, length, hex, headLenght, headWidth);
    scene.add(arrowHelper);
}