var drawingCanvas = document.getElementById('myDrawing');
var pedals = new Array(0);
//var size = 28.125;
var size = 25;
var floorWidth=0;
var floorHeight=0;
var context = null;
var selected = -1;
var soX = 0;
var soY = 0;
var cOffX = 0;
var cOffY = 0;
var dirty = false;
var board = "pt-pro";
var boardimage;
var order = new Array(0);
var added = 0;

colors = new Array("#733","#444","#55A","#6B6","#D77","#881","#949","#1BC","#1E1","#D4D","#BBB","#2B2","#B1B");
	
function dialogs(number){
	return;
	if(added == 5){
		$('#MESSAGE').dialog('option','title','Pedalboard Planner Suggestions');
		$('#MESSAGE').load('/dialogs/ads.php');
		$('#MESSAGE').dialog('open');
	}
		
	if(added > 6 && added % 5 == 0){
		$('#MESSAGE').dialog('option','title','Pedalboard Planner Suggestions');
		$('#MESSAGE').load('/dialogs/ads.php');
		$('#MESSAGE').dialog('open');
	}	
		
}	

function Point(x,y){
	this.x = x;
	this.y = y;
}



function pedal(){
	this.id 	= "";
	this.pid    = 0;
	this.active = 1;
	this.height = 5;
	this.width  = 3;
	this.x      = 1;
	this.y      = 1;
	this.input  = new Point(-1,-1);
	this.output = new Point(-1,-1);

	this.fill   = "#FFFFFF";
	this.outline= "#000000";
	this.name = "";
	this.rotation = 0;
	this.selected = false;
	this.image = "";
	this.custom = true;
	this.link = "";
	this.notes = "";
	this.connected = true;
	
	this.contains = function(x,y){
		y = y+10;
		if(this.rotation == 0){
			if( (x >= this.x * size && x <= (this.x*size +this.width*size) ) &&
			(y >= this.y * size && y <= (this.y*size+ this.height*size) ) )
			{ 
				return true; 
			}
		else 
			{
				return false;
			}
		}
		var o = new Point(this.x * size,this.y * size);
		var d = 360-this.rotation;
		var p = new Point(x,y);
		var np = new Point(0,0);
		
		if(d != 0){
			p.x += (0 - o.x);
			p.y += (0 - o.y);
			np.x = (p.x * Math.cos(d * (Math.PI/180))) - (p.y * Math.sin(d * (Math.PI/180)));
			np.y = Math.sin(d * (Math.PI/180)) * p.x + Math.cos(d * (Math.PI/180)) * p.y;
			np.x += (0 + o.x);
			np.y += (0 + o.y)	
		}
		
		if( (np.x >= this.x * size && np.x <= (this.x*size +this.width*size) ) &&
			(np.y >= this.y * size && np.y <= (this.y*size+ this.height*size) ) )
		{ 
			return true; 
		}
		else 
		{
			return false;
		}
	}
	
	this.draw = function(){
	
		//if(this.x*size > floorWidth || this.y*size > floorHeight){
		//	this.x = floorWidth /2;
		//	this.y = floorHeight/2;
		//}
	
		context.save();
		size = parseFloat(size);
		if(this.image != ""){
			context.save();
				context.shadowOffsetX = 4;
				context.shadowOffsetY = 4;
				context.shadowBlur = 4;
				context.shadowColor = "rgba(0, 0, 0, 0.6)";
				context.translate(this.x* size,this.y* size);
				context.rotate(this.rotation * (Math.PI/180));
				context.drawImage(this.image, 0 ,0, this.width * size, this.height * size);
			context.restore();
		} else {
			
			
			context.strokeStyle = this.outline;
			
			context.fillStyle = this.fill;
			context.save();
			context.shadowOffsetX = 4;
			context.shadowOffsetY = 4;
			context.shadowBlur = 3;
			context.shadowColor = "rgba(0, 0, 0, 0.5)";
			
			context.translate(this.x* size,this.y* size);
			context.rotate(this.rotation * (Math.PI/180));
			
			context.beginPath();
			context.rect(0,0, this.width * size, this.height * size);
			context.closePath();
			context.stroke();
			context.fill();
			context.restore();
			
			context.fillStyle = "#000000";	
			context.font = "10pt Arial";
			context.textAlign = "center";
			
			if(context.fillText){
				context.fillText(this.name,(this.x+this.width/2) * size,(this.y+0.5)* size, this.width* size);
			}
		}

		context.restore();
	} 
}

				
for(var i in boards){
	boards[i].img = new Image();
	boards[i].img.src = boards[i].image;
}					
				

