var P2, mainvid, vidready = false, editmode = false, em=0;
var stretch = 1;

$(function()
{
	BF.P = Raphael($('#megamural')[0]);
	
	var repos =function()
	{
		var m = $('#megamural');
		var off = m.offset(), pos=m.position();
		
		for (var i=0; i<BF.zs.length; i++)
		{
			var p = BF.zs[i].p;
			p.x /= BF.off.w;
			p.y /= BF.off.h;
		}
		m.height($(window).height()-100);
		BF.off = {x:off.left, y:off.top, w:m.width(), h:m.height()};
		$("#controls").css({top:BF.off.h+'px'});
		BF.P.setSize(BF.off.w, BF.off.h);
		//$(BF.P.canvas).css({border:"1px solid red"});
		for (var i=0; i<BF.zs.length; i++)
		{
			var z = BF.zs[i];
			var p = BF.zs[i].p;
			p.x *= BF.off.w;
			p.y *= BF.off.h;
			
			z.attr({x:p.x,y:p.y});
			z.scale(1);
		}
		
		//if (BF.bg != undefined) { BF.bg.attr({width:BF.off.w, height:BF.off.h}); }
		//if (BF.bg != undefined) { BF.bg.attr({width:40, height:20}); }
		var h = $('#homeimg');
		stretch = $(document).width() - 980;
	};
	$(window).resize(repos);
	repos();
	
	$("#overtext").hover(function(e)
		{
			$('#overtext').hide();
		}, function(e)
		{
			$('#overtext').show();
		});
	
	//BF.bg = BF.P.rect(0, 0, BF.off.w, BF.off.h).attr({fill:"blue"});
	BF.mc = BF.P.circle(0,0,BF.cd).attr({stroke:"white", "stroke-width": 2, "stroke-opacity":0.1});
	//BF.mc.insertAfter(BF.bg);
	BF.mc.hide();
	for (var i=0; i<mural.length; i++) BF.createAt(mural[i]);
	$("#megamural").hide();
	
	var uploader = new qq.FileUploader(
		{
		// pass the dom node (ex. $(selector)[0] for jQuery users)
	   element: document.getElementById('file-uploader'),
		// path to server-side upload script
	   action: 'prcv.php',
		allowedExtensions: ['jpg', 'jpeg'],
		onComplete: function(id, fileName, responseJSON)
			{
				if (responseJSON.success)
				{
					BF.freeze  = false;
					debugger;
					BF.createAt({x:BF.tomakeX,y:BF.tomakeY,name:responseJSON.name,ow:responseJSON.owidth,oh:responseJSON.oheight,w:responseJSON.nwidth,h:responseJSON.nheight});
					$("#upload").hide();
					$("#qq-upload-list").html("");
				}
			},
		showMessage: function(message)
			{
				alert(message);
			}
		});
	
	$(document).keydown(function(e)
		{
			if (e.which==69) em=1;
			if (e.which==68 && em==1) em=2;
			if (e.which==84 && em==2)
			{
				editmode=true;
				$("#controls").show();
				$("overtext").css({bottom:'-20px'});
			}
			if (e.which==32 && editmode && !BF.freeze)
			{
				var c = BF.overc;
				if (c == null)
				{
					var pos = $("#megamural").offset();
					
					BF.freeze = true;
					$("#upload").show();
				}
				else
				{
					BF.zedit = c;
					$("#input").show();
					c.toFront();
					c.animate({x:72,y:175,scale:7},500);
					BF.freeze = true;
					$("#fover").val(c.p.over);
					$("#fname").val(c.p.name);
					$("#ftext").val(c.p.text);
					$("#furl").val(c.p.url);
				}
			}
		});
	
	var butts=[];
	for (var i=0; i<3; i++)
	{
		butts.push(button(i));
	}
	var num = function(t) { return parseInt($(t).attr("num"),10); }
	$(".button").hover(
		function()
		{
			$(this).css("color", "#B19361");
			butts[num(this)].attr({fill:"90-black-#4D5A00-black"});
		},
		function()
		{
			$(this).css("color", "#AF9062");
			butts[num(this)].attr({fill:"90-black-#334417-black"});
		});
	$(".button").click(function()
		{
			var n = num(this);
			switch (n)
			{
				case 0:
					{
						$("#home").show();
						$("#video").hide();
						$("#megamural").hide();
						
						var off = $("#homeimg").offset();
						$("#contact").css({"z-index":-1, "opacity":0.4, "top":off.top + $('#homeimg').height() - $('#contact').height() -20});
						$("#contact").show();
						$("#contact").animate({left:-200}, 700, function(){$(this).css("z-index", 1)}).animate({left:10, opacity:0.9}, 700);
						
						$(document).unbind("mousemove")
						$(document).unbind("mouseup");
						//if (vidready) mainvid.pauseVideo();
					}
					break;
				case 1:
					{
						$("#home").hide();
						$("#video").hide();

						$("#megamural").show();
						repos();
						
						BF.stopzoom();
						BF.clearcurrent();
						$(document).mousemove(BF.mag);
						$(document).mouseup( function() { BF.dragging = null; } );
						
						//if (vidready) mainvid.pauseVideo();
					}
					break;
				case 2:
					{
						$("#home").hide();
						$("#megamural").hide();
						$("#video").show();
						$("#contact").hide();
						//if (vidready) mainvid.playVideo();
						$(document).unbind("mousemove")
						$(document).unbind("mouseup");
					}
					break;
			}
		});
});

