var hstr = '#';
var hdig = "0123456789abcdef";
function fader(cend, iter, time) {
	var background = document.getElementById('body');
	var rgb = document.defaultView.getComputedStyle(background, '').getPropertyValue("background-color");
	var cbeg = convertRGB(rgb);
	var rbeg = parseInt((cutHex(cbeg)).substring(0,2),16);
	var gbeg = parseInt((cutHex(cbeg)).substring(2,4),16);
	var bbeg = parseInt((cutHex(cbeg)).substring(4,6),16);
	var rend = parseInt((cutHex(cend)).substring(0,2),16);
	var gend = parseInt((cutHex(cend)).substring(2,4),16);
	var bend = parseInt((cutHex(cend)).substring(4,6),16);
	function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
	
	var colors = [];
	for ( i = 1, r = rbeg, g = gbeg, b = bbeg;
		i <= iter;
		r = Math.round(rbeg + i * ((rend - rbeg) / (iter-1))),
		g = Math.round(gbeg + i * ((gend - gbeg) / (iter-1))),
		b = Math.round(bbeg + i * ((bend - bbeg) / (iter-1))), i++ )	 {
		hstr = '#' + hdig.charAt(Math.floor(r/16)) + hdig.charAt(r%16) + hdig.charAt(Math.floor(g/16)) + hdig.charAt(g%16) + hdig.charAt(Math.floor(b/16)) + hdig.charAt(b%16);
		colors.push(hstr);
	}
	
	j = '0';
	var color = setInterval(
	function() {
		if (++j < colors.length) {
			document.getElementById('body').style.backgroundColor = colors[j];
		} else {
			document.getElementById('body').style.backgroundColor = cend;
			clearInterval(color);
		}
	}, time);
}
function convertRGB(z) {
	var newfcS = "", splitter = "";
	splitter = z.split(",");
	splitter[0] = parseInt(splitter[0].substring(4, splitter[0].length));
	splitter[1] = parseInt(splitter[1]);
	splitter[2] = parseInt(splitter[2].substring(0, splitter[2].length-1));
	for (var q = 0; q < 3; q++) {
		splitter[q] = splitter[q].toString(16);
		if (splitter[q].length == 1) splitter[q] = "0" + splitter[q];
		newfcS += splitter[q];
	}
	return newfcS;
}
function init() {
	var img1 = new Image();
	img1.src = '/images/appzapper.png';
	var img2 = new Image();
	img2.src = '/images/menuet.png';
	
	var offset = comp - server;
	
	var now = new Date();
	var diff = ((end - now) + offset);
	
	if(diff < '0') { 
		inProgress();
	} else {
		countdown();
	}
}
function countdown() {	
	var countdown = setInterval(
	function() {
		var offset = comp - server;
	
		var now = new Date();
		var diff = ((end - now) + offset);
		
		if(diff < '0') { diff = '0'; }
		
		var minutes = Math.floor(diff / 60000);
		var seconds = Math.floor((diff / 1000) - (minutes * 60));
		var msec	= Math.floor((diff / 10) - (seconds * 100) - (minutes * 6000));
		if(seconds < 10) { seconds = '0' + seconds; }
		if(msec < 10) { msec = '0' + msec; }
		
		if((minutes == '0') && (seconds == '00')) {
			document.getElementById("timer_time").innerHTML = "0:00:00";
			clearInterval(countdown);
			fade('timer', 1.0, 0, 50, null);
			fader('#F9872A', '25', '50');
			
			setTimeout(function() { 
				fade('icons', 0, 1.0, 50, function() {
					setTimeout(function() { 
						var r = 0;
						var countdowndos = setInterval(function() {
								if (++r < 21) {
									document.getElementById('counterdos').innerHTML = (20 - r);
									document.getElementById('time_hold').innerHTML = r;
								} else {
									if(!document.getElementById('clicked')) {
										clickApp(null);
									}
									clearInterval(countdowndos);
								}
							}, 1000);
					}, 750);
				});
			}, 500);
		}
		
		document.getElementById("timer_time").innerHTML = minutes + ":" + seconds + ":" + msec;
	}, 152);
}
function checkField(el, norm) {
	if(el.value == norm) {
		el.value = '';
		el.style.color = '#000000';
	}
}
function fixField(el, norm) {
	if(el.value == '') {
		el.value = norm;
		el.style.color = '#999';
	}
}
function checkBox(name) {
	var el = document.getElementById(name);
	if(el.checked == true) {
		el.checked = false;
	} else {
		el.checked = true;
	}
}
function verifyForm(form) {
	var error = "";
	if(document.getElementById('name').value == 'Full Name') {
		error += "Is your Name really 'Full Name'?\n";
	}
	var email = document.getElementById('email').value;
	if(email == 'E-Mail Address') {
		error += "Can you please enter a valid E-Mail Address?\n";
	} else {
		var emailFilter=/^.+@.+\..{2,3}$/;
		if (!(emailFilter.test(email))) { 
    	   	error += "Can you please enter a valid E-Mail Address?\n";
		}
		var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/
		if (email.match(illegalChars)) {
		   error += "The email address contains illegal characters.\n";
		}
	}
	
	if(error != "") {
		return alert(error);
	}
	return form.submit();
}
function fade(el, from, to, interval, callBack) {
    if (el == new String(el)) el = document.getElementById(el);
	if(el.style.display == 'none') { el.style.opacity = '0'; el.style.display = 'block'; }

    var dif = Math.abs(to - from);
    var pi = Math.PI;
    var i = 0;
    
    var opacs = [];
    
    for (var theta=0; theta < 90; theta+=8) { 
    	if (to > from) 
			var step = Math.sin((theta*pi)/180);
		else 
			var step = Math.cos((theta*pi)/180);
		
		opacs.push(dif*step);
    }
        
	var inter = setInterval(
		function() {
			if (++i < opacs.length) {
				el.style.opacity = Math.max(0.01, opacs[i]);
			} else {
				el.style.opacity = to;
				if(to == 0) { el.style.display = 'none'; }
				clearInterval(inter);
				if (callBack != null) callBack();
			}
		}, interval);
}
function inProgress() {
	document.getElementById('timer').style.display = 'none';
	document.getElementById('idle').innerHTML = 'a round is currently in progress';
	fade('idle', 0, 1.0, 50, null);
	
	sendRequest('nextgame', 'app=menuet');
}
function clickApp(app) {
	if(!document.getElementById('clicked')) {
		var clicked = document.createElement("div");
		clicked.setAttribute("id", "clicked");
		clicked.setAttribute("style", "display:none;");
		var container = document.getElementById('backup'); 
		container.appendChild(clicked);
	
		if(app == 'menuet') {
			fader('#33A740', '25', '50');
			document.getElementById('idle').innerHTML = 'You&rsquo;ve chosen Menuet.';
			sendRequest('enter', 'app=menuet');
		}
		if(app == 'appzapper') {
			fader('#2075B8', '25', '50');
			document.getElementById('idle').innerHTML = 'You&rsquo;ve chosen AppZapper.';
			sendRequest('enter', 'app=appzapper');
		}
		if(app == null) {
			fader('#666666', '25', '50');
			document.getElementById('idle').innerHTML = 'Shucks, you missed it.';
		}
		setTimeout(function() {
			fade('icons', 1.0, 0, 50, null);
			setTimeout(function() { 
				fade('idle', 0, 1.0, 50, null);
				fade('determine', 0, 1.0, 50, null);
				setTimeout(function() { sendRequest('entries', 'app=' + app); }, 4000);
				var time_run = document.getElementById('time_hold').innerHTML;
				var run_for = (((20 - time_run) + 5) * 1000);
				setTimeout(function() {
					fade('determine', 1.0, 0, 50, null);
					fade('idle', 1.0, 0, 50, function() {
						if(app == null) {
							document.getElementById('idle').innerHTML = 'better luck next time...';
						} else {
							var ppl = document.getElementById('clicked').innerHTML;
							if(!ppl) { ppl = 'alot'; }
							if(ppl == '1') {
								document.getElementById('idle').innerHTML = 'so has <b>' + ppl + '</b> other person...';
							} else {
								document.getElementById('idle').innerHTML = 'so have <b>' + ppl + '</b> other people...';
							}
						}
						fade('idle', 0, 1.0, 50, null);	
						setTimeout(function() { 
							fade('idle', 1.0, 0, 50, function() {
								document.getElementById('idle').innerHTML = 'the <b>Winners</b> are...';
								sendRequest('winners', 'load=true');
								fade('idle', 0, 1.0, 50, function() {
									setTimeout(function() {
										fade('idle', 1.0, 0, 50, null);
										fader('#AF1CAE', '25', '50');
										fade('winners', 0, 1.0, 50, null);
										setTimeout(function() {
											fade('winners', 1.0, 0, 50, function() {
												fader('#AF282A', '25', '50');
												countdown(); 
												fade('timer', 0, 1.0, 50, null); 
												
												var backup = document.getElementById('backup');
												var clicked = document.getElementById('clicked');
												backup.removeChild(clicked);
												
												document.getElementById('counterdos').innerHTML = '20';
												});
										}, 18000);
									}, 5000);
								});
							}); 
						}, 5000);
					}); 
				}, run_for);
			}, 1500);
		}, 2000);
	}
}

