var HEAD = document.childNodes[1].firstChild;

var deg2radians = Math.PI * 2 / 360;

var degTest = 0;

var play = "off";

var Mech = {
	webkit: false,
	ringDeg: 0,
	capDeg: 0,
	cogDeg: 0,
	gocDeg: 0,
	speed: 0,
	valveDir: "left",
	puff: false,
	stop: function() {
		Mech.speed = 0;
	
		ringEPos = window.getComputedStyle(Mech.ringE, null).getPropertyValue("-webkit-transform");
		Mech.ringE.style.webkitTransitionTimingFunction = "ease-in";
		setTimeout(
			function() {
				Mech.ring.style.webkitAnimationName = "none";
				Mech.arctic.style.webkitAnimationName = "none";
			}, 
			30000
		);
		Mech.ringE.style.webkitTransform = "rotate(-400deg)";
		//Mech.ring.style.webkitTransform = "rotate("+Mech.getDeg(ringEPos)+"deg)";
	},
	start: function() {
		if (Mech.ring) {
			wtp = window.getComputedStyle(Mech.ring, null).getPropertyValue("-webkit-transition-property");
			if (wtp == "") {
				AnInt = setInterval("Mech.increment()", 1000);
			}
			else { 
				AnInt = setInterval("Mech.increment()", 1000);
				Mech.webkit = true;
			}
			Mech.valveDir = "left";
			Mech.resetSteam();
			//Mech.speed = 1;
			changeSpeed(1);
		}
	},
	increment: function() {
		wks = 3;
		if (Mech.webkit) { wks = 3; }
		else {
			if (Mech.ringDeg > 360) Mech.ringDeg -= 360;
			if (Mech.capDeg < -360) Mech.capDeg += 360;
			if (Mech.cogDeg > 360) Mech.cogDeg -= 360;
			if (Mech.gocDeg < -360) Mech.gocDeg += 360;
		}	
		
		Mech.ringDeg += 0.4 * Mech.speed * wks;
		Mech.capDeg -= 0.4 * Mech.speed * wks;
		Mech.cogDeg += 1.8461538 * Mech.speed * wks;
		Mech.gocDeg -= 1.8461538 * Mech.speed * wks;
		
		cogRad = Mech.cogDeg * deg2radians;
		Mech.prDeg = Math.cos(cogRad) * 15;
		Mech.rodDeg = Math.cos(cogRad) * -15;
		Mech.ecrodDeg = Math.sin(cogRad) * -6.5 - 13.5;
		Mech.glinkDeg = Math.sin(cogRad+125) * 9.9 + 14.4;
		Mech.grodDeg = Math.sin(cogRad+170) * 7 + 23;
		Mech.valveDeg = Math.sin(cogRad+80) * 2 - 10;
		
		Mech.ring.style.MozTransform = "rotate("+Mech.ringDeg+"deg)";
		Mech.arctic.style.MozTransform = "rotate("+Mech.ringDeg+"deg)";
		Mech.cog.style.MozTransform = "rotate("+Mech.cogDeg+"deg)";
		Mech.crank.style.MozTransform = "rotate("+Mech.cogDeg+"deg)";
		Mech.crankpin.style.MozTransform = "rotate("+Mech.gocDeg+"deg)";
		Mech.eccentriccrank.style.MozTransform = "rotate("+Mech.cogDeg+"deg)";
		Mech.eccentricpin.style.MozTransform = "rotate("+Mech.gocDeg+"deg)";
		Mech.rod.style.MozTransform = "rotate("+Mech.rodDeg+"deg)";
		Mech.eccentricrod.style.MozTransform = "rotate("+Mech.ecrodDeg+"deg)";
		Mech.guidelink.style.MozTransform = "rotate("+Mech.glinkDeg+"deg)";
		Mech.guiderod.style.MozTransform = "rotate("+Mech.grodDeg+"deg)";
		Mech.valve.style.MozTransform = "rotate("+Mech.valveDeg+"deg)";
		Mech.pistonrod.style.MozTransform = "rotate("+Mech.prDeg+"deg)";
		
		Mech.ring.style.webkitTransform = "rotate("+Mech.ringDeg+"deg)";
		Mech.arctic.style.webkitTransform = "rotate("+Mech.ringDeg+"deg)";
		Mech.cog.style.webkitTransform = "rotate("+Mech.cogDeg+"deg)";
		Mech.crank.style.webkitTransform = "rotate("+Mech.cogDeg+"deg)";
		Mech.crankpin.style.webkitTransform = "rotate("+Mech.gocDeg+"deg)";
		Mech.eccentriccrank.style.webkitTransform = "rotate("+Mech.cogDeg+"deg)";
		Mech.eccentricpin.style.webkitTransform = "rotate("+Mech.gocDeg+"deg)";
		Mech.rod.style.webkitTransform = "rotate("+Mech.rodDeg+"deg)";
		Mech.eccentricrod.style.webkitTransform = "rotate("+Mech.ecrodDeg+"deg)";
		Mech.guidelink.style.webkitTransform = "rotate("+Mech.glinkDeg+"deg)";
		Mech.guiderod.style.webkitTransform = "rotate("+Mech.grodDeg+"deg)";
		Mech.valve.style.webkitTransform = "rotate("+Mech.valveDeg+"deg)";
		Mech.pistonrod.style.webkitTransform = "rotate("+Mech.prDeg+"deg)";
		
		for (x in Capsule) {
			Capsule[x].div.style.MozTransform = "rotate("+Mech.capDeg+"deg)";
			Capsule[x].div.style.webkitTransform = "rotate("+Mech.capDeg+"deg)";
		}
		
		if (Mech.valveDeg <= -9.8 && Mech.valveDir == "right") {
			Mech.valveDir = "left";
			Mech.puff = false;
		}
		if (Mech.valveDeg >= -10.2 && Mech.valveDir == "left") {
			Mech.valveDir = "right";
			Mech.puff = false;
		}
		if (Mech.valveDeg >= -9.6 && Mech.valveDir == "right" && !Mech.puff) {
			play = "play"; Mech.playSteam();
			Mech.puff = true;
		}
		if (Mech.valveDeg <= -10.4 && Mech.valveDir == "left" && !Mech.puff) {
			play = "play"; Mech.playSteam();
			Mech.puff = true;
		}
		if (Mech.valveDeg >= -8.2 && Mech.valveDir == "right" && Mech.puff) {
			play = "stop"; Mech.resetSteam();
		}
		if (Mech.valveDeg <= -11.8 && Mech.valveDir == "left" && Mech.puff) {
			play = "stop"; Mech.resetSteam();
		}
		
		//Mech.steamSound.SetVolume(Math.round(Math.abs(Mech.valveDeg + 10) * 18));
		
		//$('cylinder').innerHTML = Mech.valveDeg+"<br/>"+Mech.valveDir+"<br/>"+play;
			
		if (Mech.ring.filters) {
			ringRad = Mech.ringDeg * deg2radians;
			cogRad = Mech.cogDeg * deg2radians;
			costhetaR = Math.cos(ringRad);
			costhetaC = Math.cos(cogRad);
			sinthetaC = Math.sin(cogRad);
			
			Mech.ring.filters.item(0).M11 = costhetaR;
			Mech.ring.filters.item(0).M12 = -sinthetaR;
			Mech.ring.filters.item(0).M21 = sinthetaR;
			Mech.ring.filters.item(0).M22 = costhetaR;
			
			Mech.cog.filters.item(0).M11 = costhetaC;
			Mech.cog.filters.item(0).M12 = -sinthetaC;
			Mech.cog.filters.item(0).M21 = sinthetaC;
			Mech.cog.filters.item(0).M22 = costhetaC;
			
			Mech.ring.style.pixelTop = Mech.ringTop - (Mech.ring.offsetHeight - Mech.ringHeight) / 2;
			Mech.ring.style.pixelLeft = Mech.ringLeft - (Mech.ring.offsetWidth - Mech.ringWidth) / 2;
			
			Mech.cog.style.pixelTop = Mech.cogTop - (Mech.cog.offsetHeight - Mech.cogHeight) / 2;
			Mech.cog.style.pixelLeft = Mech.cogLeft - (Mech.cog.offsetWidth - Mech.cogWidth) / 2;
		}
	},
	playSteam: function() {
		for (x in Steam) {
			Steam[x].div.style.webkitAnimationName = "steamExhaust";
			/*Steam[x].div.style.opacity = 0;
			Steam[x].div.style.webkitTransitionDuration = 5/Math.abs(Mech.speed) + "s";
			Steam[x].div.style.webkitTransform = "translateY(200px) scale(1,2) rotate("+(x*50)+"deg)";
			Steam[x].div.style.webkitTransitionDelay = 1 * x / Math.abs(Mech.speed) + "s";
			setTimeout("Mech.resetSteam2("+x+")", 500/Math.abs(Mech.speed) + 100 * x / Math.abs(Mech.speed));*/
		}
	},
	resetSteam2: function(x) {
		/*Steam[x].div.style.opacity = 1;
		Steam[x].div.style.webkitTransitionDuration = 0.005/Math.abs(Mech.speed)+"s";
		Steam[x].div.style.webkitTransform = "translateY(0px) scale(0.05,0.2) rotate(0deg)";*/
	},
	resetSteam: function() {
		for (x in Steam) {
			Steam[x].div.style.webkitAnimationName = "none";
			/*Steam[x].div.style.opacity = 1;
			Steam[x].div.style.webkitTransitionDuration = "0s";
			Steam[x].div.style.webkitTransform = "translateY(0px) scale(0.05,0.2) rotate(0deg)";*/
		}
	},
	getDeg: function(matString) {
		cosStart = matString.indexOf("(") + 1;
		cosEnd = matString.indexOf(",");
		cos = matString.substring(cosStart, cosEnd);
		return Math.acos(cos) / deg2radians;
	}
}

