var pStore={};
var Utils={};
Utils.Path="";
var canvas,ctx,cw,ch,doAnim=true,stop=false;
// general variables
var PI = Math.PI;
var PI2 = PI * 2;
// 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,overflowTimeout;

$(document).ready(function()
{ 
    $("#gamePage,#responseBoxDiv,#responseDiv").hide();
    //document.body.style.backgroundColor="#ae4a84"//#c674a9";
   document.body.style.backgroundImage="url(images/scene1background.png)";
    $("#coverPage").addClass("fadeInRight1");
    document.getElementById('startPage').style.backgroundImage="url(images/closeupofjuiceshop.png)";
    $("#customerStandingImg").prop("src","images/customer1standing.png");
   setTimeout(function(){    
        setData();
        EstimationPayment.setNoteForReturn();
       init("start");    
   },4000);

    //EstimationPayment.setPaymentData();
},300);

// Init varibles (Canvas)
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 =   205;
  height =   135;
  console.log(width+"**"+height);
  fillY = cy + height / 2+1;
  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,cnt1=0;
}

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

// Draw Canvas
function drawingCanvas(){
        canvas = document.getElementById("canvas0");
        $(canvas).css({"width":"7vw","height":"25vh"});
        ctx = canvas.getContext("2d");
        initVariables();
        //start the cylinder upright (at 0 degree angle)
        setContainerAngle(0);  
        draw(); 
        
    if(juiceBtnClickFlag==true)
        startAnimation();
}
// Set Images and Text
function setData(){
    $("#coverPage").hide();
    $("#gamePage").show();
    document.body.style.backgroundImage="url(images/backgroundofshopforfillingscenesetc.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+")");
    }
    
    $("#jbtn0").prop("src","images/red-button.png");
    $("#jbtn1").prop("src","images/orange-button.png");
    $("#jbtn2").prop("src","images/green-button.png");
    $("#jbtnimg0").prop("src","images/watermelon.png");
    $("#jbtnimg1").prop("src","images/orange.png");
    $("#jbtnimg2").prop("src","images/cucumber.png");

    $("#pipe0,#pipe1,#pipe2").prop("src","images/tap1.png");
    //$("#pipe1").prop("src","images/tap1.png");
    //$("#pipe2").prop("src","images/tap1.png");
    //$("#orderImg").prop("src","images/OrderHere.png");
    $("#orderImg").text("Order");
    document.getElementById('rightDiv').style.backgroundImage="url(images/orderboard.png)";
    document.getElementById('leftDiv').style.backgroundImage="url(images/juicerframe.png)";
    $("#checkOrder").prop("src","images/tickbutton.png");
    $("#ordercustomerImg").prop("src","images/customer1lookingright.png");
    $("#ownerImg").prop("src","images/assitantlookingup.png");
    $("#responseDiv").hide();
    $("#juiceGlassDiv,#orderTxtDiv,#proceedDiv,#payment").hide();
    $("#checkOrderDiv").css('visibility','hidden');
    //$("#orderImg").attr("onclick","createOrder()");
   $("#checkOrder").attr("onclick","orderChecking()");
    $("#modalMsg").text('Glass Overflow');

    setTimeout(function(){
        createOrder();
    },50);
    generateJuiceOrder();
    juiceBtnClickFlag=false;
}
//Generate Juice Order According to level (Depend on Correct Count)
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";
    orderToServed=percentage+" ml";
   /* if(currentJuice.juiceName=="Cucumber")
        actualCost=percentage*0.1*labelMultiplier*2;   
    else 
        actualCost=percentage*0.1*labelMultiplier;*/

    //actualCost=Math.round(parseFloat(finalJuiceServed*0.1).toFixed(2));
    $("#orderJuiceSpan").text(currentJuice.juiceName+" Juice");
    $("#orderTxtSpan").text(orderToServed);
    correctAnswer=Math.ceil(juiceQuantity*(percentage/100));
    console.log(correctAnswer);
}
// After Correct Answer 
function showRateCardPage()
{
    $("#leftDiv,#rightDiv,#bottomDiv").hide();
    $("#responseDiv").show();
    document.body.style.backgroundImage="url(images/juicecentrecashcounter.png)";
    document.getElementById('customerScreen3').src=Utils.Path+"images/customer1lookingleft.png";
    document.getElementById('rateBoardDiv').style.backgroundImage="url("+Utils.Path+"images/ratedisplayboard.png"+")";
    document.getElementById('rateBoardDiv').style.height="60vh";
    createRateCard();
}
// Generate Rate Card Screen
function createRateCard()
{
    var row,column;
    document.getElementById('rateScreen3').innerHTML="Rate";
    document.getElementById('orderScreen3').innerHTML="Order";
    document.getElementById('ingredientScreen3').innerHTML=currentJuice.juiceName+" Juice";
    document.getElementById('qtyScreen3').innerHTML=orderToServed;
    actualCost=((Math.ceil(correctFilled*labelMultiplier))/100)*currentJuice.price;
    actualCost=Math.round(parseFloat(actualCost).toFixed(2));
    document.getElementById('moneyToPay').innerHTML="Rs. "+actualCost//totalCost;
    for(var i=0;i<3;i++)
    {
    row=document.createElement('tr');
    row.setAttribute("id","row"+(i+1));
    row.setAttribute("class","ingredientsRows fontClass text-center ");
    for(var j=1;j<=2;j++)
    {
        column=document.createElement('td');
        column.setAttribute("id","column"+(i+1)+j);
        column.setAttribute("class","fontClass text-center");
        row.appendChild(column);
        if(j==1)
            column.innerHTML=juiceData[i].juiceName;
        else
         column.innerHTML="Rs. "+juiceData[i].price;
    }
    ratesIngredient.appendChild(row);
    document.getElementById('check').src=Utils.Path+"images/tickbutton.png";
    //document.getElementById('reset').src=Utils.Path+"images/resetbutton.png";
    }
}
// If Wrong Answer then Reset
function reset()
{
    glassDivId=0;
     $(".centerCanvas").draggable('enable');
     $("#leftDiv,#rightDiv,#bottomDiv").show();
     //$("#payment").hide();
     $("#centerCanvas0").append($("#canvas0"));
     document.getElementById('ratesIngredient').innerHTML='';
     setData();
     init("start");
     initVariables();
      $('.juiceBtn').css("pointer-events","none");
}