var sender = null;
var command = "";
var queueCmd = new Array();
var queueData = new Array();
function createRequest() {
	var request = null;
	if (window.XMLHttpRequest)
		request = new XMLHttpRequest();
	else if (window.ActiveXObject) {
		try {
			request = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(event) {
			try {
				request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(event) {
				return null;
			}
		}
	}
	else
		return null;
	return request;
}
function sendRequest(cmd, data) {
	if (sender == null) {
		sender = createRequest();
		if (sender != null) {
			command = cmd;
			sender.onreadystatechange = dataReceived;
			sender.open("POST", "ajax.php");
			sender.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			var postData = "command=" + command;
			if (data != "")
				postData += "&" + data;
			sender.send(postData);
		}
	}
	else {
		queueCmd[queueCmd.length] = command;
		queueData[queueData.length] = data;
	}
}
function dataReceived() {
	if (sender.readyState == 4) {
		if (sender.responseText != null && sender.responseText != "") {
			if (command == "entries") {
				document.getElementById('clicked').innerHTML = sender.responseText;
			}
			if (command == "winners") {
				scriptfrag = '(?:<script.*?>)((\n|.)*?)(?:<\/script>)';
				var match    = new RegExp(scriptfrag, 'im');
    			var scripts  = sender.responseText.match(match);
				
				setTimeout(function() {
      			  for (var i = 0; i < scripts.length; i++)
					if(scripts[i].match(match)[1]) {
      			    	eval(scripts[i].match(match)[1]);
					}
      			}, 10);
			}
			if (command == "nextgame") {
				scriptfrag = '(?:<script.*?>)((\n|.)*?)(?:<\/script>)';
				var match    = new RegExp(scriptfrag, 'im');
    			var scripts  = sender.responseText.match(match);
				
				setTimeout(function() {
      			  for (var i = 0; i < scripts.length; i++)
					if(scripts[i].match(match)[1]) {
      			    	eval(scripts[i].match(match)[1]);
					}
      			}, 10);
				setTimeout(function() { countdown(); }, 100);
			}
		}
		if (queueCmd.length > 0) {
			sendRequest(queueCmd[0], queueData[0]);
			queueCmd.splice(0, 1);
			queueData.splice(0, 1);
		}
		sender = null;
	}
}

function popCentered(url, widthVar, heightVar, scrollbars, windowName) {
	var Xpos= (screen.availWidth - widthVar)/2;
	var Ypos= (screen.availHeight - heightVar)/2;
	var str="toolbar=no,location=no,scrollbars=" + scrollbars + ",directories=no,status=no,menubar=no,resizable=no,copyhistory=no,left=" + Xpos + ",screenX=" + Xpos + ",top=" + Ypos + ",screenY=" + Ypos + ",width="+widthVar+",innerWidth="+widthVar+",height="+heightVar+",innerHeight="+heightVar;
	windowName = windowName == null ? "newWin" : windowName;
	window.open(url,windowName,str);
}