function onYouTubePlayerReady()
{
	vidready = true;
	mainvid = document.getElementById("vplayer");
	mainvid.playVideo();
}
function button(pos, text)
{
	if (P2 === undefined)
	{
		P2 = Raphael($("#buttons")[0]);
	}
	var home = $("#homeimg").offset();
	var x = pos*275;//$("#homeimg").width() / 3 * pos;
	var y = home.top;
	var w = 275;//$("#homeimg").width() / 3;
	var h = 40;
	var r = P2.rect(x,y,w,h,10).attr({fill:"90-black-#334417-black"});
	
	return r;
}

var count=0;
var d = +new Date;
var editmode = false;
var BF=
{
	md:25, // mid circle distance
	sq:100, // width of indivudal items zoomed out 
	//div:4, // divider from true size of images when zoomed out
	cd:200, // full circle distance
	f:1, // focus factor on mousing into zoom zone
	scaler:1,
	//md:25, // mid circle distance
	//sq:25, // width of indivudal items zoomed out
	div:3, // divider from true size of images when zoomed out
	//cd:150, // full circle distance
	//f:1.5, // focus factor on mousing into zoom zone
	//scaler:8,
	zs:[],
	moves:0,
	processing:false,
	ismag:false,
	freeze:false,
	zedit:null,
	nozoom:false,
	
	mag:function(e)
	{
		if (BF.fcurrent != null)
		{
			var f = BF.fcurrent;
			var c = BF.current;
			var vx = e.pageX - BF.off.x;
			var vy = e.pageY - BF.off.y;
			var px = vx / BF.off.w;
			var py = vy / BF.off.h;
			var dw = c.p.ow - BF.off.w;
			var dh = c.p.oh - BF.off.h;
			var ntx = -(px * dw);
			var nty = -(py * dh);
			//if (ntx + c.p.ow < BF.off.w) ntx = BF.off.w - c.p.ow;
			//if (nty + c.p.oh < BF.off.h) ntx = BF.off.h - c.p.oh;
			var minx = BF.off.w - c.p.ow;
			var maxx = 0;
			var miny = BF.off.h - c.p.oh;
			var maxy = 0;
			if (ntx < minx) ntx = minx;
			if (ntx > maxx) ntx = maxx;
			if (nty < miny) nty = miny;
			if (nty > maxy) nty = maxy;
			//if (nty + c.p.oh > BF.off.h) ntx = BF.off.h - c.p.oh;
			if (dw > 0) f.attr({x: ntx})
			if (dh > 0) f.attr({y: nty})
			return;
		}
		
		if (BF.processing || BF.freeze) return;
		
		if (BF.dragging)
		{
			var pos = $("#megamural").offset();
			//log("{0}, {1}", pos.left, pos.top);
			BF.dragging.p.x = e.pageX - pos.left;
			BF.dragging.p.y = e.pageY - pos.top;
			//BF.dragging.attr({x:BF.dragging., y:e.y});
		}
		
		var p = BF.coords(e);
		if (BF.nozoom || p.x < 0 || p.x > BF.off.w || p.y < 0 || p.y > BF.off.h)
		{
			BF.stopzoom();
			return;
		}
		else BF.mc.show();
		BF.processing = true;
		BF.ismag = true;
		
		BF.tomakeX = e.pageX - BF.off.x;;
		BF.tomakeY = e.pageY - BF.off.y;
		
		// Convert to percentages
		BF.tomakeX /= BF.off.w;
		BF.tomakeY /= BF.off.h;
		
		//logset("{0}",++count);
		window.setTimeout(function()
		{
			BF.mc.attr({cx:p.x,cy:p.y});
			var maxd=1000, closez = null;
			for (var i=0; i<BF.zs.length; i++)
			{
				var z = BF.zs[i];
				var d = (Math.distance(p, z.p));
				var f = BF.f;
				var dx = p.x-z.p.x, dy = p.y-z.p.y;
				var s = 1;
				var ms = BF.scaler;
				var d2 = BF.cd/2;
				if ("text" in z.p)
				{
					z.attr({x:p.x-dx*f,y:p.y-dy*f});
					continue;
				}
				if (d<d2)
				{
					s = ms - (ms-1)*d/d2;
					if (d<maxd) { z.toFront(); closez = z; maxd = d; }
				}
				z.attr({x:p.x-dx*f-BF.sq*s/2,y:p.y-dy*f-BF.sq*s/2});
				z.scale(s,s,z.attrs.x+BF.sq/2,z.attrs.y+BF.sq/2);
			}
			if (closez != null && maxd<BF.sq)
			{
				logset(closez.p.over);
				//closez.attr({opacity:1}); 
			}
			else logset("");
			BF.P.safari();
			BF.processing = false;
		},1);
	},
	
	coords: function(e)
	{
		var p = {x:-BF.off.x, y:-BF.off.y};
		if (!e) e = window.event;
		if (e.pageX || e.pageY) { p.x += e.pageX; p.y += e.pageY; }
		else if (e.clientX || e.clientY)
		{
			p.x += e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
			p.y += e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
		}
		return p;
	},
	
	createAt: function(p)
	{
		var s = BF.sq, c;
		//c = BF.P.rect(p.x - s/2, p.y - s/2, s, s).attr({fill:"blue"});
		
		// Convert to percentage
		p.x *= BF.off.w;
		p.y *= BF.off.h;
		
		if ("text" in p)
		{
			c = BF.P.text(p.x, p.y, p.text).attr({fill:"white"});
		}
		else
		{
			var x = p.x - (p.w/BF.div)/2;
			var y = p.y - (p.h/BF.div)/2;
			var w = p.w / BF.div;
			var h = p.h / BF.div;
			//if (document.all)
			//	c = BF.P.rect(x, y, w, h).attr({fill:"url(upload/thumbs/{0})".format(p.name)});
			//else
				c = BF.P.image("upload/thumbs/{0}".format(p.name), x, y, w, h);
		}
		c.attr({opacity:0.4});
		c.p = p;
		c.mousemove(BF.mag);
		if (document.getElementById("output") != null)
		{	
			$(c.node).mousedown(function(e)
			{
				if (BF.freeze) return;
				if (e.which==1)
				{
					if (editmode)
					{
						BF.dragging = c;
					}
					else
					{
						BF.freeze = true;
						BF.current = c;
						
						var tx, ty, tw, th;
						var aspect = c.p.ow/c.p.oh;
						var mw = $("#megamural").width();
						var mh = $("#megamural").height();
						var showtype = 2;
						
						th = c.p.oh;
						tw = c.p.ow;
						tx = mw / 2 - tw / 2;
						ty = mh / 2 - th / 2;
						
						var f = BF.P.image("upload/{0}".format(c.p.name), tx, ty, tw, th).attr({opacity:0.01});
						for (var i=0; i<BF.zs.length; i++)
						{
							var z = BF.zs[i];
							z.animate({opacity:0}, 500);
						}
						f.animate({opacity:1}, 500);
						BF.mc.hide();
						//$("#overtext").hide();
						$('#overtext').css({bottom:'40px', color:'#ffe', 'text-shadow': '#311 2px 2px 2px'});
						f.toFront();
						f.node.style.cursor="pointer";
						BF.fcurrent = f;
						f.click(BF.clearcurrent);
						//$(document).click(BF.clearcurrent);
					}
					if (e.preventDefault)e.preventDefault();
				}
			});
		};
		
		//c.node.style.cursor="pointer";
		c.node.style.cursor="pointer";
		if ("url" in p)
		{
			c.node.style.cursor="pointer";
			c.click(function()
			{
				if (document.getElementById("output")) window.open(p.url); else window.location.href = p.url;
			});
		}
		c.mouseover(function() { if (BF.freeze) return; c.attr({opacity:1}); BF.overc = c; });
		c.mouseout(function() { if (BF.freeze) return; c.attr({opacity:0.5}); BF.overc = null; });
		c.node.style.antialias = "false";
		BF.zs.push(c);
		return c;
	},
	
	stopzoom: function()
	{
		BF.mc.hide();
		logset("");
		if (BF.ismag)
		{
			for (var i=0; i<BF.zs.length; i++)
			{
				var z = BF.zs[i];
				if ("text" in z.p)
					z.attr({x:z.p.x,y:z.p.y});
				else
				{
					stretch = 1;
					z.attr({x:(z.p.x)-BF.sq/2,y:(z.p.y)-BF.sq/2});
					z.scale(1,1,z.attrs.x+BF.sq/2,z.attrs.y+BF.sq/2);
				}
			}
			BF.ismag = false;
		}
	},
	
	clearcurrent: function()
	{
		if (BF.fcurrent==null) return;
		var f = BF.fcurrent;
		BF.fcurrent = null;
		
		for (var i=0; i<BF.zs.length; i++)
			{
				var z = BF.zs[i];
				z.animate({opacity:0.5}, 500);
			}
		BF.mc.show();
		//$("#overtext").show();
		$('#overtext').css({bottom:'20px', color:'#4D5A00', 'text-shadow': 'none'});
		$(document).unbind("click");
		f.animate({opacity:0.01}, 500, function()
		{
			f.remove();
			BF.freeze = false;
		});
	},
	
	save: function()
	{
		BF.freeze = false;
		$("#input").hide();
		var p = jQuery.extend({}, BF.zedit.p);
		
		p.over =  jQuery("#fover").val();
		//p.name = jQuery("#fname").val();
		//p.text =  jQuery("#ftext").val();
		//p.url =   jQuery("#furl").val();
		
		jQuery("#fover").val("");
		//jQuery("#fname").val("");
		//jQuery("#ftext").val("");
		//jQuery("#furl").val("");
		
		if (p.text == "") delete(p.text);
		if (p.url == "") delete(p.url);
		for (var i=0; i<BF.zs.length; i++)
		{
			if (BF.zs[i] === BF.zedit)
			{
				BF.zs.splice(i, 1);
				BF.zedit.remove();
				break;
			}
		}
		// convert to percentages;
		p.x /= BF.off.w;
		p.y /= BF.off.h;
		BF.createAt(p);
	},
	
	remove: function()
	{
		BF.freeze = false;
		document.getElementById("input").style.display = "none";
		for (var i=0; i<BF.zs.length; i++)
		{
			if (BF.zs[i] === BF.zedit)
			{
				BF.zs.splice(i, 1);
				BF.zedit.remove();
				break;
			}
		}
	},
	
	getJSON: function()
	{
		var output = document.getElementById("output");
		var zs = [];
		for (var i=0; i<BF.zs.length; i++)
		{
			var p = $.extend({}, BF.zs[i].p);
			p.x /= BF.off.w;
			p.y /= BF.off.h;
			zs.push(p);
		}
		return JSON.stringify(zs);
	},
	
	store: function()
	{
		//log(BF.getJSON());
		$.ajax({
			type: 'POST',
			url: "savejson.php",
			data: "data=" + encodeURIComponent(BF.getJSON()),
			success: function(ret)
			{
				//log("Successfully saved.");
				log(ret);
			}
		});
	},
	
	spit: function()
	{
		var output = document.getElementById("output");
		var zs = [];
		for (var i=0; i<BF.zs.length; i++)
		{
			zs.push(BF.zs[i].p);
		}
		var s = "var mural = " + JSON.stringify(zs);
		output.innerHTML = s.escapeHTML();
	}
};


