pStore={};
var canvas,ctx,cw,ch,doAnim=true,stop=false;
// general variables
var PI = Math.PI;
var PI2 = PI * 2;
var change=5;
// cylinder related variables
var cx,cy,width,height,fillY,w2, h2, h4, h8, h16, ytop, cpYtop, ybottom, cpYbottom, degreeAngle, rAngle, dx, dy, r, a, xx, yy, limitValues, juiceBtnClickFlag=false,btnClicked,currentJuiceColor="red";
var glassDivId=0,percentage,label,temp,juiceQuantity,correctAnswer,correctAnswerCnt=0,cnt1=5,orderToServed, labelMultiplier=1,correctFilled,finalJuiceServed=0,totalCost=0,actualCost=0,orderButtonClick=false;
var glassFullImg=["glassFull.png","orangeFull.png","fullGreen.png"];
var gameId=null;

pStore.startJuiceGame=function(id)
{
	gameId=id;
	setTimeout(function()
	{
		setData();
		init("start");
 	},200);
}

function initVariables(){
  cw = canvas.width;
  ch = canvas.height;
  doAnim=true;
  stop=false;
  PI = Math.PI;
  PI2 = PI * 2;

// cylinder related  variables
  cx = cw / 2;
  cy = ch / 2;
  width = 160;
  height = 136;
  fillY = cy + height / 2+3;
  w2 = width / 2;
  h2 = height / 2;
  h4 = height / 4;
  h8 = height / 8;
  h16 = height / 16;
  ytop = -h2 + h8;
  cpYtop = -h2 - h16;
  ybottom = h2 - h8;
  cpYbottom = h2 + h16;
  degreeAngle, rAngle, dx, dy, r, a, xx, yy,limitValues,correctFilled=0,finalJuiceServed=0,orderToServed="",cnt1=0;
}

function init(divId){
    if(divId=='start')
      {  juiceBtnClickFlag=false;
         currentJuiceColor="red";
        $('.juiceBtn').css("pointer-events","none");
      }
    else
         juiceBtnClickFlag=true;
    
     $(".centerCanvas").draggable({
            cursor:"move",
            revert:true,
            drag:emptyCanvas,
            drag:stopAnimation
        });
        $(".glassClass").droppable({
            drop:handleDrop
        });
    drawingCanvas();
}

function drawingCanvas(){
        canvas = document.getElementById("canvas0");
        $(canvas).css({"width":"17vw","height":"41.5vh"});
        ctx = canvas.getContext("2d");
        initVariables();
        //start the cylinder upright (at 0 degree angle)
        setContainerAngle(0);  
        draw(); 
        
    if(juiceBtnClickFlag==true)
        startAnimation();
}

function setData(){
    document.body.style.backgroundImage="url(images/BG.png)";
    var btnData=0;
    orderButtonClick=false;
    for(var i=0;i<3;i++)
    {
        $("#jbtnDiv"+i).data("juiceBtn",i);
        $("#glassDiv"+i).data("glassPresentData",i);
        btnData=i;
        $("#jbtn"+i).attr("onclick","init("+btnData+")");
    }
    $("#responseDiv").hide();
    $("#juiceGlassDiv,#orderTxtDiv,#giveOrderDiv,#proceedDiv,#payment").hide();
    $("#orderImg").attr("onclick","createOrder()");
    $("#giveOrder").attr("onclick","orderChecking()");
    $('.juiceBtn').css("pointer-events","none");
    generateJuiceOrder();
    juiceBtnClickFlag=false;
}

