function close(id){
	var answer = confirm("Are you sure you want to remove this note?")
	if (answer){
		$("#"+id).remove();
		notes = $.grep(notes, function(val) { return val != id; });
	}
}
function clear(){
	var answer = confirm("Are you sure you wish to clear the page? This cannot be undone.")
	if (answer){
		if(url != ""){
			window.location = '/draw.php?url='+url;
		}else{
			window.location = '/v/'+token;
		}
	}
}

function addNote(){
	boxIndex = boxIndex+1;
	var id = random();
	$(document.createElement("div")).attr("id",id).attr("class","box").attr("style","background-color: "+divBG+"; top: "+(Math.floor(Math.random()*300)+10)+"; z-index: "+boxIndex).html('<div style="float: left; width: 70%; font-weight: bold;">'+name+'\'s Note</div><div style="text-align: right; width: 30%; float: right;"><a href="javascript:close(\''+id+'\');">close</a></div><div style="clear: both;"></div><div id="'+id+'-text">Double click here to edit...</div>').prependTo("body");
	if(isMobile){
		$("#"+id+"-text").bind('touchend', function(event) {
			var current = $("#"+id+"-text").html();
			var name = prompt("What would you like the box to say?", current);
			$("#"+id+"-text").html(name);
		});
		$("#"+id).touch({
		    animate: false,
		    sticky: false,
		    dragx: true,
		    dragy: true,
		    rotate: false,
		    resort: false,
		    scale: false
		});
	}else{
		$("#"+id+"-text").dblclick(function() {
			var current = $("#"+id+"-text").html();
			var name = prompt("What would you like the box to say?", current);
			$("#"+id+"-text").html(name);
		});
		$("#"+id).draggable().resizable();
	}
	notes.push(id);
}
function saveWork(){
	$.blockUI({ 
    message: $('#saving'), 
    css: { top: '30%' } 
  });
	if(notes.length > 0){
		var dividerStrings = "";
		for(i=0;i<notes.length;i++){
			var position = $('#'+notes[i]).position();
			var previousName = $('#'+notes[i]).attr("name");
			var content = $('#'+notes[i]+'-text').html();
			var divider = new Object();
			divider.id = notes[i];
			if(previousName !== undefined && previousName.length > 0)
				divider.name = previousName;
			else
				divider.name = name;
			divider.top = position['top'];
			divider.left = position['left'];
			divider.height = $('#'+notes[i]).height();
			divider.width = $('#'+notes[i]).width();
			divider.bg = $('#'+notes[i]).css("background-color");
			divider.content = content;
			if(i != 0)
				dividerStrings += "|";
			dividerStrings += JSON.stringify(divider);
		}
	}
	//This will save the strings
	$.post("/accept.php", { 'div[]': [dividerStrings,token,url,screenWidth] }, 
	function(data){
		if(data == "TRUE"){
			bRes = canvas.toDataURL();
			if (!bRes) {
				alert("Sorry, this browser is not capable of saving PNG files!");
				return false;
			}
			//This will save the image
			try{
				$.post("/save.php", { 'file[]': [bRes,token,"png"] }, 
				function(data){
					if(data == "TRUE"){
						$("#controlBoxLink").html("<input type=\"text\" id=\"controlBoxLinkText\"value=\"http://dodraw.com/"+token+"\" onClick=\"selectAll('controlBoxLinkText');\" size=\"45\">");
						$.blockUI({ 
			        message: $('#controlBox'), 
			        css: { top: '30%' } 
			      });
					}else{
						$.blockUI({ 
			        message: "<p style='padding: 20px;'><strong>Your drawing could not be saved.</strong><br><br>Please click 'send to a colleague' again.</p>", 
			        css: { top: '30%' } 
			      });
						setTimeout($.unblockUI, 4000);
					}
				});
			}catch(e){
				alert(e);
			}
		}else{
			$.blockUI({ 
        message: "<p style='padding: 20px;'><strong>Your message could not be saved.</strong><br><br>Please click 'send to a colleague' again.</p>", 
        css: { top: '30%' } 
      });
			setTimeout($.unblockUI, 4000); 
		}
	});
}
function closeBox(){
	$.unblockUI();
}
function help(){
	$.blockUI({ 
    message: $('#helpBox'), 
    css: { top: '30%' } 
  });
}
function saveName(){
	name = $("#name").val();
	userEmail = $("#userEmail").val();
	$.post("/session.php", { 'user[]': [name,userEmail] }, 
	function(data){
		$.growlUI('Thank you '+name+'!','Your settings have been saved.'); 
	});
}
function showEmail(){
	$("#emailBox").show("fast");
}
function sendEmail(){
	var senderName = name;
	var email = userEmail;
	var recipient = $("#recipientEmail").val();
	var recipientMessage = $("#recipientMessage").val();
	$.post("/send.php", { 'emailer[]': [senderName,recipient,token,email,recipientMessage] }, 
	function(data){
		if(data == "1"){
			$.growlUI('Email sent successfully!'); 
			$("#controlBox").html();
		}else{
			alert("Failed! "+data);
		}
	});
}
function randomNum(len){
	var num = Math.floor(Math.random()*(len-1));
	return num;
}
function random(){
	var letter = "notes";
	var num = Math.floor(Math.random()*10000);
	return letter+num;
}
function setColor(color){
	pen.strokeStyle = color;
}
function selectAll(id)
{
  document.getElementById(id).focus();
  document.getElementById(id).select();
}
jQuery.event.special.tripleclick = {
    setup: function(data, namespaces) {
        var elem = this, $elem = jQuery(elem);
        $elem.bind('touchend', jQuery.event.special.tripleclick.handler);
    },

    teardown: function(namespaces) {
        var elem = this, $elem = jQuery(elem);
        $elem.unbind('touchend', jQuery.event.special.tripleclick.handler);
    },

    handler: function(event) {
        var elem = this, $elem = jQuery(elem), clicks = $elem.data('clicks') || 0;
        clicks += 1;
        if ( clicks === 2 ) {
            clicks = 0;
            // set event type to "tripleclick"
            event.type = "touchend";
            // let jQuery handle the triggering of "tripleclick" event handlers
            jQuery.event.handle.apply(this, arguments)
        }
        $elem.data('clicks', clicks);
    }
};