var Capsule = {};
var Steam = {};

function initRing() {
	Mech.ringE = $('ringStart');
	Mech.ring = $('ring');
	Mech.arctic = $('arctic');
	Mech.cogE = $('cogEase');
	Mech.cog = $('cog');
	Mech.crank = $('crank');
	Mech.crankpin = $('crankpin');
	Mech.eccentriccrank = $('eccentriccrank');
	Mech.eccentricpin = $('eccentricpin');
	Mech.eccentricrod = $('eccentricrod');
	Mech.guidelink = $('guidelink');
	Mech.guiderod = $('guiderod');
	Mech.valve = $('valve');
	Mech.pistonrod = $('pistonrod');
	Mech.rod = $('rod');
	Mech.ringWidth = $('ring').offsetWidth;
	Mech.ringHeight = $('ring').offsetHeight;
	Mech.ringTop = $('ring').offsetTop;
	Mech.ringLeft = $('ring').offsetLeft;
	Mech.cogWidth = $('cog').offsetWidth;
	Mech.cogHeight = $('cog').offsetHeight;
	Mech.cogTop = $('cog').offsetTop;
	Mech.cogLeft = $('cog').offsetLeft;
	capsules = $$("div.capsule");
	caplen = capsules.length;
	for (i = 0; i < caplen; i++)
	{
		Capsule[capsules[i].id] = new capsuleObject(capsules[i], i, caplen);
	}
	steam = $$("div.steamExhaust");
	stelen = steam.length;
	for (i = 0; i < stelen; i++)
	{
		Steam[i] = new steamObject(steam[i]);
	}
	
	Mech.ring.observe('webkitAnimationEnd', function(e) { console.log('animation end'); });
	
	//Mech.steamSound = $('steamSound');
	//Mech.steamSound.SetVolume(0);
	Mech.start();
	
	overlayBox.div = $('overlayBox');
	overlayBox.closeButton = $('overlayCloseButton');
	overlayBox.closeButton.observe('click', overlayBox.close);
	
	if (window.location.hash)
	{
		var wlHash = window.location.hash.match(/#.*/);
		var hashApp = wlHash.toString().substring(1);
		var initApp = Capsule[hashApp+"Capsule"] || null;
		if (initApp) { initApp.clickzone.fire('cnlt:pageinit'); }
		if (hashApp == "admin") {
			var stall = { div: $('SCCStall'), rad: 5, width: 135 };
			stall.div.observe('click', overlayBox.open.bind(stall));
			stall.div.observe('cnlt:pageinit', overlayBox.open.bind(stall));
			stall.div.fire('cnlt:pageinit');
			new Ajax.Request("panels/log_control.php", {
				onSuccess: function(transport) {
					adminjs = document.createElement('script');
					adminjs.type = "text/javascript";
					adminjs.src = "js/admin.js";
					HEAD.appendChild(adminjs);
				}
			} );
		}
	}
}

capColors = ["red", "orange", "yellow", "green", "blue", "purple"];
function capsuleObject(element, index, count) {
	this.color = capColors[Math.floor(Math.random() * capColors.length)];
	dist = 363;
	armDist = 317;
	radius = Math.round(element.parentNode.offsetWidth / 2);
	this.point = 360 / count * index;
	this.rad = this.point * deg2radians;
	this.sin = Math.sin(this.rad);
	this.cos = Math.cos(this.rad);
	this.div = element;
	this.width = this.div.offsetWidth;
	this.div.style.left = Math.round(this.sin * dist) + radius - this.width / 2 + "px";
	this.div.style.bottom = Math.round(this.cos * dist) + radius - this.width / 2 + "px";
	this.div.style.backgroundImage = "url(http://www.steveferrisworld.com/images/heads/01.png)";
	
	this.cap = document.createElement('div');
	this.cap.addClassName('capCar');
	this.cap.style.backgroundImage = "url(http://www.steveferrisworld.com/images/capsule."+this.color+".png)";
	this.div.appendChild(this.cap);
	
	appNameEnd = this.div.id.indexOf("Capsule");
	this.app = {
		name: this.div.id.substring(0, appNameEnd)
	}
	
	this.init = function() {
		new Ajax.Request(this.app.name+"/index.php",
		{
			parameters: { index: "1" },
			onSuccess: function(transport)
			{
				this.app.js = document.createElement('script');
				this.app.js.type = "text/javascript";
				this.app.js.src = this.app.name+"/js/app.js";
				HEAD.appendChild(this.app.js);
				
				this.app.trt = transport.responseText;
				window.location.hash = this.app.name;
			}.bind(this)
		} );
	}.bind(this)
	
	this.arm = document.createElement('div');
	this.arm.addClassName('capArm');
	element.parentNode.appendChild(this.arm);
	this.armW = this.arm.offsetWidth;
	this.armL = Math.round(this.sin * armDist + radius - this.armW / 2);
	this.armT = Math.round(this.cos * -armDist + radius - this.armW / 2);
	this.arm.style.left = this.armL + "px";
	this.arm.style.top = this.armT + "px";
	this.arm.style.webkitTransform = 'rotate('+this.point+'deg)';
	this.arm.style.MozTransform = 'rotate('+this.point+'deg)';
	
	this.label = document.createElement('img');
	this.label.setAttribute("id", this.app.name+"Label");
	this.label.addClassName('capLabel');
	this.label.src = "http://www.steveferrisworld.com/"+this.app.name+"/label.png";
	this.label.alt = this.app.name;
	this.arm.appendChild(this.label);
	
	this.clickzone = document.createElement('div');
	this.clickzone.addClassName('capClickZone');
	this.clickzone.observe('click', overlayBox.open.bind(this));
	this.clickzone.observe('click', this.init);
	this.clickzone.observe('cnlt:pageinit', overlayBox.open.bind(this));
	this.clickzone.observe('cnlt:pageinit', this.init);
	this.clickzone.observe('mouseover', function() { 
		this.div.style.backgroundPosition = "90px 40px";
		this.div.style.webkitBackgroundSize = "40px 54px";
	}.bind(this));
	this.clickzone.observe('mouseout', function() { 
		this.div.style.backgroundPosition = "40px 90px";
		this.div.style.webkitBackgroundSize = "4px 5px";
	}.bind(this));
		
	this.arm.appendChild(this.clickzone);
	//this.label.style.left = Math.round((this.div.offsetWidth / 2) - (this.label.offsetWidth / 2)) + "px";
}

var overlayBox = {
	tslX: 0,
	tslY: 0,
	open: function(event) {
		overlayBox.source = this;
		olBsin = Math.sin(Mech.ringDeg * deg2radians + this.rad);
		olBcos = Math.cos(Mech.ringDeg * deg2radians + this.rad);
		olBL = Mech.ring.offsetLeft + this.div.offsetWidth/2 - overlayBox.div.offsetWidth/2
			+ Math.round(olBsin * dist) + radius - this.width/2;
		olBT = Mech.ring.offsetTop + this.div.offsetHeight/2 - overlayBox.div.offsetHeight/2
			+ Math.round(olBcos * -dist) + radius - this.width/2;
		overlayBox.div.style.webkitTransitionDuration = "2s";
		overlayBox.div.style.MozTransitionDuration = "2s";
		overlayBox.div.style.left = olBL + "px";
		overlayBox.div.style.top = olBT + "px";
		overlayBox.tslX = olBsin*-dist;
		overlayBox.tslY = olBcos*dist;
		overlayBox.div.style.webkitTransform = "translate("+overlayBox.tslX+"px,"+overlayBox.tslY+"px)";
		overlayBox.div.style.MozTransform = "translate("+overlayBox.tslX+"px,"+overlayBox.tslY+"px)";
		overlayBox.div.style.opacity = "1";
	},
	close: function(event) {
		overlayBox.div.style.webkitTransitionDuration = "0.5s";
		overlayBox.div.style.webkitTransform = 
			"translate("+overlayBox.tslX+"px,"+overlayBox.tslY+"px) scale(0.001)";
		overlayBox.div.style.MozTransitionDuration = "0.5s";
		overlayBox.div.style.MozTransform = 
			"translate("+overlayBox.tslX+"px,"+overlayBox.tslY+"px) scale(0.001)";
		overlayBox.div.style.opacity = "0.5";
		setTimeout(function() {
			overlayBox.div.style.webkitTransitionDuration = "0s";
			overlayBox.div.style.webkitTransform = "translate(0,0) scale(0.001)";
			overlayBox.div.style.MozTransitionDuration = "0s";
			overlayBox.div.style.MozTransform = "translate(0,0) scale(0.001)";
		}, 500);
		window.location.hash = "";
	}
}
		

function steamObject(element) {
	this.div = element;
	this.pos = "a";
}

function changeSpeed(newSpeed)
{
	difSpeed = newSpeed - Mech.speed;
	incs = Math.abs(difSpeed * 100);
	initTime = 500 - Mech.speed * 100;
	initSpeedStep = Mech.speed + difSpeed / incs;
	setTimeout("incSpeed("+initSpeedStep+", "+newSpeed+", "+incs+")", initTime);
}

function incSpeed(speed, newSpeed, incs)
{
	if (speed >= Mech.speed && speed >= newSpeed) {
		Mech.speed = speed;
	}
	else if (speed <= Mech.speed && speed <= newSpeed) {
		Mech.speed = speed;
	}
	else {
		difSpeed = newSpeed - Mech.speed;
		incs--;
		Mech.speed = speed;
		nextSpeedStep = Mech.speed + difSpeed / incs;
		nextTime = 500 - Mech.speed * 100;
		setTimeout("incSpeed("+nextSpeedStep+", "+newSpeed+", "+incs+")", nextTime);
	}
}

	
	