var intervalID;

function showDebugInfo(info){
	if(debug)document.getElementById("debug").innerHTML=info;
}

function showMouseCoords(info){
    $("#mouseCoords").html(info);
}

function initialise(){
    showAppTitle();
    if(!eventsInitialised){
        initialiseEvents();
    }
    initialiseCanvas();
    initialisePage();
    toggleSolutionButtons(true);
}

function initialiseEvents(){
    $(document).on("keydown",function(e){
        if(e.shiftKey){
            shiftPressed=true;
        }
        else if(e.ctrlKey){
            ctrlPressed=true;
        }
        else if(e.altKey){
            altPressed=true;
        }
    });
    
    $(document).on("keyup",function(e){
        shiftPressed=false;
        ctrlPressed=false;
        altPressed=false;
    });

    $("#slideFontSize").bind("change keyup touchstart touchend",function(event,ui) {
        graphFontSize=$(this).val();
        setGraphFont();
        currentTime-=timeStep;
        simulateMovement();
    });
    
    $("#btnNextSnapshot").bind("click touchstart touchend",function(event,ui){
        simulateMovement();
    });
    
    $("#btnPreviousSnapshot").bind("click touchstart touchend",function(event,ui){
        currentTime-=2*timeStep;
        simulateMovement();
    });
    
    $("#showGrid").bind("change keyup touchstart touchend",function(event,ui){
        drawScene();
    });
    
    $("#showSolidGrid").bind("change keyup touchstart touchend",function(event,ui){
        drawScene();
    });
    
    $("#boxGraph").bind("change keyup touchstart touchend",function(event,ui){
        drawScene();
    });
    
    $("#showGraphGrid").bind("change keyup touchstart touchend",function(event,ui){
        drawScene();
    });

    $("#showSpaceTimeInfo").bind("change keyup touchstart touchend",function(event,ui){
        drawScene();
    });
    
    $("#showGraphPoints").bind("change keyup touchstart touchend",function(event,ui){
        drawScene();
    });
    
    $("#showGraphCurve").bind("change keyup touchstart touchend",function(event,ui){
        drawScene();
    });
    
    $("#showPointsCoords").bind("change keyup touchstart touchend",function(event,ui){
        drawScene();
    });
    
    $("#testBodyInitialPos").bind("change keyup touchstart touchend",function(event,ui){
        currentTime-=timeStep;
        simulateMovement();
        //currentPosition=$("#testBodyInitialPos").val();
        //drawScene();
    });
    
    $("#testBodyInitialVelocity").bind("change keyup touchstart touchend",function(event,ui){
        currentTime-=timeStep;
        simulateMovement();
        //drawScene();
    });

    $("#testBodyAcceleration").bind("change keyup touchstart touchend",function(event,ui){
        currentTime-=timeStep;
        simulateMovement();
        //drawScene();
    });
    
    $("#showCaptions").bind("change keyup touchstart touchend",function(event,ui){
        if($("#showCaptions:checked").val()=="show"){
            buttonCaptionsVisible=true;
        }
        else{
            buttonCaptionsVisible=false;
        }
        showButtonCaptions();
    });
    
    $("#slideSpeed").bind("change keyup touchstart touchend",function(event,ui){
        var maxSimSpeed=Number($(this).attr("max"))+1;
        simSpeed=maxSimSpeed-$(this).val();
        if($("#btnSimulateSolution").text()=="Παύση"){
            stopSimulation();
            startSimulation();
        }
    });
    
    $("#btnStudy").on("click touchstart touchend",function(){
        exerciseMode=false;
        toggleSolutionButtons(true);
        var newVal=parseInt(Math.random()*(parseFloat($("#testBodyInitialPos").attr("max"))-parseFloat($("#testBodyInitialPos").attr("min")))+parseFloat($("#testBodyInitialPos").attr("min")));
        $("#testBodyInitialPos").val(newVal).slider("refresh");

        newVal=parseInt(Math.random()*(parseFloat($("#testBodyInitialVelocity").attr("max"))-parseFloat($("#testBodyInitialVelocity").attr("min")))+parseFloat($("#testBodyInitialVelocity").attr("min")));
        $("#testBodyInitialVelocity").val(newVal).slider("refresh");
        
        newVal=parseInt(Math.random()*(parseFloat($("#testBodyAcceleration").attr("max"))-parseFloat($("#testBodyAcceleration").attr("min")))+parseFloat($("#testBodyAcceleration").attr("min")));
        $("#testBodyAcceleration").val(newVal).slider("refresh");
        
        $("#btnOptions").prop("disabled",false);
        $("#showOptions").attr("href","#popupSpeed");
        initialisePage();        
        resetSimulation();
        simulateMovement();
    });
    
    $("#btnFinalise").on("click touchstart touchend",function(){
        $("#btnSimulateSolution").prop("disabled",true);
        currentTime=tFinal-timeStep;
        simulateMovement();
    });

    $("#btnReset").on("click touchstart touchend",function(){
        exerciseMode=false;
        toggleSolutionButtons(true);
        $("#btnOptions").prop("disabled",false);
        $("#showOptions").attr("href","#popupSpeed");
        resetSimulation();
        simulateMovement();
    });

    $("#btnNewProblem").on("click touchstart touchend",function(){
        $("#btnOptions").prop("disabled",true);
        $("#showOptions").attr("href","");
        toggleSolutionButtons(false);
        stopSimulation();
        exerciseMode=true;
        setNewProblem();
    });
    
    $("#btnSimulateSolution").on("click touchstart touchend",function(){
        if($("#btnSimulateSolution").text()=="Προσομοίωση"){
            startSimulation();
        }
        else{
            stopSimulation();
        }
    });
    
    $("#requestConfirmations").bind("change keyup touchstart touchend",function(event,ui){
        if($("#requestConfirmations:checked").val()=="reqConfirm"){
            requestConfirmationState=requestConfirmation;
        }
        else{
            requestConfirmationState=dontRequestConfirmation;
        }
    });
    
    $("#zoomFactor").bind("change keyup", function(eent,ui){
        var newValue=$("#zoomFactor").val();
        if(newValue=="" || parseFloat(newValue)>10 || parseFloat(newValue)<0.1){
            $("#zoomFactor").css("background-color","red");
            $("#zoomFactor").css("color","white");
        }
        else{
            $("#zoomFactor").css("background-color","white");
            $("#zoomFactor").css("color","black");
            setZoomFactor();
        }
    });    

    if (document.addEventListener){
        //IE9,Chrome,Safari,Opera
        document.getElementById("canvas2D").addEventListener("mousewheel",handleMouseWheel,false);
        //Firefox
        document.getElementById("canvas2D").addEventListener("DOMMouseScroll",handleMouseWheel,false);
    }
    //IE6/7/8
    else{
        document.getElementById("canvas2D").attachEvent("onmousewheel",handleMouseWheel);
    }

    eventsInitialised=true;
}