$(document).ready(function(){
			$('#TEXTOUT').dialog({autoOpen:false,title:'Effects Lineup',width:'500px'});
			$('#CONNECTIONS').click(refresh);
			$('.menuDone, #BLOCKOUT').click(function(){
							$('.menuScreen').slideUp('slow');	
							$('#BLOCKOUT').fadeOut('slow');
						});
		
			$("#WELCOMEBUTTON").click(function(){
								if($('#BLOCKOUT').css('display') == 'none'){
									$('#BLOCKOUT').fadeIn('slow');
								}
								
								$('#HELPSCREEN').slideUp('slow');
								$('#VENDORSCREEN').slideUp('slow');
								$("#WELCOMESCREEN").slideDown('slow');
							});
									
			$("#HELPBUTTON").click(function(){ 
								if($('#BLOCKOUT').css('display') == 'none'){
									$('#BLOCKOUT').fadeIn('slow');
								}
								$('#BLOCKOUT').show();
								$('#WELCOMESCREEN').slideUp('slow');
								$('#VENDORSCREEN').slideUp('slow');
								$("#HELPSCREEN").slideDown('slow');
							});
			$("#VENDORBUTTON").click(function(){ 
								if($('#BLOCKOUT').css('display') == 'none'){
									$('#BLOCKOUT').fadeIn('slow');
								}
								$('#HELPSCREEN').slideUp('slow');
								$('#WELCOMESCREEN').slideUp('slow');
								$("#VENDORSCREEN").slideDown('slow');
							});			





	$(".SORTABLE").sortable(
						{stop:function(){
							order = $(this).sortable('toArray');
							refresh();	
						}
						}
						);


	cOffX = $("#myDrawing").position().left;
	cOffY = $("#myDrawing").position().top;
	drawingCanvas = document.getElementById('myDrawing');
	if(drawingCanvas.getContext) {
		context = drawingCanvas.getContext('2d');	
		refresh();
	}
	
	
	
});

function getImage(){
	var canvas = document.getElementById("myDrawing");
	$("#IMGGET").attr('action',canvas.toDataURL("image/png"));
	$("#IMGGET").submit();
}

function conn(id){
	pedals[id].connected = !(pedals[id].connected);
	refresh();
}

// Functions



$(document).ready(function(){
	$("#bselect").change(function(){ board = $(this).val();refresh(); });
	$("#myDrawing").mousedown(clicker);
	$("#myDrawing").mouseup(unclicker);	
	$("#myDrawing").dblclick(doubleClicker);
	$("#myDrawing").mousemove(dragger);
	$("#addToolbar").dialog({'autoOpen':false,title:'Pedal Tools',width:'350px'});
	$("#settingToolbar").dialog({
							'title':'Settings',
							position: 'right',
							'autoOpen':false,
							'width':'500px'
							});	
	$("#editPedal").dialog({
							autoOpen:false,
							position: 'left',
							buttons:{
								'Delete': function(){
									deletePedal();
								},
								'Cancel': function(){
									$("#editPedal").dialog('close');
								},
								'OK':function(){
									editPedal();
									$("#editPedal").dialog('close');
								}
								
							}
							});
	$("#addPedal").dialog({
							autoOpen:false,
							
							buttons:{
								'Cancel': function(){
									$("#addPedal").dialog('close');
								},
								'OK':function(){
									addPedalDrop();
									$("#addPedal").dialog('close');
								}
							}
						});
});



function addPedalDialog(){
	$("#addPedal").dialog('open');
}


function tryload(i){
	if(i.complete == true){
		refresh();
	} else {
		setTimeout("tryload(i);",500);
	}
}
function addPedalDrop(){
	if($("#PED").val() == ""){
		return;
	}
	//addPedal($("#PED").val());
	
	$.ajax({
			url:'ajax/getpedal.php',
			type:'post',
			data:{id:$("#PED").val()},
			dataType:'json',
			success:function(r){addPedal(r);}
	});
}

