// Copyright 2010 William Malone (www.williammalone.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var canvas;
var context;
var canvasWidth = 830;
var canvasHeight = 520;
var lineWidth = 8;
var outlineImage = new Image();

var drawingDots = new Array;
var loadedDots;

var paint = false;
var curColor = "#d14c2c";
var curTool = "mouse";
var curSize = "small";
var noteHasFocus = false;
var drawingAreaX = 0;
var drawingAreaY = 0;
var drawingAreaWidth = canvasWidth;
var drawingAreaHeight = canvasHeight;
var totalLoadResources = 1;
var curLoadResNum = 0;
/**
* Calls the redraw function after all neccessary resources are loaded.
*/



function touchHandler(event)
{
    var touches = event.changedTouches,
        first = touches[0],
        type = "";
         switch(event.type)
    {
        case "touchstart": type = "mousedown"; break;
        case "touchmove":  type="mousemove"; break;        
        case "touchend":   type="mouseup"; break;
        default: return;
    }

   //initMouseEvent(type, canBubble, cancelable, view, clickCount, 
    //           screenX, screenY, clientX, clientY, ctrlKey, 
    //           altKey, shiftKey, metaKey, button, relatedTarget);
    
    var simulatedEvent = document.createEvent("MouseEvent");
    simulatedEvent.initMouseEvent(type, true, true, window, 1, 
                              first.screenX, first.screenY, 
                              first.clientX, first.clientY, false, 
                              false, false, false, 0/*left*/, null);

                                                                                 first.target.dispatchEvent(simulatedEvent);
    event.preventDefault();
}

function resourceLoaded()
{
	if(++curLoadResNum >= totalLoadResources){
		redraw();
	}
}


/**
* Creates a canvas element, loads images, adds events, and draws the canvas for the first time.
*/
function prepareCanvas()
{
	
	if (TT.IS_TOUCH_DEVICE) {

	document.addEventListener("touchstart", touchHandler, true);
    document.addEventListener("touchmove", touchHandler, true);
    document.addEventListener("touchend", touchHandler, true);
    document.addEventListener("touchcancel", touchHandler, true); 
    }
    
	// Create the canvas (Neccessary for IE because it doesn't know what a canvas element is)
	canvas = document.createElement('canvas');
	var x = 0;
	$('.drawable').each(function() {
		x++;
		canvas = document.createElement('canvas');
		canvas.setAttribute('width', canvasWidth);
		canvas.setAttribute('height', canvasHeight);
		var id = $(this).attr("id");
		canvas.setAttribute('id', id);
		
		$(this).addClass("clickthrough");
		
		loadSketch($(canvas));
		loadNotes($(canvas));
		$(this).append(canvas);
		//drawing["canvas-"+x] = [];
		
		drawingDots[id] = [];
	
		//$("#console").text("added: "+$(canvas).attr("id"));
		
		
		//context = canvas.getContext("2d"); // Grab the 2d canvas context
	
			
		
		$(canvas).mousedown(function(e) {
			
			imgs = [];
			
			$(this).parent().parent().children(".content").children("img").each(function() { 
			
			pos = $(this).position();
				imgs.push(new Array(pos.left,pos.right));
			});
			
			//$("#console").text(imgs[4][0]);
						
			// Mouse down location
			var mouseX = e.layerX;
			var mouseY = e.layerY;
			

			
			//$("#console").text("down");
			
			
			if ((curTool == "note") && (noteHasFocus != true)) {
				//alert("add note");
				
				cid = $(this).attr("id");
				addNote(cid,mouseX,mouseY);
				noteHasFocus = true;
				
			} else if ((curTool == "note") && (noteHasFocus == true)) {
				//alert("add note");
				cid = $(this).attr("id");
				moveNote(cid,mouseX,mouseY);
				
			} else {
				paint = true;
				//$("#navigation").text("down: "+event.layerX);
				cid = $(this).attr("id");
				addClick(cid,mouseX, mouseY, 0);
				//$("#console").text("mouseX: "+mouseX+" | mouseY: "+mouseY);
			}
			//redraw(cid,'local');
			
			//redrawFromJson(cid);
		});
		
		$(canvas).mousemove(function(e){		
			if(paint==true){
				//$("#console").text("mousemove");
				cid = $(this).attr("id");
				addClick(cid,e.layerX+drawingAreaX, e.layerY+drawingAreaY, 1);
				redraw(cid,'local');
				
			}
		});
		
		$(canvas).mouseup(function(e){
			//$("#console").text("up");
			var mouseX = e.layerX;
			var mouseY = e.layerY;
			paint = false;
			cid = $(this).attr("id");
			//$("#console").text($(this).attr("id"));
			saveSketch($(canvas));
		    
		    	
		  	redraw(cid,'local');
		});
		
		$(canvas).mouseleave(function(e){
			var mouseX = e.layerX;
			var mouseY = e.layerY;
/*			if ($("canvas").mouseenter(function(e){
				// mouse left but entered another canvas area
				if (paint == true) { 
					var stay = 1;

					
					first = $(this).parent().parent().parent().children(":first").children(":first").children("canvas:first").attr("id");
					
					if ($(this).attr("id") == first) {
						newMouseX = mouseX+490;
					} else {
						newMouseX = mouseX-490;
					}
					//$("#navigation").text("first: "+first);
					addClick($(this).attr("id"),newMouseX, mouseY, false);

				 }

				//$("#navigation").text("aan de bak");
			}));
			*/

			paint = false;
			saveSketch($(canvas));
			
			//$("#navigation").text("");

			
			
		});
		
		$("img").hover(function() {
			//$("#console").text("hovered: "+$(this).attr("class"));
		});
    }); 


}