function generateJuiceOrder(){
    var randomNumber,randomNumber1,randomNumber2,maxRange=19,minRange=4;
    
   
    randomNumber2=Math.floor(Math.random()*(2-0+1)+0);
    currentJuice=juiceData[randomNumber2];
    randomNumber=Math.floor(Math.random()*(2-0+1)+0);
    
    
     if(correctAnswerCnt<3)
    {
        randomNumber1=Math.floor(Math.random()*(4-1+1)+1);
        percentage=randomNumber1*25;
        label=[25,50,75,100];        
        juiceQuantity=100;
        labelMultiplier=1;
    }
    else if(correctAnswerCnt>=3 && correctAnswerCnt<6){
        randomNumber1=Math.floor(Math.random()*(4-1+1)+1);
        percentage=randomNumber1*25;
        label=[50,100,150,200];
        juiceQuantity=200;
        labelMultiplier=2;
    }
    else
    {
        randomNumber1=Math.floor(Math.random()*(maxRange-minRange+1)+minRange);
        percentage=randomNumber1*5;
        if(randomNumber==0)
        {  label=[25,50,75,100];        
            juiceQuantity=100;
            labelMultiplier=1;
        }
        else
        {   label=[50,100,150,200];
            juiceQuantity=200;
            labelMultiplier=2;
        }
    }

    $("#juiceGlassImg").prop("src","images/"+currentJuice.juiceImg);
    orderToServed=percentage+"% of "+juiceQuantity+" ml";
    actualCost=percentage*0.1*labelMultiplier;
    $("#orderTxtSpan").text(orderToServed);
    correctAnswer=Math.ceil(juiceQuantity*(percentage/100));
    console.log(correctAnswer);
}

function orderChecking(){
    var answerCorrectWrong=0,juiceMinRange=juiceMaxRange=0;
    totalCost=Math.round(parseFloat(finalJuiceServed*0.1).toFixed(2));
    $("#juiceGamePage").hide();
    $("#responseDiv").show();
    $("#orderedJuice").text("Ordered: "+percentage+"% of "+juiceQuantity+" ml of "+currentJuice.juiceName+" juice");
    $("#orderedJuiceQuantity").text("Juice Quantity:"+percentage+"% of "+juiceQuantity+" ml="+correctAnswer+" ml");
    $("#servedJuice").text("Served: "+finalJuiceServed+" ml of "+currentJuice.juiceName+" juice and Total Cost:"+totalCost);
    $("#servedJuiceDivCanvas").append($("#canvas0"));
     $(".centerCanvas").draggable('disable');
    $("#proceedImg").attr("onclick","paymentPage("+totalCost+")");

    juiceMinRange=finalJuiceServed-5;
    juiceMaxRange=finalJuiceServed+5;

    if(correctAnswer>=juiceMinRange && correctAnswer<=juiceMaxRange && currentJuice.juiceColor==currentJuiceColor)
    {
		$("#correctWrongImg").prop("src","images/correct.png");
		$("#proceedDiv").show();
		$(canvas).css({"width":"26vw","height":"55.5vh"});
		correctAnswerCnt++;
    }
    else
    {   $("#correctWrongImg").prop("src","images/wrong.png");
        setTimeout(function(){
          pStore.reset();
        },3500);
    }
}


pStore.reset=function()
{
    glassDivId=0;
    $("#juiceGamePage").show();
	$("#juiceGlassDiv,#orderTxtDiv,#giveOrderDiv").hide();
     $(".centerCanvas").draggable('enable');
     $("#leftDiv,#rightDiv").show();
     //$("#payment").hide();
     $("#centerCanvas0").append($("#canvas0"));
     setData();
     init("start");
     initVariables();
      $('.juiceBtn').css("pointer-events","none");
}
function paymentPage(actualCost)
{
	Shop.checkJuiceShopFlag=true;
    $("#juiceGamePage,#responseDiv").hide();
    $("#payment").show();   
    EstimationPayment.setPayment(actualCost,gameId);
}

function createOrder(){
    orderButtonClick=true;
    $("#juiceGlassDiv,#orderTxtDiv,#giveOrderDiv").show();
     $('.juiceBtn').css("pointer-events","none");
    $("#jbtn"+glassDivId).css("pointer-events","auto");
    $('#giveOrder').css("pointer-events","none");
}

