

// ≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣
var zIndex = 1
//var host = 'https://www.icalendar37.net/v/external_resources/'
var host = 'img/'

let selectedPiece = false
//┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅
function createRight(i){
	//return {draw:" l -10,50 l 10,50 ",invers:" l  -10,-50 l 10,-50 "}	
    var path =[
        {draw:"q -4,20 -5,43 l-5,0 a11,11 1,1,0 0,14 l5,0 q1,20 5,43",
         invers:"q -4,-20  -5,-43 l-5,0 a11,11 1,1,1 0,-14 l5,0 q 1-20 5,-43"},
        {draw:"q -4,20 -5,43 l5,0 a11,11 1,1,1 0,14 l-5,0 q1,20 5,43",
         invers:"q -4,-20 -5,-43 l 5,0 a11,11 1,1,0 0,-14 l-5,0 q 1-20 5,-43"},
         {draw:"q 4,20 5,43 l-5,0 a11,11 1,1,0 0,14 l5,0 q -1,20 -5,43",
         invers:"q 4,-20  5,-43 l-5,0 a11,11 1,1,1 0,-14 l5,0 q -1-20 -5,-43"},
        {draw:"q 4,20 5,43 l5,0 a11,11 1,1,1 0,14 l-5,0	q -1,20 -5,43",
         invers:"q 4,-20  5,-43 l5,0 a11,11 1,1,0 0,-14 l-5,0 q -1-20 -5,-43"}, 
    ]
    
    return path[Math.floor(Math.random()*path.length)]
    
}
function createBottom(i){
	//return {draw:" l -50,10 l -50,-10 ",invers:" l  50,10 l 50,-10 "}
    var path =[
        {draw:"q -20,-4 -43,-5 l0,-5 a11,11 1,1,0 -14,0 l0,5 q-20,1 -43,5",
         invers:"q 20,-4 43,-5 l0,-5 a11,11 1,1,1 14,0 l0,5 q20,1 43,5 "},
        {draw:"q -20,-4 -43,-5 l0,5 a11,11 1,1,1 -14,0 l0,-5 q-20,1 -43,5",
         invers:"q 20,-4 43,-5 l0,5 a11,11 1,1,0 14,0 l0,-5 q20,1 43,5 "},
       {draw:"q -20,4 -43,5 l0,-5 a11,11 1,1,0 -14,0 l0,5 q-20,-1 -43,-5",
         invers:"q 20,4 43,5 l0,-5 a11,11 1,1,1 14,0 l0,5 q20,-1 43,-5 "},
        {draw:"q -20,4 -43,5 l0,5 a11,11 1,1,1 -14,0 l0,-5 q-20,-1 -43,-5",
         invers:"q 20,4 43,5 l0,5 a11,11 1,1,0 14,0 l0,-5 q20,-1 43,-5 "}, 
    ]
    
    return path[Math.floor(Math.random()*path.length)]
}
function inverseRight(i){
    return {draw:director[i-1].b.invers}
}
function inverseTop(i){    
    return {draw:director[i-numCols].c.invers}
}