function saveSketch(canvas) {
	var cid = canvas.attr("id");
	
	//TT.log("drawingDots[id]: "+drawingDots[cid]);
	
	
	$.ajax({
        url: SERVER_VARIABLES.DRAWTO,
        type: "post",
        data: {cid: cid, pic: drawingDots[cid]}, 
        success: function(msg)
        {
           //$("#console").text(msg);
           // display some message and/or redirect
        }
    });
    
}

function loadSketch(canvas) {
	var cid = canvas.attr("id");
	
	//TT.log("drawingDots[id]: "+drawingDots[cid]);
	
	
	$.ajax({
        url: SERVER_VARIABLES.DRAWTO,
        type: "post",
        data: {cid: cid}, 
        success: function(dots)
        {

           loadedDots = dots;
           redraw(cid,'json');
        }
    });
    
}

function randomFromTo(from, to){
       return Math.floor(Math.random() * (to - from + 1) + from);
}

function loadNotes(canvas) {
	var cid = canvas.attr("id");
	canvas = $(".drawable#"+cid);
	
	//TT.log("drawingDots[id]: "+drawingDots[cid]);
	
	$.ajax({
        url: SERVER_VARIABLES.COMMENT,
        type: "post",
        data: {cid: cid}, 
        success: function(notes)
        {

			notes = $.parseJSON(notes);
			var x = 0;
			
			$.each(notes, function () {

				comment_id = parseInt(notes[x][0]);
				post_id = parseInt(notes[x][1]);
				
				xpos = parseInt(notes[x][2]);
				ypos = parseInt(notes[x][3]);
				
				comment = notes[x][4];

				note = document.createElement('div');
				note.setAttribute('class', 'note');
				note.setAttribute('id', "comment_"+comment_id);
				$(note).addClass('rotate-'+randomFromTo(1,5));
				
				text = document.createElement('div');
				text.setAttribute('class', 'stext');
				
				$(text).text(comment);
				
				
				$(note).append(text);
								
				$(note).css({top: ypos, left: xpos, opacity:1, zIndex: 100+comment_id});
				//alert("epos: "+ypos+ " xpos:"+xpos);
				
				canvas.append(note);
				
				
				$(note).hover(function() {
					normalZindex = $(this).css('z-index');
					$(this).css({ zIndex: 500});
				},function() {
					$(this).css({ zIndex: normalZindex});
				});
				
				
				//$(note).animate({opacity: 1});
				
				
				x++;
			});
			
		 }
    });
    
}

function generateNote(note,x,y,comment_id) {

}

function moveNote(cid,x,y) {
	if ((canvasWidth - x) <= 180) {
		x = x - 180;
	}
	if ((canvasHeight - y) <= 150) {
		y = y - 150;
	}
	$('.unfinished').css({top: y, left: x});
}