function handleDrop(event,ui)
{
    var src,srcDiv,dst,dstDiv;
    initVariables();
    doAnim=false;
    emptyCanvas();
    src=ui.draggable;   
    srcDiv=$(src);
    dstDiv=$(this);
    glassDivId=$(dstDiv).data("glassPresentData");
    $(dstDiv).append(srcDiv);
    $(src).css({"top":"0%","left":"0%","width":"17vw","height":"41.5vh"});   
    $('.juiceBtn').css("pointer-events","none");
    if(orderButtonClick)
        $("#jbtn"+glassDivId).css("pointer-events","auto");
    currentJuiceColor=juiceData[glassDivId].juiceColor;
    console.log(currentJuice);
}

function startAnimation()
{   
    doAnim=true;
    stop=false;
    $("#jbtn0").attr("onclick","stopAnimation()");   
    $("#jbtn"+glassDivId).attr("onclick","stopAnimation()");
    requestAnimationFrame(animateFill);
     $('#giveOrder').css("pointer-events","none");  
}

function stopAnimation()
{   
    doAnim=false;
    stop=true;
    $('#giveOrder').css("pointer-events","auto");
    console.log(" Answer "+correctAnswer+" "+Math.ceil(correctFilled*labelMultiplier));
    finalJuiceServed=Math.ceil(correctFilled*labelMultiplier);
    finalJuiceServed-=1;
    $("#jbtn0").attr("onclick","startAnimation()");
    $("#jbtn"+glassDivId).attr("onclick","startAnimation()");
    requestAnimationFrame(animateFill);
}

// animate filling the cylinder
function animateFill()
{
    if (fillY-1 > cy - height / 2 + h8-7) 
    {
        if(doAnim){
         requestAnimationFrame(animateFill);
        }
        draw();  
        if(stop==false && doAnim)
        {
            console.log("start"+fillY);
            drawPouring(cx, 0, fillY);  
            fillY -= 0.5;
            cnt1+=0.92;
            correctFilled=cnt1*0.5000;
            console.log("currentLoc"+(cnt1*0.5000));
        }
    } 
    else
    {  
        //alert("Glass Full");
         $("#modalImg").prop("src","images/"+glassFullImg[glassDivId]);
        $("#responseBoxDiv").show();
        setTimeout(function(){
            $("#responseBoxDiv").hide();
            initVariables();
            emptyCanvas();
            stopAnimation();
            setData();
        },2500);   
    }
}

function emptyCanvas(){
    ctx.fillStyle = "#d7dff5";
    ctx.fillRect(0, 0, cw+10, ch+20);
    ctx.save();
    defineFillOutline(cx, cy, width, height, degreeAngle);
    drawContainer(cx, cy, width, height, degreeAngle);
    setlabels(); 
}
// draw the scene (background, cylinder, liquid in cylinder)
function draw() 
{
    ctx.fillStyle = "#d7dff5";
    ctx.fillRect(0, 0, cw, ch);
    ctx.save();
    defineFillOutline(cx, cy, width, height, degreeAngle);
   // setlabels();
   if(degreeAngle >= -90) 
    {
        ctx.clip();
        ctx.fillStyle = currentJuiceColor;
        ctx.fillRect(0, Math.max(fillY+2, yy), cw, ch);

    }
    ctx.restore();
   // setlabels(); 
    drawContainer(cx, cy, width, height, degreeAngle);
     setlabels(); 
    
    /**/
}
function setlabels(){    
    var labelXPos=width+16,labelYPos=140.8,cnt=0;
    ctx.font = "bold 1.8vw arial";
    ctx.fillStyle = "#000000";
    for(var i=0;i<label.length;i++)
    {
        if(labelYPos<=height+h2)
        {   
            for(var j=0;j<4;j++)
            {           
                labelYPos-=5.44;
                //cnt+=0.8;    
                //ctx.fillText('  _ ', labelXPos+20, labelYPos);         
            }
             ctx.font = "1.8vw arial";
            ctx.fillText('     _', labelXPos, labelYPos);   
            ctx.font = "bold 1.8vw arial";
            ctx.fillText(label[i]+"  ", labelXPos-7, labelYPos+6);         
            labelYPos-=5.3;
        }
    }   

    /*ctx.shadowBlur = 20;
    ctx.shadowColor = "black";
    ctx.fillStyle = "gray";
    ctx.fillRect(width-80,25, 15, 120);*/

    drawLine("round");
}