function pieceData(row,col,index){
	var object ={}
	switch (true) {
     case (col == 0 && row == 0) :
       object={
			type:"supEsquerra",
			a:{draw:" l 100,0 "},
			b:createRight(index),
			c:createBottom(index),
			d:{draw:" l 0,-100"},
       }	
       break;
     case (row == 0 && col == numCols-1) :
       object={
			type:"supDreta",
			a:{draw:" l 100,0 "},
			b:{draw:" l 0,100 "},
			c:createBottom(index),
			d:inverseRight(index),	 
		}		
       break;
     case (row == numRows-1 && col == 0) :
       object={
			type:"infEsquerra",
			a:inverseTop(index),
			b:createRight(index),
			c:{draw:" l -100,0 "},
			d:{draw:" l 0,-100 "},
		}		
       break;			
     case (row == numRows-1 && col == numCols-1) :
       object={
			type:"infDreta",
			a:inverseTop(index),
			b:{draw:" l 0,100 "},
			c:{draw:" l -100,0 "},
			d:inverseRight(index),		
		}	
       break;			
     case (row == 0 ) :
       object={
			type:"superior",
           a:{draw:" l 100,0 "},
           b:createRight(index),
           c:createBottom(index),
           d:inverseRight(index),
		}
       break;
     case (col == 0 ) :
       object={
			type:"esquerra",
			a:inverseTop(index),
			b:createRight(index),
			c:createBottom(index),
			d:{draw:" l 0,-100 "},
		}		
       break;
     case (col == numCols-1 ) :
       object={
			type:"dreta",
			a:inverseTop(index),
			b:{draw:" l 0,100 "},
			c:createBottom(index),
			d:inverseRight(index),
		}		
       break;			
     case (row == numRows-1 ) :
       object={
			type:"inferior",
			a:inverseTop(index),
			b:createRight(index),
			c:{draw:" l -100,0 "},
			d:inverseRight(index),
		}	
       break;			
      default:
		object={
			type:"central",
			a:inverseTop(index),
			b:createRight(index),
			c:createBottom(index),
			d:inverseRight(index),
		}	
    }
	object.col=col
	object.row=row
	object.index=index
    object.path=function(){return this.a.draw+this.b.draw+this.c.draw+this.d.draw+"z"}
	return object
	
}


function createSvg(pathPeza,x,y,index){
    xmlns = "http://www.w3.org/2000/svg"
    var svg=document.createElementNS(xmlns,"svg")
    var idPattern="row"+x+"col"+y
    var pattern='<defs><pattern id="'+ idPattern +'" patternUnits="userSpaceOnUse" width="600" height="400"><image xlink:href="'+host+model.urlImg+'" x="'+(x*-100+40)+'" y="'+(y*-100+40)+'" width="'+(numCols*100)+'" height="'+(numRows*100)+'" /></pattern></defs>'
    svg.innerHTML= pattern
    svg.setAttribute("width",180)
    svg.setAttribute("height",180)
    var path= document.createElementNS(xmlns,"path")
    path.setAttribute("d","M40,40 "+pathPeza)
    path.setAttribute("fill","url(#"+idPattern+")")
    path.style.fill="url(#"+idPattern+")"
    svg.appendChild(path)
    var move = document.createElement("DIV")
    move.appendChild(svg)
    move.className="move"
    move.path=path
    move.onmousemove=getPos
    move.onmouseout=stopTracking
    //move.setAttribute("classangle","g0")
    move.angle=0
    move.occupy= false
    move.position=function(){
		return {
			left:this.offsetLeft+50,top:this.offsetTop +50
		}
	}
    move.onmouseup=dropPiece
    move.index=index    
	
    var position = document.createElement("DIV")
    position.className="position"
    position.index=index
    position.occupied =false
    document.querySelector("#container").appendChild(position)
    position.appendChild(move)
    move.style.zIndex = zIndex++
    move.zIndexPrevi=move.style.zIndex
    
   
}
var i, element
var models=[
	/*
    {
    numRows : 4,
    numCols : 6,
    urlImg :"puzzle-01.jpg"
    },
    {
    numRows : 2,
    numCols : 2,
    urlImg :"puzzle-01.jpg"
    }, 
    {
    numRows : 3,
    numCols : 3,
    urlImg :"puzzle-01.jpg"
    }, 
     {
    numRows : 4,
    numCols : 4,
    urlImg :"puzzle-01.jpg"
    },  


     {
    numRows : 5,
    numCols : 5,
    urlImg :"puzzle-01.jpg"
    },
	*/
        {
    numRows : 5,
    numCols : 8,
    urlImg :"puzzle-01-800.jpg"
    },
	{
    numRows : 6,
    numCols : 9,
    urlImg :"puzzle-01-900.jpg"
    },
	{
    numRows : 8,
    numCols : 12,
    urlImg :"puzzle-01-1200.jpg"
    },
    
]