function handleMouseWheel(e){
    // cross-browser wheel delta
    var e=window.event || e; // old IE support
    var delta=(e.wheelDelta || -e.detail);
    var newZoomFactor=parseInt($("#zoomFactor").val())+Math.sign(delta);
    if(newZoomFactor>=parseInt($("#zoomFactor").attr("min")) && newZoomFactor<=parseInt($("#zoomFactor").attr("max"))){
        $("#zoomFactor").val(newZoomFactor);
    }
    e.preventDefault();
    drawScene();
}

function startSimulation(){
    animationRunning=true;
    intervalID=setInterval(simulateMovement,simSpeed);
    $("#btnSimulateSolution").text("Παύση");
    $("#btnFinalise").prop("disabled",true);
}

function stopSimulation(){
    animationRunning=false;
    clearInterval(intervalID);
    $("#btnSimulateSolution").text("Προσομοίωση");
    $("#btnFinalise").prop("disabled",false);
    drawScene();
}

function clearBodies(){
    for(var i=bodies.length-1;i>-1;i--){
        bodies[i]=null;
        bodies.splice(i,1);
    }
}

function clearLinkedVectors(){
    for(var i=linkedVecs.length-1;i>-1;i--){
        linkedVecs[i]=null;
        linkedVecs.splice(i,1);
    }
}

function clearFreeVectors(){
    for(var i=vecs.length-1;i>-1;i--){
        vecs[i]=null;
        vecs.splice(i,1);
    }
}

function initialiseScene(){
    updateGrid();
    basicWidth=4;
    changeGridStep(2);
}