function paymentPage()
{
    $("#responseDiv,#proceedDiv").hide();
    $("#payment").show();   
    EstimationPayment.setPayment(actualCost);
}

//  On Click of Orders
function createOrder(){
    orderButtonClick=true;
    $("#juiceGlassDiv,#orderTxtDiv").show();
    $("#checkOrderDiv").css('visibility','visible');
    $('.juiceBtn').css("pointer-events","none");
    $("#jbtn"+glassDivId).css("pointer-events","auto");
    $('#checkOrder').css("pointer-events","none");
}

function handleDrop(event,ui)
{
	/*clearTimeout(overflowTimeout);
	overflowTimeout=null;*/
    var src,srcDiv,dstDiv;
    initVariables();
    doAnim=false;
    emptyCanvas();
    src=ui.draggable;   
    srcDiv=$(src);
    dstDiv=$(this);
    glassDivId=$(dstDiv).data("glassPresentData");
    if(glassDivId==0)
         $("#glassDiv0").css("left","0");
    $(dstDiv).append(srcDiv);
    $(srcDiv).css({"top":"0%","left":"0%","width":"7vw","height":"25vh"});  
    //$(canvas).css({"width":"10vw","height":"30vh"});
     
    $('.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);
     $("#ordercustomerImg").prop("src","images/customer1lookingup.png");
     $('#checkOrder').css("pointer-events","none");  
}

function stopAnimation()
{   
    doAnim=false;
    stop=true;
    $('#checkOrder').css("pointer-events","auto");
    console.log(" Answer "+correctAnswer+" "+Math.ceil(correctFilled*labelMultiplier));
    finalJuiceServed=Math.floor(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.94;
            correctFilled=cnt1*0.5000;
           // console.log("currentLoc"+(cnt1*0.5000));
        }
    } 
  else
    {  
        $("#ordercustomerImg").prop("src","images/"+juiceData[glassDivId].juiceOverflow);
         $('#checkOrder').css("pointer-events","none");
         $(".centerCanvas").draggable('disable');
         //document.getElementById('div1').setAttribute('draggable', false);
        overflowTimeout=setTimeout(function(){
            initVariables();
            emptyCanvas();
            stopAnimation();
            setData();
             $(".centerCanvas").draggable('enable');
        },2500);   
    }
}

// Check Order Details after Serving 
function orderChecking(){
    var answerCorrectWrong=0,juiceMinRange=juiceMaxRange=0;
    juiceMinRange=finalJuiceServed-5;
    juiceMaxRange=finalJuiceServed+5;

    if(correctAnswer>=juiceMinRange && correctAnswer<=juiceMaxRange && currentJuice.juiceColor==currentJuiceColor)
    {
        $("#correctWrongImg").prop("src","images/correct.png");
        $("#ordercustomerImg").prop("src","images/"+currentJuice.customerHappy);
        $('#checkOrder').css("pointer-events","none");
        $("#proceedDiv").show();
        correctAnswerCnt++;
         setTimeout(function(){
                document.getElementById('gamePage').style.display='none';
                showRateCardPage();
        },2000);
 
    }
    else
    {   $("#correctWrongImg").prop("src","images/wrong.png");
        $("#ordercustomerImg").prop("src","images/"+currentJuice.customerSad);
         $('#checkOrder').css("pointer-events","none");
        setTimeout(function(){
                document.getElementById('gamePage').style.display='none';
           reset();
        },2500);
    }

}

// Clear Canvas
function emptyCanvas(){
    ctx.fillStyle = "#d3d3d3";
    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 ="#d3d3d3"; // "#d3d3d3";
    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(10, Math.max(fillY+2, yy), cw, ch);

    }
    ctx.restore();
   // setlabels(); 
    drawContainer(cx, cy, width, height, degreeAngle);
    setlabels();   
    /**/
}
// Set Labels On Glass (Numbers)
function setlabels(){    
    var labelXPos=width,labelYPos=height+4,cnt=0;
    ctx.font = "bold 210% 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 = "200%";
            ctx.fillText('    _', labelXPos-5, labelYPos);   
            ctx.font = "210%";
            ctx.fillText(label[i]+"  ", labelXPos-25, labelYPos+6);         
            labelYPos-=5.3;
        }
    }   
   drawLine("round");
}

// Unit Lines On Glass
function drawLine(cap)
{
     //var canvas1 = document.getElementById("canvas0");
    var ctx1= canvas.getContext("2d");
    ctx1.lineCap = cap;
    ctx1.shadowBlur = 5;
    ctx1.shadowColor = "lightgray";
    ctx1.fillStyle = "white";
    ctx1.fillRect(width-140,23, 20, 111);
}

// draw the liquid being poured in a vertical stream
function drawPouring(xx, yy, yyy) 
{
    ctx.save();
    ctx.beginPath();
    ctx.moveTo(xx+10, yy);
    ctx.lineTo(xx+10, 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.shadowBlur = 0;
            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-15, cy-10);
    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);
}