/*** Features ***/
Math.randbetween = function(n1,n2) { return Math.floor(Math.random() * (n2-n1+1)) + n1 };
Math.square = function(x) { return x*x; };
Math.distance = function(p1,p2){ return (Math.sqrt(Math.square(p1.x-p2.x)+Math.square(p1.y-p2.y))); }
String.prototype.format = function()
{
	var pattern = /\{\d+\}/g;
	var args = arguments;
	return this.replace(pattern, function(capture){ return args[capture.match(/\d+/)]; });
};
String.prototype.escapeHTML = function () {return(this.replace(/&/g,'&amp;').replace(/>/g,'&gt;').replace(/</g,'&lt;').replace(/"/g,'&quot;'));};
function log()
{
	var console = document.getElementById('output');
	if (console==null)
	{
		document.body.appendChild(console = document.createElement("div"));
		console.setAttribute("id", "output");
		$("#console").css(
			{
				"color":"lime",
				"background-color":"black",
				"font-family":"consolas",
				"position":"absolute",
				"left":"0px",
				"bottom":"0px",
				"z-index":100,
				"font-size":"8pt"
			});
	}
	var args = Array.prototype.slice.call(arguments);
	if (args[0] == "")
	{
		for (var i=0; i<args.length-1; i++)
		{
			args[0] += "{" + i + "} ";
		}
	}
	var t = args.shift();
	console.innerHTML += "<br>" + String.prototype.format.apply(String(t), args).escapeHTML();
};
function logset()
{
	var args = Array.prototype.slice.call(arguments);
	var t = args.shift();
	var console = document.getElementById('overtext');
	if (console == null)
	{
		console = document.createElement("div");
		console.id = "overtext";
		document.body.appendChild(console);
	}
	console.innerHTML = String.prototype.format.apply(String(t), args).escapeHTML();
};