function addPedal(i){
	p = new pedal();
	p.name 		= i.name;
	p.height 	= i.height;
	p.width  	= i.width;
	p.link   	= i.link;	
	p.notes  	= i.notes;
	p.pid		= i.pedal_id;
	if(i.input_x != ''){
		p.input.x = i.input_x;
		p.input.y = i.input_y;
	}
	if(i.output_y != ''){
		p.output.x = i.output_x;
		p.output.y = i.output_y;
	}	
	p.image = new Image();
	
	p.onLoad = function(){ alert('test');refresh(); };
	p.custom = false;
	p.image.src = "/pedalimages/"+i.file; 
	pedals.push(p);
	number = pedals.length-1;
	
	addEntry(i,number);
	
	dirty = true;
	refresh();
}
function addEntry(i,number){
	var line = "<DIV CLASS=PART CODE='"+i.pedal_code+"' ID='PART_"+number.toString()+"'>";
	line += "<img src=/ui-images/cancel.png onClick='deleteAPedal(\""+number.toString()+"\")' TITLE='Remove'>";
	line = line + "<IMG SRC=\"/pedalimages/"+i.file+"\" style=\"float:right\" height=80 onLoad='refresh();'>";
	line = line + "<SPAN STYLE='margin-left:10px;'>"+i.name+"</SPAN><BR>";
	line = line + "Height: " + i.height+ "in Width:"+  i.width + "in";
	line = line + "<BR>Connected: <INPUT TYPE=CHECKBOX CHECKED onChange='conn("+number.toString()+")'><BR>";
	
	if(i.link != ""){
	
		line = line +"<SPAN STYLE='margin-left:10px;'><A  TARGET=_NEW HREF='"+i.link+"'   onClick='pageTracker._trackPageview(\"/outbound/"+i.vendor_code+"\");'   >";
		line = line + i.link;
		line = line + "</A></SPAN>";
	}			
	if(i.notes){
		line = line + "<HR><SPAN STYLE='margin-left:10px;'>";
		line = line + i.notes;
		line = line + "</SPAN>";
	}
	pageTracker._trackPageview("/pedal/"+i.vendor_code+'-'+i.pedal_code); 	
	
	
	line = line + "</DIV>";
	$("#PARTSLIST").append(line);
	order = $(".SORTABLE").sortable('toArray');	
	added++;
	dialogs(added);
}

function editPedalDialog(p){

	$("#editPedal").dialog('open');
	$("#EDITID").val(p);
	$("#EDITX").val(pedals[p].width);	
	$("#EDITY").val(pedals[p].height);	
	if(pedals[p].custom){	
		$("#editPedal").dialog('option','title','Edit Pedal');
		$("#EDITSTATIC").hide();	
		$("#EDITNAME").val(pedals[p].name);
		$("#EDITCOLOR").val(pedals[p].fill);
			
		$("#EDITROT").val(pedals[p].rotation);	
		$("#EDITBLOCK").show();
	} else {
		$("#editPedal").dialog('option','title','Pedal Info');
		$("#EDITBLOCK").hide();
		$("#EDITSTATIC").html(pedals[p].name+"<BR>");
		if(pedals[p].link != ""){
			$("#EDITSTATIC").append("<A HREF='"+pedals[p].link+"'>"+pedals[p].link+"</A>");
		}
		$("#EDITROT").val(pedals[p].rotation);
		$("#EDITSTATIC").show();
	}
}
function editPedal(){
	p = $("#EDITID").val();
	if(pedals[p].custom){
	pedals[p].name = $("#EDITNAME").val();
		pedals[p].fill = $("#EDITCOLOR").val();
		pedals[p].width = parseInt($("#EDITX").val());	
		pedals[p].height = parseInt($("#EDITY").val());	
	}
	pedals[p].rotation = parseInt($("#EDITROT").val());
	refresh();
}

function deletePedal(){
	p = $("#EDITID").val();
	var id = "#PART_"+p.toString();
	$(id).remove();
	pedals[p].active = 0;
	$("#editPedal").dialog('close');
	order = $(".SORTABLE").sortable('toArray');	
	refresh();
}
function deleteAPedal(x){
	pedals[x].active = 0;
	var id = "#PART_"+x;
	$(id).remove();
	order = $(".SORTABLE").sortable('toArray');	
	refresh();
}

function dragger(e){
	if( dirty ){
		refresh();
	}

	if(selected >=0){
		$('BODY').css({'cursor':'move'});
		pedals[selected].x = ((e.pageX-cOffX)-soX)/size;
		pedals[selected].y = ((e.pageY-cOffY)-soY)/size;
		refresh();
	}
}