function createPuzzle(model){
    pecaAlSeuLloc=0
    document.getElementById("container").innerHTML=""
    director=[]
    index=0
    selectedPiece= false
    numRows=model.numRows
    numCols=model.numCols
    document.getElementById("container").style.width=numCols*100 +"px"
    document.getElementById("container").style.backgroundPositionY=100*model.numRows+"px"
    for (row=0; row<numRows; row++){
        for (col=0; col<numCols; col++){
            var dades=pieceData(row,col,index)
            director.push(dades)		
            createSvg(dades.path(),col,row,index)
           index++
        }
    }
}
function selectModel(i){
    model=models[i]
    createPuzzle(model)
    document.querySelector("#start").style.height=""
}


//┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅
$('.pieces-40').click(e =>{ selectModel(0) })
$('.pieces-54').click(e =>{ selectModel(1) })
$('.pieces-96').click(e =>{ selectModel(2) })
//┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅
document.addEventListener("DOMContentLoaded", function() { 
    model = models[0]
    createPuzzle(model)
	
	// see model event
    document.getElementById("seeModel").onmouseover=function(){
        document.getElementById("container").style.backgroundImage="url("+host+model.urlImg+")"
        document.getElementById("container").style.backgroundPositionY=0;
    }
    document.getElementById("seeModel").onmouseout=function(){   
            document.getElementById("container").style.backgroundPositionY=100*model.numRows+"px" 
    }
	
	// start event
    document.getElementById("start").onclick = start
	
	// end ok
    document.getElementById("end-ok").onclick = endOK
	
	// fullscreen event
    var botoFullScreen = document.getElementById("fullscreen")
    botoFullScreen.fullScreen=false
    botoFullScreen.onclick=function(){
        if (this.fullScreen){
            if (document.msExitFullscreen) { 
                document.msExitFullscreen()
            }else{
                document.exitFullscreen();
            }	
            this.className="fullscreen"
        }else{			
            if (document.body.msRequestFullscreen) { 
                document.body.msRequestFullscreen()
            }else{
                document.body.requestFullscreen()
            }
            this.className="fullscreenOff"
        }
        this.fullScreen=!this.fullScreen
    }
 })

function scrollBodyTop(){
	return document.body.scrollTop ||
			document.documentElement.scrollTop
}
function final(){
    document.querySelectorAll(".move").forEach(function(e,i){
        e.path.style.strokeWidth="1px"
        e.path.style.stroke="black"
    })
	
	$("#tap").hide()
	$("#seeModel").hide()
	
    document.getElementById("time").innerHTML=timeEnd
    document.getElementById("time").style.opacity=1
	
	
	$("#message2").fadeIn();
	$("#puzzle .note").css('opacity', 0);

}
function showModels(){
    document.getElementById("models").style.height="2000px"
    document.getElementById("time").innerHTML=""
    document.querySelector("#modelsButton").style.height=0
    document.querySelector("#tap").style.height=""
    document.querySelector("#tap").style.opacity=1
}
function start(){
	$("#puzzle .note").css('opacity', 1);
	$("#seeModel").fadeIn();
	$("#message1").fadeOut();
	$('.pieces-40').hide();
	$('.pieces-54').hide();
	$('.pieces-96').hide();
	$('#tap').hide();
	
    document.querySelectorAll(".move").forEach(function(e,i){ 
       
        e.parentNode.removeChild(e)
        document.body.appendChild(e)
		//document.querySelector("#pieces").appendChild(e)
		
        e.style.top = 360 + 80 + Math.random()*400 +"px"   
        e.style.left=Math.random()*(window.innerWidth -100) +"px" 
        setTimeout(function(){
                var angle=Math.floor(Math.random()*4)
                e.setAttribute("classangle","g"+angle)
                e.style.transform="rotate("+angle*90+"deg)"
                e.angle=angle
        },10)
  
    })
    timeInitial=(new Date).getTime()
    document.getElementById("time").innerHTML=""
}
function endOK(){
	$("#message2").fadeOut();
}

