/*ardoraPoster, created by ARDORA www.webardora.net

Copyright (C) <2011>  <José Manuel Bouzán M.>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
var canvasAux; var pizarra_canvas; var pizarra_context; var xMin; var xMax; var yMin; var yMax; var xStart=0; var yStart=0; var is_touch_device;
function initCanvas(){
		pizarra_canvas = document.getElementById("canvas01");
		var valueZ=giveZindex()+1;
		var cssObj = {"z-index" : valueZ};
		xMin=parseInt($(pizarra_canvas).css("width").replace("px",""));
		xMax=0;
		yMin=parseInt($(pizarra_canvas).css("height").replace("px",""));
		yMax=0;
		$(pizarra_canvas).css(cssObj);
		pizarra_context = pizarra_canvas.getContext("2d");
		pizarra_context.strokeStyle = drawCanvasColor;
		pizarra_context.lineWidth = $( "#amount" ).val();
		is_touch_device = 'ontouchstart' in document.documentElement;
		if (is_touch_device) {
			pizarra_canvas.addEventListener('touchstart', empezarPintar, false);
            pizarra_canvas.addEventListener('touchend', terminarPintar, false);
            // prevent elastic scrolling
            pizarra_canvas.addEventListener('touchmove', function (event) {
               event.preventDefault();
            }, false); 
		}
		else{
			pizarra_canvas.addEventListener("mousedown",empezarPintar,false);
			pizarra_canvas.addEventListener("mouseup",terminarPintar,false);	
		}
}
function empezarPintar(e){
		pizarra_context.beginPath();
		pizarra_context.moveTo(e.clientX-pizarra_canvas.offsetLeft,e.clientY-pizarra_canvas.offsetTop);
		pizarra_canvas.addEventListener("mousemove",pintar,false);
		if (is_touch_device) {
			xStart=e.touches[0].pageX-pizarra_canvas.offsetLeft;
            yStart=e.touches[0].pageY-pizarra_canvas.offsetTop;
			pizarra_canvas.addEventListener('touchmove', pintar, false);
		}
		else{
			xStart=e.clientX-pizarra_canvas.offsetLeft;
			yStart=e.clientY-pizarra_canvas.offsetTop;
		}
}
function terminarPintar(e){
	if (is_touch_device) {
		fX=e.changedTouches[0].pageX;
		fY=e.changedTouches[0].pageY;
	}
	else{
		fX=e.clientX;
		fY=e.clientY;
	}
	if ((drawTool=="Rectangle") || (drawTool=="Line") || (drawTool=="Circle") || (drawTool=="Point") || (drawTool=="Poly")) {
		var c=pizarra_canvas.getContext("2d");
		var grosor=c.lineWidth;
		if ((drawTool=="Circle") || (drawTool=="Poly")){
			var radio=Math.round(Math.sqrt((fX-xStart)*(fX-xStart)+(fY - yStart)*(fY - yStart)));	
			radio=radio+2;
			if (xStart-grosor-radio<xMin){xMin=xStart-grosor-radio;}
			if (xStart+grosor+radio>xMax){xMax=xStart+grosor+radio;}
			if (yStart-grosor-radio<yMin) {yMin=yStart-grosor-radio;}
			if (yStart+grosor+radio>yMax) {yMax=yStart+grosor+radio;}
		}
		if ((drawTool=="Rectangle") || (drawTool=="Line") || (drawTool=="Point")) {
			if (xStart-grosor<xMin){xMin=xStart-grosor-2;}
			if (xStart+grosor>xMax){xMax=xStart+grosor+2;}
			if (yStart-grosor<yMin) {yMin=yStart-grosor-2;}
			if (yStart+grosor>yMax) {yMax=yStart+grosor+2;}
			if (fX-grosor-pizarra_canvas.offsetLeft<xMin){xMin=fX-grosor-pizarra_canvas.offsetLeft-2;}
			if (fX+grosor-pizarra_canvas.offsetLeft>xMax){xMax=fX+grosor-pizarra_canvas.offsetLeft+2;}
			if (fY-grosor-pizarra_canvas.offsetTop<yMin) {yMin=fY-grosor-pizarra_canvas.offsetTop-2;}
			if (fY+grosor-pizarra_canvas.offsetTop>yMax) {yMax=fY+grosor-pizarra_canvas.offsetTop+2;}
		}
		c.drawImage(canvasAux,0,0);
		canvasAux.width=canvasAux.width;
		reorganizaLimites();
	}
	pizarra_canvas.removeEventListener("mousemove",pintar,false);
	pizarra_canvas.removeEventListener('touchmove', pintar, false);
}
function saveCanvas(){
	if (xMin>xMax){ 
		cancelaNuevoCanvas();
	}
	else{
		xMax=xMax+5; yMax=yMax+5;
		var objPizarra = document.getElementById("pizarra");
		var objCanvas = document.createElement("canvas");
		objCanvas.id = "canvasRecorte";
		objCanvas.width=xMax-xMin;
		objCanvas.height=yMax-yMin;
		objCanvas.style.visibility="hidden";
		objPizarra.appendChild(objCanvas);
		var c=objCanvas.getContext("2d");
		var canvas = document.getElementById("canvas01");
		c.drawImage(canvas, xMin, yMin, xMax-xMin,yMax-yMin,0,0,xMax-xMin,yMax-yMin);
		var canvasData = objCanvas.toDataURL('image/png');
		var cssObj = {
			"z-index" : $(canvas).css("z-index")-1,
			"left" :xMin+5+"px",
			"top" :yMin+5+"px",
			"transform" : "rotate(0deg)",
			"-ms-transform" : "rotate(0deg)",
			"-webkit-transform" : "rotate(0deg)",
			"-moz-transform" : "rotate(0deg)",
			"-o-transform" : "rotate(0deg)"
		}
		var cssSend="";
		$.ajaxSetup({async:false});
		for (name in cssObj){cssSend=cssSend+name + ":" + cssObj[name]+"|";}
		$.post("saveXMLBack.php",{
			   		  folderG:folderGroup,
					  typeSave:"pngFile",
					  css:cssSend,
					  imageData: canvasData
		},function(data){},"json");
		$.ajaxSetup({async:true});
		objPizarra.removeChild(document.getElementById("canvasRecorte"));
		reFresh();
		borrar();
	}
}
function pintar(e) {
	if (is_touch_device) {
		fX=e.changedTouches[0].pageX;
		fY=e.changedTouches[0].pageY;
	}
	else{
		fX=e.clientX;
		fY=e.clientY;
	}
	var c=canvasAux.getContext("2d");
	c.clearRect(0,0,canvasAux.width,canvasAux.height);
	c.strokeStyle=drawCanvasColor;
	c.fillStyle=drawCanvasColor;
	c.lineWidth = $( "#amount" ).val();
	var grosor=c.lineWidth;
	if (drawTool=="Pen"){pizarra_context.lineTo(fX-pizarra_canvas.offsetLeft,fY-pizarra_canvas.offsetTop);}
	if (drawTool=="Rectangle"){
		c.beginPath();
		c.rect(xStart,yStart,fX-xStart,fY-yStart);
		indName=$("#drawFill").css("background-image").lastIndexOf("/")+1;
		if ($("#drawFill").css("background-image").substring(indName,indName+6)=="pinga1"){
			c.fill();
		}
		c.stroke();
		c.closePath();
	}
	if (drawTool=="Point"){
		    var headlen = (($( "#amount" ).val()/4)*10)+10;
    		var angle = Math.atan2(fY-yStart,fX-xStart);
    		c.lineWidth = 1;
			c.beginPath();
    		c.lineTo(fX-headlen*Math.cos(angle-Math.PI/6),fY-headlen*Math.sin(angle-Math.PI/6));
    		c.moveTo(fX,fY);
    		c.lineTo(fX-headlen*Math.cos(angle+Math.PI/6),fY-headlen*Math.sin(angle+Math.PI/6));
			c.lineTo(fX-headlen*Math.cos(angle-Math.PI/6),fY-headlen*Math.sin(angle-Math.PI/6));
			c.fill();
			c.closePath();
			c.beginPath();
			c.lineWidth = $( "#amount" ).val();
			c.moveTo(xStart, yStart);
    		xM=((fX-headlen*Math.cos(angle+Math.PI/6))+(fX-headlen*Math.cos(angle-Math.PI/6)))/2;
			yM=((fY-headlen*Math.sin(angle+Math.PI/6))+(fY-headlen*Math.sin(angle-Math.PI/6)))/2;
			c.lineTo(xM,yM);
			c.stroke();
	  		c.closePath();
	}
	if (drawTool=="Line"){	
	  c.beginPath();
      c.moveTo(xStart,yStart);
      c.lineTo(fX,fY);
	  c.stroke();
	  c.closePath();
	}
	if (drawTool=="Circle"){	
	  var radio=Math.round(Math.sqrt((fX-xStart)*(fX-xStart)+(fY - yStart)*(fY - yStart)))	
	  c.beginPath();
	  c.arc(xStart, yStart,radio, 0, 2 * Math.PI, false);  
	  indName=$("#drawFill").css("background-image").lastIndexOf("/")+1;
	  if ($("#drawFill").css("background-image").substring(indName,indName+6)=="pinga1"){
			c.fill();
	  }
	  c.stroke();
	  c.closePath();
	}
	if (drawTool=="Poly"){	
		var numberOfSides = drawPoly;
    	size = Math.round(Math.sqrt((fX-xStart)*(fX-xStart)+(fY - yStart)*(fY - yStart)));
		c.beginPath();
		c.moveTo (xStart +  size * Math.cos(0), yStart +  size *  Math.sin(0));          
		for (var i = 1; i <= numberOfSides;i += 1) {
    		c.lineTo (xStart + size * Math.cos(i * 2 * Math.PI / numberOfSides), yStart + size * Math.sin(i * 2 * Math.PI / numberOfSides));
		}
		indName=$("#drawFill").css("background-image").lastIndexOf("/")+1;
	  	if ($("#drawFill").css("background-image").substring(indName,indName+6)=="pinga1"){
			c.fill();
	  	}
		c.stroke();
	}
	if (drawTool=="Pen"){
		if (fX-grosor-pizarra_canvas.offsetLeft<xMin){xMin=fX-grosor-pizarra_canvas.offsetLeft-2;}
		if (fX+grosor-pizarra_canvas.offsetLeft>xMax){xMax=fX+grosor-pizarra_canvas.offsetLeft+2;}
		if (fY-grosor-pizarra_canvas.offsetTop<yMin) {yMin=fY-grosor-pizarra_canvas.offsetTop-2;}
		if (fY+grosor-pizarra_canvas.offsetTop>yMax) {yMax=fY+grosor-pizarra_canvas.offsetTop+2;}
	}
	reorganizaLimites();
	pizarra_context.stroke();
}
function reorganizaLimites(){
	if (xMin<0){ xMin=0;}
	if (yMin<0){ yMin=0;}
	if (xMax>parseInt($(pizarra_canvas).css("width").replace("px",""))){ xMax=parseInt($(pizarra_canvas).css("width").replace("px",""))}
	if (yMax>parseInt($(pizarra_canvas).css("height").replace("px",""))){ yMax=parseInt($(pizarra_canvas).css("height").replace("px",""))}
}
function borrar(){pizarra_canvas.width = pizarra_canvas.width;}
function crearNuevoCanvas(){
		if (isOpenCanvas){
				pizarra_canvas.removeEventListener("mousedown",empezarPintar,false);
				pizarra_canvas.removeEventListener("mouseup",terminarPintar,false);
				pizarra_canvas.removeEventListener('touchstart', empezarPintar, false);
            	pizarra_canvas.removeEventListener('touchend', terminarPintar, false);
				saveCanvas();
				isOpenCanvas=false;
				selected=null;
				document.getElementById("pizarra").removeChild(document.getElementById("canvasAux"));
				crearNuevoCanvas();
		}
		else{
			if (selected==null){	
				isOpenCanvas=true;
				widthPizarra=$("#pizarra").css("width").replace("px","");
				heightPizarra=$("#pizarra").css("height").replace("px","");
				$("#canvas01").attr({"width":widthPizarra,"height":heightPizarra});
				selected = document.getElementById("canvas01");
				var objPizarra = document.getElementById("pizarra");
				var objCanvas = document.createElement("canvas");
				var canvas = document.getElementById("canvas01");
				objCanvas.id = "canvasAux";
				objCanvas.width=canvas.width;
				objCanvas.height=canvas.height;				
				objPizarra.appendChild(objCanvas);
				drawUpgrade();
				$("#drawBar").css("visibility", "visible");
				initCanvas();
				$("#bNewCanvas").css("visibility", "hidden");
				$("#canvas01").css("cursor","crosshair");
			}
		}
}
function cancelaNuevoCanvas(){
	borrar();
	pizarra_canvas.removeEventListener("mousedown",empezarPintar,false);
	pizarra_canvas.removeEventListener("mouseup",terminarPintar,false);
	pizarra_canvas.removeEventListener('touchstart', empezarPintar, false);
    pizarra_canvas.removeEventListener('touchend', terminarPintar, false);        	
	isOpenCanvas=false;
	var cssObj = {"z-index" : 0};
	$(pizarra_canvas).css(cssObj);
	selected=null;
	$("#drawBar").css("visibility", "hidden");
	$("#bNewCanvas").css("visibility", "visible");
	$("#drawSliderBar").css("visibility","hidden");
	$("#drawSliderPoly").css("visibility","hidden");
	$("#canvas01").css("cursor","default");
	document.getElementById("pizarra").removeChild(document.getElementById("canvasAux"));
}
function drawSideChange(){
	if (drawSide=="R"){
		$("#bDrawSide").html('<span class="ui-icon ui-icon-arrowthickstop-1-w"></span>');
		$("#drawBar").removeClass("drawBarClassL");
		$("#drawBar").addClass("drawBarClassR");
		$("#drawSliderBar").removeClass("drawSliderBarClassL");
		$("#drawSliderBar").addClass("drawSliderBarClassR");
		$("#drawSliderPoly").removeClass("drawSliderBarClassL");
		$("#drawSliderPoly").addClass("drawSliderBarClassR");
		
		drawSide="L";
	}
	else{
		$("#bDrawSide").html('<span class="ui-icon ui-icon-arrowthickstop-1-e"></span>');
		$("#drawBar").removeClass("drawBarClassR");
		$("#drawBar").addClass("drawBarClassL");
		$("#drawSliderBar").removeClass("drawSliderBarClassR");
		$("#drawSliderBar").addClass("drawSliderBarClassL");
		$("#drawSliderPoly").removeClass("drawSliderBarClassR");
		$("#drawSliderPoly").addClass("drawSliderBarClassL");
		drawSide="R";
	}
}
function drawUpgrade(){	
	pizarra_canvas = document.getElementById("canvas01");
	pizarra_context = pizarra_canvas.getContext("2d");
	pizarra_context.strokeStyle=drawCanvasColor;
	pizarra_context.lineWidth = $( "#amount" ).val();
	canvasAux=document.getElementById("canvasAux");
	var valueZ=giveZindex()+1;
	var cssObj = {"z-index" : valueZ};	
	$(pizarra_canvas).css(cssObj);
	var canvasAux_zIndex=$(pizarra_canvas).css("z-index")+1;
	if (drawTool=="Pen"){
		$("#drawPen").addClass("ui-state-highlight");
		$(canvasAux).css("z-index",0);
	}
	else{$("#drawPen").removeClass("ui-state-highlight");}
	if (drawTool=="Rectangle"){
		$("#drawRectangle").addClass("ui-state-highlight");
		$(canvasAux).css("z-index",canvasAux_zIndex);
	}
	else{$("#drawRectangle").removeClass("ui-state-highlight");}
	if (drawTool=="Line"){
		$("#drawLine").addClass("ui-state-highlight");
		$(canvasAux).css("z-index",canvasAux_zIndex);
	}
	else{$("#drawLine").removeClass("ui-state-highlight");}
	if (drawTool=="Circle"){
		$("#drawCircle").addClass("ui-state-highlight");
		$(canvasAux).css("z-index",canvasAux_zIndex);
	}
	else{$("#drawCircle").removeClass("ui-state-highlight");}
	if (drawTool=="Point"){
		$("#drawPoint").addClass("ui-state-highlight");
		$(canvasAux).css("z-index",canvasAux_zIndex);
	}
	else{$("#drawPoint").removeClass("ui-state-highlight");}
	if (drawTool=="Poly"){
		$("#drawPoly").addClass("ui-state-highlight");
		$(canvasAux).css("z-index",canvasAux_zIndex);
	}
	else{$("#drawPoly").removeClass("ui-state-highlight");}
}
function showSlide(){
	if ($("#drawSliderBar").css("visibility")=="hidden"){
		$("#drawSliderPoly").css("visibility","hidden");
		$("#drawSliderBar").css("visibility","visible");
	}
	else{
		$("#drawSliderBar").css("visibility","hidden");
	}
}
function showSlidePoly(){
	if ($("#drawSliderPoly").css("visibility")=="hidden"){
		$("#drawSliderBar").css("visibility","hidden");
		$("#drawSliderPoly").css("visibility","visible");
	}
	else{
		$("#drawSliderPoly").css("visibility","hidden");
	}
}
function selectRectangle(){drawTool="Rectangle";drawUpgrade();}
function selectPen(){drawTool="Pen";drawUpgrade();}
function selectLine(){drawTool="Line";drawUpgrade();}
function selectCircle(){drawTool="Circle";drawUpgrade();}
function selectPoint(){drawTool="Point";drawUpgrade();}
function selectFill(){
	indName=$("#drawFill").css("background-image").lastIndexOf("/")+1;
	if ($("#drawFill").css("background-image").substring(indName,indName+6)=="pinga0"){
		$("#drawFill").attr("style", "background-image: url('img/pinga1.png') !important");
	}
	else{
		$("#drawFill").attr("style", "background-image: url('img/pinga0.png') !important");
	}
}
function selectPoly(){showSlidePoly();drawTool="Poly";drawUpgrade();}