function drawLine(cap)
{
     //var canvas1 = document.getElementById("canvas0");
    var ctx1= canvas.getContext("2d");
    ctx1.lineCap = cap;
    ctx1.shadowBlur = 5;
    ctx1.shadowColor = "lightgray";
    ctx1.fillStyle = "darkgray";
    ctx1.fillRect(width-87,22, 16, 121);
}

// draw the liquid being poured in a vertical stream
function drawPouring(xx, yy, yyy) 
{
    ctx.save();
    ctx.beginPath();
    ctx.moveTo(xx, yy);
    ctx.lineTo(xx, yyy);
    ctx.lineWidth = 15;
    ctx.shadowColor = currentJuiceColor;
    ctx.shadowBlur = 0;
    if(doAnim)
    {
         ctx.strokeStyle = currentJuiceColor;
         ctx.stroke();
    }
    else
    {   
        if(stop==true)
        {  
            ctx.strokeStyle = "transparent";
            ctx.stroke();
        }
    }
    
   // this is the top-outer lip of the cylinder
    /*ctx.shadowBlur=0;
    ctx.translate(cx,cy);
    ctx.beginPath();
    ctx.moveTo(-w2,-h2+h8);        
    ctx.bezierCurveTo( -w2+14,-h4-16, w2+16,-h4-16, w2,-h2+h8-5);// this is the top-outer lip of the cylinder
    ctx.strokeStyle="gray";
    ctx.lineWidth=2;
    ctx.stroke();*/
    ctx.restore();
}

// define the clipping region (which is the cylinder)
function defineFillOutline(x, y, w, h, degrees) {
    ctx.save();
    ctx.translate(x, y);       //x , y axis of cylinder
    ctx.beginPath();
    //ctx.moveTo(-w2, ytop);      //cylinder cap
   // ctx.bezierCurveTo(-w2, cpYtop, w2, cpYtop, w2, ytop);   //curve of cylinder cap
    ctx.moveTo(-w2, ytop-2); 
    ctx.bezierCurveTo(-w2, cpYtop+20, w2, cpYtop+18, w2, ytop-3);   //curve of cylinder cap
    ctx.lineTo(w2, h2 - h16+9);                //width & height defined for cylinder's right side
    ctx.bezierCurveTo(w2, cpYbottom-5, -w2, cpYbottom+2, -w2, ybottom+14);
    //ctx.lineTo(w2+h16-10, h2 - h8+10); 
    //ctx.bezierCurveTo(w2, cpYbottom+5, -w2, cpYbottom+4, -w2, ybottom+8);  //curve of cylinder bottom
    
    ctx.closePath();
    ctx.restore();
  
}

// draw the cylinder at the specified angle
function drawContainer(cx, cy, width, height, degreeAngle)
{ 
    defineFillOutline(cx, cy, width, height, degreeAngle);
    ctx.save();
    ctx.translate(cx, cy);
    ctx.strokeStyle = "gray";
    ctx.lineWidth = 5;
    ctx.stroke();
    ctx.restore();
}

// change the angle of the cylinder
function setContainerAngle(degrees) {
    degreeAngle = degrees;
    rAngle = degreeAngle * Math.PI / 180;
    dx = width / 2;
    dy = height / 2 - height / 8;
    r = Math.sqrt(dx * dx + dy * dy);   //radius used to fill the container
    a = Math.atan2(dy, dx) + Math.PI + rAngle;      //container get fill upto a level.
    xx = cx + r * Math.cos(a);
    yy = cy + r * Math.sin(a);
}