function doubleClicker(e){
	if(selected >= 0){
		pedals[selected].selected = false;
		selected = -1;
		
	}
	for(var p in pedals){
		if(pedals[p].active && pedals[p].contains(e.pageX-cOffX,e.pageY-cOffY))
		{
			editPedalDialog(p);
		}
	}
	refresh();	
}

function unclicker(){
	if(selected >= 0){
		$('BODY').css({'cursor':'default'});
		pedals[selected].selected = false;
		selected = -1;
		refresh();	
	}
}

function clicker(e){
	refresh();
	if(selected >= 0){
		pedals[selected].selected = false;
		selected = -1;
		refresh();	
	} else {
		for(var p in pedals){
			if(pedals[p].contains(e.pageX-cOffX,e.pageY-cOffY))
			{
				selected = p;
				pedals[p].selected = true;
				
				soX = (e.pageX-cOffX)-pedals[p].x*size;
				soY = (e.pageY-cOffY)-pedals[p].y*size;
			}
		}
	}
}
function doFloorSize(){
	if(board == "custom"){
		size= $("#myDrawing").width();
		size = size/parseFloat($("#FLOORWIDTH").val());
		floorWidth  = $("#myDrawing").width();
		floorHeight = parseFloat($("#FLOORHEIGHT").val())*size;
		$("#myDrawing").attr({height:(floorHeight+1)});
	} else {
		h = boards[board].height;
		w = boards[board].width;
		
		size= $("#myDrawing").width();
		size = size/parseFloat(w);
		floorWidth  = $("#myDrawing").width();
		floorHeight = parseFloat(h)*size;
		$("#myDrawing").attr({height:(floorHeight+1)});
	}
	//floorWidth  = boards[board].width*size;
	//floorHeight = boards[board].height*size;
	//$("#myDrawing").attr({height:(floorHeight+1)});
	//$("#myDrawing").attr({width:(floorWidth+1)});	
	
}

function drawFloor(){
	doFloorSize();
	context.save();
	if(board == "custom"){
		context.strokeStyle = "#000000";
		context.fillStyle = "#BBBBBB";
		context.beginPath();
		context.rect(0,0,floorWidth ,floorHeight );
		context.closePath();
		context.fill();
		for(var i = 0;i*92<floorWidth;i++){
			for(var j = 0;j*92<floorHeight;j++){
				context.drawImage(velcro, i*92,j*92, 92, 92);
			}
		}
		
		//context.stroke();
		context.textAlign = "left";
		context.fillStyle = "#222";	
		context.font = "14pt Arial";
		if(context.fillText){
			context.fillText("Pedalboard Size: "+$("#FLOORWIDTH").val()+"\"x"+$("#FLOORHEIGHT").val()+"\"",10,20);
		}
	} else {
		context.drawImage(boards[board].img, 0, 0, floorWidth, floorHeight);
	}
	
	context.restore();
}
function resize(){
	$("#myDrawing").attr('width',parseFloat($("#IMAGEWIDTH").val()));
	refresh();
}
function refresh(){
	cOffX = $("#myDrawing").position().left;
	cOffY = $("#myDrawing").position().top;

	for(var b in boards){
		if(!boards[b].img.complete){
			setTimeout("refresh()",500);
			return;
		}
	}

	if(dirty){
		$("#WAIT").show();
		var clean = true;
		for(var p in pedals){
			if(pedals[p].active){
				if(pedals[p].image){
					if(pedals[p].image.complete == false){
						clean = false;
					}
				}
			}
		}
		if(!clean){
			return;
		} else {
			$("#WAIT").hide();
			dirty = clean;
		}
	}

	context.clearRect(0, 0, floorWidth, floorHeight);
	drawFloor();
	
	var i = 0;
	context.save();
	
	context.shadowBlur = 10;
	context.shadowColor = "black";
	
	context.lineWidth   = 0.25*size;
	
	var l = -1;
	var p = -1;
	var temp = -1;
	var lastUsed = -1;
	
	
	if ($('#CONNECTIONS:checked').val() != null) {
	//if(1==1){
		for(var id in order){
			context.beginPath();
			p = order[id].split("_")[1];  

			if(pedals[p].connected == false){
				i++; continue;
			}
			
			if(lastUsed == -1){
				lastUsed = p;
				i++; 
				continue; 
			} 
			l = lastUsed;
							
			context.save();
			context.translate(pedals[l].x*size,pedals[l].y*size);
			context.rotate(pedals[l].rotation* (Math.PI/180));		
			if(pedals[l].output.x <= 0 && pedals[l].output.y <= 0){
				context.moveTo(0,pedals[l].height*size*3.0/8.0);
			} else {
				context.moveTo(pedals[l].output.x*size,pedals[l].output.y*size);
			}
			context.restore();
			
			context.save();
			context.translate(pedals[p].x*size,pedals[p].y*size);
			context.rotate(pedals[p].rotation* (Math.PI/180));
			context.strokeStyle = colors[i%colors.length];
			context.lineCap = "round";
			if(pedals[p].input.x <= 0 && pedals[p].input.y <= 0 ){
				context.lineTo(pedals[p].width*size ,pedals[p].height*size*3.0/8.0);
			} else {
				context.lineTo(pedals[p].input.x*size,pedals[p].input.y*size);
			}
			context.stroke();
			context.restore();
			lastUsed = p;
			i++;
		}
	}
	context.restore();
	
	
	for(var p in pedals){
		if(pedals[p].active){
			pedals[p].draw();
		}
	}
}