function drawGrid(){
    var i,j;
    var jStart=0;
    if($("#showGrid:checked").val()=="showGrd"){
        var iStart=0;
        //Πλέγμα με γραμμές
        if($("#showSolidGrid:checked").val()=="showSolidGrd"){
            cntx.fillStyle="rgb(180,180,180)";
            cntx.strokeStyle="rgb(180,180,180)";
            i=iStart;
            while(i<=canvasWidth){
                cntx.beginPath();
                cntx.moveTo(i,0);
                cntx.lineTo(i,canvasHeight);
                cntx.stroke();
                i+=gridStep;
            }
            j=jStart;
            while(j<=canvasHeight){
                cntx.beginPath();
                cntx.moveTo(0,j);
                cntx.lineTo(canvasWidth,j);
                cntx.stroke();
                j+=gridStep;
            }
        }
        //Πλέγμα με κουκίδες
        cntx.fillStyle="rgb(0,0,180)";
        cntx.strokeStyle="rgb(0,0,180)";
        i=iStart;
        while(i<=canvas.width){
            j=jStart;
            while(j<=canvas.height){
                cntx.beginPath();
                cntx.arc(i,j,1,0,2*Math.PI);
                cntx.fill();
                j+=gridStep;
            }
            i+=gridStep;
        }
    }
}

function changeGridStep(newVal){
    gridStep=4*Math.pow(2,newVal);
    var gridSteps=canvasHeight/gridStep;
    floorInitY=parseInt(gridSteps/2)*gridStep;
    if(!initialising){
        drawScene();
    }
}

function nextPage(){
    if(currentPage<maxPage){
        currentPage++;
    }
	$("#btnOptions").prop("disabled",false);
	$("#showOptions").attr("href","#popupSpeed");
    initialisePage();
}

function previousPage(){
    if(currentPage>minPage){
        currentPage--;
    }
    $("#btnOptions").prop("disabled",false);
    $("#showOptions").attr("href","#popupSpeed");
    initialisePage();
}

function handlePreviousNextButtons(){
    if(currentTime<=tInit){
    	$("#btnPreviousSnapshot").prop("disabled",true);
    	$("#btnNextSnapshot").prop("disabled",false);
    }
    else if(currentTime>=tFinal){
    	$("#btnPreviousSnapshot").prop("disabled",false);
    	$("#btnNextSnapshot").prop("disabled",true);
    }
    else{
    	$("#btnPreviousSnapshot").prop("disabled",false);
    	$("#btnNextSnapshot").prop("disabled",false);
    }
}

function updateGrid(){
    changeGridStep( parseInt($("#gridStep").val()) );
    gridStep=5*parseInt($("#gridStep").val());
    if(currentPage==twoStarSystem){
        if(star2 && $("#snapToGrid").is(":checked")){
            var oldX=star2.left;
            var steps=parseInt(oldX/gridStep);
            if(oldX % gridStep>gridStep/2){
                steps++;
            }
            star2.move(steps*gridStep,star2.top);
        }
    }
    if(!initialising) drawScene();
}

/**
 * Υπολογισμός γωνίας στο διάστημα [0,2π] (σε μοίρες)
 */
function wholeAngle(dx,dy){
    var angle;
    if(dx>0){
        angle=Math.atan(dy/dx);     
    }
    else if(dx==0){
        if(dy>0){
            angle=Math.PI/2;
        }
        else if(dy==0){
            angle=0;
        }
        else{
            angle=3*Math.PI/2;
        }
    }
    else{
        angle=Math.atan(dy/dx)+Math.PI;
    }
    return angle*180/Math.PI;   
 }

function showButtonCaptions(){
    if(buttonCaptionsVisible){
        $("#btnPreviousSnapshot").html("Προηγούμενο");
        $("#btnNextSnapshot").html("Επόμενο");
        $("#btnReset").html("Επαναφορά");
        $("#btnStudy").html("Μελέτη");
        $("#btnFinalise").html("Πλήρες");
        $("#btnNewProblem").html("Άσκηση");
        $("#btnSimulateSolution").html("Προσομοίωση");

        $(".btnMenu").css({"width":"175px"});
        $(".buttonData").width(160);
    }
    else{
        $("#btnPreviousSnapshot").html("");
        $("#btnNextSnapshot").html("");
        $("#btnReset").html("");
        $("#btnStudy").html("");
        $("#btnFinalise").html("");
        $("#btnNewProblem").html("");
        $("#btnSimulateSolution").html("");
        
        $(".btnMenu").css({"width":"30px"});
        $(".buttonData").width(40);
    }
}

function toggleSolutionButtons(disabledState){
    $("#btnShowHint").prop("disabled",disabledState);
    $("#btnSimulateSolution").prop("disabled",!disabledState);
}