function rotation(){
    
    this.angle++
   
    this.style.transform="rotate("+this.angle*90+"deg)"
    
    this.setAttribute("classangle","g"+this.angle%4)
    if ((this.occupy===this.index) && this.angle%4 ==0)fixPiece(this)

    
}
function takePiece(e){

    selectedPiece=this
    offset = [
        this.offsetLeft - e.clientX,
        this.offsetTop - e.clientY
    ]

    if(typeof this.occupy == "number") {
        document.querySelectorAll(".position")[this.occupy].occupied= false
        this.occupy=false
    }
   
}

function fixPiece(p){
    document.body.removeChild(p)
   document.querySelectorAll(".position")[p.index].appendChild(p)
    p.onmousedown=""
    p.onmouseover=""
    p.onmouseout=""
    p.onmousemove=""
    p.ondblclick=""
    p.onmouseup=""
    p.style.cursor="default"
    p.style.position="static"
   setTimeout(function(){p.removeAttribute("classangle")},300)
   
    
    p.style.transition=".1s"
    p.path.style.strokeWidth=".5px"
    setTimeout(function(){p.style.transform="scale(1.05)"},50)
    setTimeout(function(){p.style.transform="scale(1)"},150)
    setTimeout(function(){p.path.style.strokeWidth="2px"; p.style.zIndex= 0},250)
    pecaAlSeuLloc++
    if (pecaAlSeuLloc == numRows * numCols ){
        timeEnd = Math.floor(((new Date).getTime()-timeInitial)/1000)
        var hores = Math.floor(timeEnd/3600)
        var minuts =  Math.floor((timeEnd - hores * 3600)/60)
        minuts= minuts<10 ? "0"+minuts : minuts
        var segons = timeEnd - hores * 3600 - minuts *60 
        segons= segons<10 ? "0"+segons : segons
        timeEnd ="Χρόνος: " + 
            +((hores>0) ? hores +"h " :"")+            
            + minuts +"' " + segons +"''"
        document.getElementById("time").style.opacity=0  
        setTimeout(final,1500)
    }
}
function placePiece(p){
  
    p.style.zIndex = zIndex++
    p.zIndexPrevi=p.style.zIndex
        document.querySelectorAll(".position").forEach (function(e,i){
        	if ((p.position().left>e.offsetLeft &&
				 p.position().left<e.offsetLeft+100) &&(p.position().top>e.offsetTop+96 && p.position().top<e.offsetTop+196) &&
				 !e.occupied ){
            p.style.left = e.offsetLeft+"px"
            p.style.top = (e.offsetTop+96)+"px"
            e.occupied= true
            p.occupy = i
            if (e.index == p.index &&
				p.getAttribute("classangle")=="g0") fixPiece(p)
           
        }
    })
    
}
function dropPiece(){
   
    placePiece(selectedPiece)
    
    selectedPiece=false
    
}

//┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅
document.addEventListener('mousemove', function(event) {
    event.preventDefault();
    if (selectedPiece) {
        mousePosition = {

            x : event.clientX,
            y : event.clientY

        };
        selectedPiece.style.left = (mousePosition.x + offset[0]) + 'px';
        selectedPiece.style.top  = (mousePosition.y + offset[1]) + 'px';
                

    }
}, true);


function getPos(e){

	var x=e.clientX-this.offsetLeft
	var y=e.clientY- this.offsetTop + scrollBodyTop()

    if ((x>0 && x<100) && (y>0 && y<100)){
		this.onmousedown=takePiece
        this.ondblclick=rotation
        this.style.cursor="move"
		this.style.zIndex=zIndex+1
     
    } else {
        this.onmousedown=""
        this.ondblclick=""
        this.style.cursor="default"
        this.style.zIndex=this.zIndexPrevi
    }
    	
  
}
function stopTracking(){
    
   

}


$(document).ready(function(){
	if ( $(window).width() <= 800 ) {
		$('<div id="warning">')
			.html('Διαθέσιμο μόνο σε συσκευές με οθόνη πλάτους μεγαλύτερου των 800 pixels.')
			.appendTo('main')
	}
})