function toCookie(){
	var out = "[";
	for(var p in pedals){
		if(pedals[p].active = true){
			out += "{";
			out += "\"x\":"+ pedals[p].x + ",";
			out += "\"y\":"+ pedals[p].y + ",";		
			out += "\"width\":"+ pedals[p].width + ",";
			out += "\"height\":"+ pedals[p].height + ",";
			out += "\"img\":\""+ pedals[p].image.src+"\",";
			out += "\"name\":\""+ pedals[p].name+"\"";
			out += "},\n";	
		}
	}
	out += "{} ] ";
	$("#CJSON").val(out);
	
	out  = "{";
	out += "\"img\":\""+boards[board].img.src+"\",";
	out += "\"height\":"+boards[board].height+",";
	out += "\"width\":"+boards[board].width;
	out += "}";
	
	$("#CBOARD").val(out);
	
	$("#COOKIE").submit();
}

function toText(){

	var output = "";
	if(order.length > 0){
		output = "<SPAN style='font-size:.75em'>Guitar --> ";
		for(var id in order){
			p = order[id].split("_")[1];  
			output = output + pedals[p].name;
			output = output + " --> ";
		}
		output = output + "Amp </SPAN>";
	} else {
		output = "There are no pedals on your board yet.";
	}
	$('#TEXTOUT').html(output);
	$('#TEXTOUT').dialog('open');
}

function toSvg(){
	var out = "[";
	for(var p in pedals){
		if(pedals[p].active = true){
			out += "{";
			out += "\"x\":"+ pedals[p].x + ",";
			out += "\"y\":"+ pedals[p].y + ",";		
			out += "\"width\":"+ pedals[p].width + ",";
			out += "\"height\":"+ pedals[p].height + ",";
			out += "\"img\":\""+ pedals[p].image.src+"\",";
			out += "\"name\":\""+ pedals[p].name+"\"";
			out += "},\n";	
		}
	}
	out += "{} ] ";
	$("#JSON").val(out);
	
	out  = "{";
	out += "\"img\":\""+boards[board].img.src+"\",";
	out += "\"height\":"+boards[board].height+",";
	out += "\"width\":"+boards[board].width;
	out += "}";
	
	$("#BOARD").val(out);
	
	$("#SVG").submit();
}

function toSave(){
	var out = "[";
	for(var p in pedals){
		if(pedals[p].active = true){
			out += "{";
			out += "\"id\":\""+ pedals[p].pid+"\"";
			out += "\"x\":"+ pedals[p].x + ",";
			out += "\"y\":"+ pedals[p].y + ",";		
			out += "\"width\":"+ pedals[p].width + ",";
			out += "\"height\":"+ pedals[p].height + ",";
			out += "\"rotation\":\""+ pedals[p].rotation + "\",";
			out += "},\n";	
		}
	} 
	out += "{} ] ";
	$("#SAVEJSON").val(out);
	
	out  = "{";
	out += "\"img\":\""+boards[board].img.src+"\",";
	out += "\"height\":"+boards[board].height+",";
	out += "\"width\":"+boards[board].width;
	out += "}";
	
	$("#SAVEBOARD").val(out);
	$("#SAVE").submit();
}