function addNote(cid,x,y){
	canvas = $(".drawable#"+cid);

	note = document.createElement('div');
	note.setAttribute('class', 'note');
	$(note).addClass('unfinished');

	text = document.createElement('textarea');
	text.setAttribute("maxlength",133);
	//$(text).css({width: "130px", height: "110px",backgroundColor: "#f5f5f5", zIndex: 999});

	cancel = document.createElement('input');
	cancel.type = 'button';
	cancel.value = 'cancel';
	
	submit = document.createElement('input');
	submit.type = 'submit';
	submit.value = 'post';

	 
	//submit.setAttribute('onclick', 'insertNote('+id+','+x+','+y+');');
	
	if ((canvasWidth - x) <= 180) {
		x = x - 180;
	}
	if ((canvasHeight - y) <= 150) {
		y = y - 150;
	}
	
	
	

	
	$(note).css({top: y, left: x, opacity: 0,zIndex: 999});
	$(note).append(text);
	
	$(note).append(submit);
	$(note).append(cancel);
	
	canvas.append(note);
	
	$(note).animate({opacity: 1});

	
	//event = (TT.IS_TOUCH_DEVICE) ? "touchstart" : "click";
	
	if (TT.IS_TOUCH_DEVICE) {
		$(submit).bind("touchstart", function(e) {
			saveNote(note,cid,x,y); $(note).removeClass("unfinished");
		});
		
		$(cancel).bind("touchstart", function(e) {
			$(note).animate({opacity: 0},function() {$(this).remove(); noteHasFocus = false; });
		});
		
	} else {
		$(submit).bind("click", function(e) { saveNote(note,cid,x,y); $(note).removeClass("unfinished"); });
		$(cancel).bind("click", function(e) { $(note).animate({opacity: 0},function() {$(this).remove(); noteHasFocus = false; }); });
	}
	
	/*
	cancel.onclick = function() { 
	$(note).animate({opacity: 0},function() {$(this).remove(); noteHasFocus = false; });
	};
	
	submit.onclick = function() { saveNote(note,cid,x,y); $(note).removeClass("unfinished"); };
	*/
		
}

function saveNote(note,cid,x,y) {
	comment = $(note).children("textarea").val();
	
	
	$.ajax({
        url: SERVER_VARIABLES.COMMENT,
        type: "post",
        data: {cid: cid, x: x, y: y,comment: comment}, 
        success: function(msg)
        {
			$(note).children("input").animate({opacity: 0},function() {$(this).hide();});
			$(note).children("textarea").attr("disabled","true");
			noteHasFocus = false;
			//$("#console").text("comment: "+comment+" return: "+msg);
        }
    });
    
}


/**
* Adds a point to the drawing array.
* @param x
* @param y
* @param dragging
*/
function addClick(id,x, y, dragging)
{
	if (curTool == "eraser") {
		curColor = "white";
		curSize = "normal";
	} else {
		curSize = "small";
	}

	var dot = new Array(x,y,curTool,curColor,curSize,dragging);
	drawingDots[id].push(dot);
	
}


/**
* Clears the canvas.
*/
function clearCanvas(context)
{
	//context.fillStyle = '#ffffff'; // Work around for Chrome
	//context.fillRect(0, 0, canvasWidth, canvasHeight); // Fill in the canvas with white
	canvas.width = canvas.width; // clears the canvas 
}

function redraw(cid,method) {
	canvas = $("canvas#"+cid);
	context = canvas[0].getContext("2d"); // Grab the 2d canvas context
	
	clearCanvas(context);
	var locX;
	var locY;
	
	
	// Keep the drawing in the drawing area
	context.save();
	context.beginPath();
	context.rect(drawingAreaX, drawingAreaY, drawingAreaWidth, drawingAreaHeight);
	context.clip();
	var radius;
	var x = 0;	
	
	if (method == "json") {
		dots = $.parseJSON(loadedDots);
	} else {
		dots = new Array(drawingDots[cid]);
	}
	
	
	
	for(; x < dots.length; x++) {

		var i = 0;
		for(; i < dots[x].length; i++) {

			clickX = dots[x][i][0];
			
			if (i) {
				prevclickX = dots[x][i-1][0];
				prevclickY = dots[x][i-1][1];
			}
			clickY = dots[x][i][1];
	
			clickTool = dots[x][i][2];
			clickColor = dots[x][i][3];
			clickSize = dots[x][i][4];
			clickDrag = dots[x][i][5];
			
			
			//$("#console").text("x:"+ dots[0][0]);
			
			if(clickSize == "small"){
				radius = 1;
			} else if(clickSize == "normal") {
				radius = 5;
			} else if(clickSize == "large") {
				radius = 10;
			} else if(clickSize == "huge") {
				radius = 20;
			} else{
				//alert("Error: Radius is zero for click " + i);
				radius = 0;	
			}
			
			context.beginPath();
			
			if (method != "json") {
				//$("#console").text("clickDrag: "+clickX);
			}
			
			if(clickDrag == "1" && i) {
				context.moveTo(prevclickX, prevclickY);
			} else {
				// hier lijkt het fout te gaan..?
				context.moveTo(clickX, clickY);
				//context.moveTo(0, 0);
			}
			context.lineTo(clickX, clickY);
			
			//context.closePath();
			
			if(clickTool == "eraser"){
				context.globalCompositeOperation = "destination-out"; // To erase instead of draw over with white
				context.strokeStyle = 'white';
			}else{
				context.globalCompositeOperation = "source-over";	// To erase instead of draw over with white
				context.strokeStyle = clickColor;
			}
			context.lineJoin = "round";
			context.lineWidth = radius;
			context.stroke();
		}
		
	}
	
	context.globalCompositeOperation = "source-over";// To erase instead of draw over with white
	context.restore();
	
	
}
