/**
 * Copyright (C) 2010-2011 Graham Breach
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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 Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * jQuery.tagcanvas 1.6.1
 * For more information, please contact <graham@goat1000.com>
 */
(function($) {
Point3D = function(x,y,z) { this.x = x; this.y = y; this.z = z; };
RotX = function(p1,t) {
	var s = Math.sin(t), c = Math.cos(t); 
	return new Point3D(p1.x, (p1.y * c) + (p1.z * s), (p1.y * -s) + (p1.z * c));
};
RotY = function(p1,t) {
	var s = Math.sin(t), c = Math.cos(t); 
	return new Point3D((p1.x * c) + (p1.z * -s), p1.y, (p1.x * s) + (p1.z * c));
};
RotZ = function(p1,t) {
	var s = Math.sin(t), c = Math.cos(t); 
	return new Point3D((p1.x * c) + (p1.y * s), (p1.x * -s) + (p1.y * c),
		p1.z);
};
Project = function(tc,p1,w,h,fov,asp) {
	var yn, xn, zn;
	yn = (p1.y  * tc.z1) / (tc.z1 + tc.z2 + p1.z);
	xn = (p1.x  * tc.z1) / (tc.z1 + tc.z2 + p1.z);
	zn = tc.z2 + p1.z;
	return new Point3D(xn, yn, zn);
};
function TagCanvas() {
	this.Draw = function() {
		var cv = this.canvas, max_sc = 0, x1, y1, c, a, i;
		c = cv.getContext('2d');
		c.setTransform(1,0,0,1,0,0);
		c.clearRect(0,0,cv.width,cv.height);
		x1 = cv.width / 2;
		y1 = cv.height / 2;
		this.active = null;
		for(i = 0; i < this.taglist.length; ++i)
			this.taglist[i].Calc(this.yaw, this.pitch);
		this.taglist = this.taglist.sort(function(a,b) { return a.sc-b.sc;});
		for(i = 0; i < this.taglist.length; ++i)
		{
			a = this.taglist[i].Draw(c, x1, y1);
			if(a && a.sc > max_sc)
			{
				this.active = a;
				this.active.index = i;
				max_sc = a.sc;
			}
		}
		if(this.freezeActive && this.active)
			this.yaw = this.pitch = 0;
		else
			this.Animate(cv.width, cv.height);
		if(this.active)
			this.active.Draw(c);
	};
	this.Animate = function(w,h) {
		if(this.mx >= 0 && this.my >= 0 &&
				this.mx < w && this.my < h)
		{
			this.yaw = (this.maxSpeed * 2 * this.mx / w) - this.maxSpeed;
			this.pitch = -((this.maxSpeed * 2 * this.my / h) - this.maxSpeed);
			if(this.reverse)
			{
				this.yaw = -this.yaw;
				this.pitch = -this.pitch;
			}
			this.initial = null;
		}
		else if(!this.initial)
		{
			var ay = Math.abs(this.yaw), ap = Math.abs(this.pitch);
			if(ay > this.minSpeed)
				this.yaw = ay > this.z0 ? this.yaw * this.decel : 0.0;
			if(ap > this.minSpeed)
				this.pitch = ap > this.z0 ? this.pitch * this.decel : 0.0;
		}
	};
	this.Clicked = function(e) {
		try {
			if(this.active && this.taglist[this.active.index]) 
				this.taglist[this.active.index].Clicked(e);
		} catch(ex) {
			//window.alert(ex);
		}
	};
	this.Outline = function(tc) {
		this.tc = tc;
		this.ts = new Date();
		this.Update = function(x,y,w,h,sc) {
			this.x = sc * (x - this.tc.outlineOffset);
			this.y = sc * (y - this.tc.outlineOffset);
			this.w = sc * (w + this.tc.outlineOffset * 2);
			this.h = sc * (h + this.tc.outlineOffset * 2);
			this.sc = sc;
		};
		this.Draw = function(c) {
			var diff = new Date() - this.ts;
			c.setTransform(1,0,0,1,0,0);
			c.strokeStyle = this.tc.outlineColour;
			c.lineWidth = this.tc.outlineThickness;
			c.shadowBlur = c.shadowOffsetX = c.shadowOffsetY = 0;
			if(this.tc.pulsateTo < 1.0)
				c.globalAlpha = this.tc.pulsateTo + ((1.0 - this.tc.pulsateTo) * 
					(0.5 + (Math.cos(2 * Math.PI * diff / (1000 * this.tc.pulsateTime)) / 2.0)));
			else
				c.globalAlpha = 1.0;
			c.strokeRect(this.x, this.y, this.w, this.h);
		};
		this.Active = function(c,x,y) {
			return (x >= this.x && y >= this.y &&
				x <= this.x + this.w && y <= this.y + this.h);
		};
		this.Update(0,0,0,0,1);
	};
	this.Tag = function(tc,name,a,v,w,h) {
		this.tc = tc;
		this.image = name.src ? name : null;
		this.name = name.src ? '' : name;
		this.a = a;
		this.p3d = new Point3D;
		this.p3d.x = v[0] * tc.radius * 1.1;
		this.p3d.y = v[1] * tc.radius * 1.1;
		this.p3d.z = v[2] * tc.radius * 1.1;
		this.x = 0;
		this.y = 0;
		this.w = w;
		this.h = h;
		this.colour = tc.textColour;
		this.weight = 1;
		this.weighted = !tc.weight;
		if(!this.image) {
			if(tc.weight) {
				var wt = 1, p;
				if(document.defaultView && document.defaultView.getComputedStyle) {
					p = document.defaultView.getComputedStyle(a,null).getPropertyValue('font-size');
					wt = p.replace('px','') * 1.0;
				} else {
					tc.weight = false;
				}
				if(wt > tc.max_weight)
					tc.max_weight = wt;
				if(wt < tc.min_weight)
					tc.min_weight = wt;
				this.weight = wt;
			}
			this.textHeight = tc.textHeight;
			this.extents = TagCanvas.FindTextBoundingBox(this.name, this.tc.textFont, this.textHeight);
			if(this.extents)
				this.h = this.extents.max.y;
		}
		this.sc = 1;
		this.alpha = 1;
		this.outline = new tc.Outline(tc);

		this.Weight = function(c,t) {
			var m1, m2, g, i;
			if(t.weightMode == 'colour' || t.weightMode == 'both') {
				m1 = t.canvas.height * (1 + t.max_weight - t.min_weight);
				m2 = t.canvas.height * (1 + this.weight - t.min_weight);
				g = c.createLinearGradient(0, m2 - m1, 0, m2);
				for(i in t.weightGradient) {
					g.addColorStop(i, t.weightGradient[i]);
				}
				this.colour = g;
			}
			if(t.weightMode == 'size' || t.weightMode == 'both') {
				this.textHeight = this.weight * t.weightSize;
			}
			this.extents = TagCanvas.FindTextBoundingBox(this.name, t.textFont, this.textHeight);
			if(this.extents)
				this.h = this.extents.max.y;
			this.weighted = true;
		};
		this.Draw = function(c,xoff,yoff) {
			var t = this.tc, x1, y1;
			if(!this.image && t.weight && !this.weighted)
				this.Weight(c,t);

			c.globalAlpha = this.alpha;
			c.setTransform(this.sc,0,0,this.sc,0,0);
			xoff = xoff / this.sc;
			yoff = yoff / this.sc;
			c.textBaseline = 'top';
			c.fillStyle = this.colour;
			if(t.shadowBlur || t.shadowOffset[0] || t.shadowOffset[1]) {
				c.shadowColor = t.shadow;
				c.shadowColor = TagCanvas.SetAlpha(c.shadowColor, this.alpha);
				c.shadowBlur = t.shadowBlur;
				c.shadowOffsetX = t.shadowOffset[0];
				c.shadowOffsetY = t.shadowOffset[1];
			}
			c.font = this.textHeight + 'px ' + t.textFont;
			if(this.image) {
				this.w1 = this.w * this.sc;
				this.h1 = this.h * this.sc;
			} else {
				if(!this.w1)
					this.w1 = c.measureText(this.name).width + 2;
				if(this.extents)
					this.h1 = this.extents.max.y + this.extents.min.y;
				else
					this.h1 = this.h;
			}
			x1 = xoff, y1 = yoff;
			xoff = xoff - (this.w1 / 2);
			yoff = yoff - (this.h1 / 2);

			if(this.image)
				c.drawImage(this.image, xoff + this.x, yoff + this.y,
					this.image.width * this.sc, this.image.height * this.sc);	
			else
				c.fillText(this.name, xoff + this.x + 1, yoff + this.y + 1, this.w1 - 2);
			this.outline.Update(x1 + this.x - this.w1/2, y1 + this.y - this.h1/2, this.w1, this.h1, this.sc);
			if(this.outline.Active(c, t.mx, t.my))
				return this.outline;
			return null;
		};
		this.Calc = function(yaw,pitch) {
			var pp = RotY(this.p3d,yaw);
			this.p3d = RotX(pp,pitch);

			pp = Project(this.tc, this.p3d, this.w, this.h, Math.PI / 4, 20);
			this.x = pp.x;
			this.y = pp.y;
			this.sc = (this.tc.z1 + this.tc.z2 - pp.z) / this.tc.z2;
			this.alpha = Math.min(1.0,this.tc.minBrightness + 1 -
				((pp.z - this.tc.z2 + this.tc.radius) / (2 * this.tc.radius)));
			if(this.alpha > 1.0)
				console.log(this.alpha);
		};
		this.Clicked = function(e) {
			if(this.a.target != '' && this.a.target != '_self') {
				if(self.frames[this.a.target])
					self.frames[this.a.target] = this.a.href;
				else if(top.frames[this.a.target])
					top.frames[this.a.target] = this.a.href;
				else
					window.open(this.a.href, this.a.target);
				return;
			}
			if(this.a.fireEvent) {
				if(!this.a.fireEvent('onclick'))
					return;
			} else {
				var evt = document.createEvent('MouseEvents');
				evt.initMouseEvent('click', true, true, window,
						0, 0, 0, 0, 0, false, false, false, false, 0, null);
				if(!this.a.dispatchEvent(evt))
					return;
			}
			document.location = this.a.href;
		};
	};
	this.PointsOnSphere = function(n) {
		var i, y, r, phi, pts = [], inc = Math.PI * (3-Math.sqrt(5)), off = 2/n;
		for(i = 0; i < n; ++i) {
			y = i * off - 1 + (off / 2);
			r = Math.sqrt(1 - y*y);
			phi = i * inc;
			pts.push([Math.cos(phi)*r, y, Math.sin(phi)*r]);
		}
		return pts;
	};
	this.AddImage = function(i,t,tl) {
		if(i.complete) {
			t.w = i.width;
			t.h = i.height;
			tl.push(t);
		} else {
			jQuery(i).bind('load',function() {
				t.w = this.width;
				t.h = this.height;
				tl.push(t);
			});
		}
	};

	var i, opts = {
	mx : -1, my : -1,
	cx : 0, cy : 0,
	z1 : 20000, z2 : 20000, z0 : 0.0002,
	freezeActive : false,
	pulsateTo : 1.0,
	pulsateTime : 3,
	reverse : false,
	depth : 0.5,
	maxSpeed : 0.05,
	minSpeed : 0.0,
	decel : 0.95,
	initial : null,
	hideTags: true,
	minBrightness : 0.1,
	outlineColour : '#ffff99',
	outlineThickness : 2,
	outlineOffset : 5,
	textColour : '#ff99ff',
	textHeight : 15,
	textFont : 'Helvetica, Arial, sans-serif',
	shadow: '#000',
	shadowBlur: 0,
	shadowOffset: [0,0],
	zoom: 1.0,
	weight: false,
	weightMode: 'size',
	weightSize: 1.0,
	weightGradient: {0:'#f00', 0.33:'#ff0', 0.66:'#0f0', 1:'#00f'}
	};
	for(i in opts)
		this[i] = opts[i];
	this.max_weight = 0;
	this.min_weight = 200;
};
TagCanvas.MouseMove = function(e) {
	var i, tc, dd = document.documentElement;
	for(i in TagCanvas.tc) {
		tc = TagCanvas.tc[i]
		if(e.pageX) {
			tc.mx = e.pageX - tc.cx;
			tc.my = e.pageY - tc.cy;
		} else {
			tc.mx = e.clientX + (dd.scrollLeft ? 
				dd.scrollLeft : document.body.scrollLeft)
				- tc.cx;
			tc.my = e.clientY + (dd.scrollTop ? 
				dd.scrollTop : document.body.scrollTop)
				- tc.cy;
		}
	}
};
TagCanvas.MouseClick = function(e) {
	var t = TagCanvas, cb = document.addEventListener ? 0 : 1,
		tg = e.target ? e.target.id : e.srcElement.parentNode.id;
	if(e.button == cb && t.tc[tg]) {
		t.MouseMove(e);
		t.tc[tg].Clicked(e);
	}
};
TagCanvas.DrawCanvas = function()
{
	var t = TagCanvas, i;
	for(i in t.tc)
		t.tc[i].Draw();
};
TagCanvas.tc = {};
TagCanvas.SetAlpha = function(c,a) {
	var d = c, p1, p2;
	a = new Number(a).toPrecision(3);
	if(c[0] == '#') {
		if(c.length == 4)
			c = '#' + c[1] + c[1] + c[2] + c[2] + c[3] + c[3];
		d = 'rgba(' + parseInt(c.substr(1,2),16) + ',' +
			parseInt(c.substr(3,2),16) + ',' +
			parseInt(c.substr(5,2),16) + ',' + a + ')';
	} else if(c.substr(0,4) == 'rgb(' || c.substr(0,4) == 'hsl(') {
		d = (c.replace('(','a(').replace(')', ',' + a + ')'));
	} else if(c.substr(0,5) == 'rgba(' || c.substr(0,5) == 'hsla(') {
		p1 = c.lastIndexOf(',') + 1, p2 = c.indexOf(')');
		a *= parseFloat(c.substring(p1,p2));
		d = c.substr(0,p1) + a.toPrecision(3) + ')';
	} else {
		d = c; // give up!
	}
	return d;
};
TagCanvas.FindTextBoundingBox = function(s,f,ht)
{
	// if using excanvas, give up now
	if(window.G_vmlCanvasManager)
		return null;
	var cv = document.createElement('canvas'), c, w, h, idata, w1, h1, x, y, i, ex;
	cv.width = w = parseInt(s.length * ht);
	cv.height = h = parseInt(ht * 2);
	c = cv.getContext('2d');
	c.fillStyle = '#000';
	c.fillRect(0,0,w,h);
	c.font = f;
	c.textHeight = ht;
	c.textBaseline = 'top';
	c.fillStyle = '#fff';
	c.font = ht + 'px ' + f;
	c.fillText(s, 0, 0);

	idata = c.getImageData(0,0,w,h);
	w1 = idata.width; h1 = idata.height;
	ex = {
		min: { x: w1, y: h1 },
		max: { x: -1, y: -1 }
	};
	for(y = 0; y < h1; ++y) {
		for(x = 0; x < w1; ++x) {
			i = (y * w1 + x) * 4;
			if(idata.data[i+1] > 0) {
				if(x < ex.min.x) ex.min.x = x;
				if(x > ex.max.x) ex.max.x = x;
				if(y < ex.min.y) ex.min.y = y;
				if(y > ex.max.y) ex.max.y = y;
			}
		}
	}
	// device pixels might not be css pixels
	if(w1 != w) {
		ex.min.x *= (w / w1);
		ex.max.x *= (w / w1);
	}
	if(h1 != h) {
		ex.min.y *= (w / h1);
		ex.max.y *= (w / h1);
	}

	cv = null;
	return ex;
};


jQuery.fn.tagcanvas = function(options,lctr) {
	var links, ctr = lctr ? jQuery('#'+lctr) : this;
	if(document.all && !lctr) return false; // IE must have external list
	links = ctr.find('a');
	if(typeof(window.G_vmlCanvasManager) != 'undefined')
		this.each(function() { $(this)[0] = window.G_vmlCanvasManager.initElement($(this)[0]); });

	if(!links.length || !this[0].getContext || !this[0].getContext('2d').fillText)
		return false;

	this.each(function() {
		var i, vl, im, ii, tag, jqt, o = $(this).offset();

		// if using internal links, get only the links for this canvas
		if(!lctr)
			links = $(this).find('a');
			
		jqt = new TagCanvas;
		for(i in options)
			jqt[i] = options[i];

		jqt.z1 = (19800 / (Math.exp(jqt.depth) * (1-1/Math.E))) +
			20000 - 19800 / (1-(1/Math.E));
		jqt.z2 = jqt.z1 * (1/jqt.zoom);

		jqt.radius = (this.height > this.width ? this.width : this.height)
			* 0.33 * (jqt.z2 + jqt.z1) / (jqt.z1);
		jqt.taglist = [];

		vl = jqt.PointsOnSphere(links.length);
		for(i = 0; i < links.length; ++i) {
			im = links[i].getElementsByTagName('img');
			if(im.length) {
				ii = new Image;
				ii.src = im[0].src;
				tag = new jqt.Tag(jqt,ii, links[i], vl[i], 1, 1);
				jqt.AddImage(ii,tag,jqt.taglist);
			} else {
				jqt.taglist.push(new jqt.Tag(jqt,links[i].innerText ? links[i].innerText :
					links[i].textContent, links[i],
					vl[i], 2, jqt.textHeight + 2));
			}
		}

		jqt.yaw = jqt.initial ? jqt.initial[0] * jqt.maxSpeed : 0;
		jqt.pitch = jqt.initial ? jqt.initial[1] * jqt.maxSpeed : 0;
		jqt.cx = o.left;
		jqt.cy = o.top;
		jqt.canvas = $(this)[0];
		TagCanvas.tc[$(this)[0].id] = jqt;
		if(!TagCanvas.started) {
			jQuery(document).bind('mousemove', TagCanvas.MouseMove);
			jQuery(document).bind('mouseout', TagCanvas.MouseMove);
			jQuery(document).bind('mouseup', TagCanvas.MouseClick);
			TagCanvas.started = setInterval(function() { TagCanvas.DrawCanvas(); }, 10);
		}
		if(lctr && jqt.hideTags)
			ctr.hide();
	});
	return true;
};
})(jQuery);

