/*global fullW, scriptPath */

/* width of entire counter */
fullW = 450;
scriptPath = "/scripts/" ;

/*global msinDay, msinHour, msinMin, msinSec */

//define time units in miliseconds. Aids in time calculations
msinSec  = 1000;
msinMin  = msinSec * 60;
msinHour = msinMin * 60;
msinDay  = msinHour * 24;

/*global debug, imgSet, imageProps, themes, debugOut */
debug = 0;

imgSet = "bones.gif";
numPic = [30,30];
colPic = [30,15];

imageProps = [
	["boysmall.gif",40,74],
	["nozzhead.gif",40,74],
	["monfly.gif",60,68],
	["x1",60,68]
];

themes = [
	["venjunpat.gif", imageProps[0], 0 , imgSet],
	["venjunpat.gif", imageProps[1], "nozzshaft.gif", imgSet],
	["skullisland.gif", imageProps[2], 0 , imgSet],
	["gargantua.gif", imageProps[3], 0 , imgSet]
];

//accept milliseconds (ms) and converts into a time array of [day,hours,minutes,seconds]
function timeArr(ms) {
	var msRem = ms;
	
	var dayRem = Math.floor(msRem / msinDay );
	msRem %= msinDay;
	
	var hrRem = Math.floor(msRem / msinHour );
	msRem %= msinHour;

	var doggy = smallTime(msRem);
				
	return [dayRem , hrRem , doggy[0] , doggy[1] ];
}

function smallTime(ms) {
	var msRem = ms;

	var minRem = Math.floor(msRem / msinMin );
	msRem %= msinMin;

	var sRem = Math.floor(msRem / msinSec );
					
	return [minRem , sRem];
}


function elCreate(type,classy,id) {
	var newEl = document.createElement(type);
	if (classy) {newEl.className = classy;}
	if (id) {newEl.id = id;}
	return newEl;
}

function killChildren(cell) {
	if ( cell.hasChildNodes() )
	{
		while ( cell.childNodes.length >= 1 )
    	{
        	cell.removeChild( cell.firstChild );       
		} 
	}
}


// adds style definitions in order to properly display background images
function timgStyle(item , size , bkImg , bPos ) {
	item.style.backgroundImage = "url('" + scriptPath + bkImg + "')";
	item.style.backgroundPosition = bPos[0] + "px " + bPos[1] + "px";
	item.style.height = size[0] + "px";
	item.style.width = size[1] + "px";
}

function movPos( ms ) {
	var unit = ms / msinMin;
	var unitInDay = 1440;
	
	return (unit * (fullW / unitInDay )).toFixed(2);
}

function chooseTheme( choice ) {
	var theme = themes[0];
	if (choice === "noz")	{ theme = themes[1]; }
	if (choice === "mon")	{ theme = themes[2]; }
	return theme;	
}

function showRunner(time , theme ) {
	var place = movPos( time );
	var tChoice = chooseTheme(theme);
    var runway = document.getElementById("run1");
	killChildren(runway);
	
	if (time < 1) {
		var gotime = elCreate('img',"timesup","go-1");
		gotime.src = scriptPath + "go!.png";
		gotime.style.display = "block";
		gotime.style.margin = "0 auto";
		runway.appendChild(gotime);
		return;
	}
	
	var runHead =  elCreate('img',"runmage","runner-head");

	runHead.style.cssFloat = "left";
	runHead.style.marginLeft = place + "px";
	runHead.src = scriptPath + tChoice[1][0];
	
	var runTrail = elCreate('div',"flourish","trail-image");
	runTrail.style.cssFloat = "left";
	
	if (tChoice[2] !== 0) {	
		timgStyle(runTrail , [tChoice[1][1],(fullW - place - 40) ] , tChoice[2], [0,0]);
		runTrail.style.backgroundRepeat = "repeat-x";
	}

	runway.appendChild(runHead);
	runway.appendChild(runTrail);
}

function addZero(num) {
	var nmSt = num.toString();
	if (nmSt.length <= 1) {nmSt = "0" + nmSt;}
	return nmSt;
}

// represents a numeral with a series of images 
function numPicts( num ) {
	var nmSt = addZero(num);	
	var numSL = nmSt.length;
	var clock = document.getElementById("clock1");
	
	for (var dig = 0; dig < numSL; dig += 1) {		
		var curNum = nmSt.charAt(dig);
		
		var digital = elCreate('div',"timage", "digit-" + curNum );
		timgStyle(digital , numPic , imgSet , [-(numPic[1] * curNum ), 0]);
		clock.appendChild(digital);
	}
}

// pass off a time array from timeArr() format into a countdown clock format.
function graphicTime( time ) {
	var tArr = timeArr( time );
	var leng = tArr.length;
	var clock = document.getElementById("clock1");
	killChildren( clock );

	for (var x = 0;x < leng;x += 1) {
		numPicts(tArr[x]);
		//colons only between numbers
		if (x < leng - 1) {
			var timer = elCreate('div',"timage","col-" + x);
			timgStyle(timer , colPic , imgSet, [-(numPic[1]*10) , 0]);
			clock.appendChild( timer );
		}
	}
	
}

function layout(where,theme) {
	var myDiv = document.getElementById(where);
	killChildren(myDiv);

	var wcDiv = elCreate('div' ,"wholecount" , "countme");
	wcDiv.style.backgroundImage = "url('" + scriptPath + chooseTheme(theme)[0] + "')";
	
	var head 	= elCreate('div' ,"timehead" , "head1");
	var runway 	= elCreate('div' ,"runner" , "run1");
	var clock 	= elCreate('div' ,"time" ,"clock1");
	
	runway.style.height = chooseTheme(theme)[1][1] + "px";
	/* clock.style.clear = "both"; */
	
	wcDiv.appendChild(head);
	wcDiv.appendChild(runway);
	wcDiv.appendChild(clock);
	
	
	myDiv.appendChild(wcDiv);
		
	if (debug) {
		debugOut = elCreate('div',"debugger" ,"debug1");
		debugOut.style.cssFloat = "right";
		myDiv.appendChild(debugOut);
	}	
}

function timeLeft(endDate) {
	var today = new Date();
	var msLeft = new Date(endDate).getTime() - today.getTime();
	
	/*get timezone offset from GMT in hours.
	var tmz = today.getTimezoneOffset()/60;
	
	adjust for timezone.  Central (5) and Mountain (6), during DST anyway
	if (tmz === 5 || tmz === 6) {
		msLeft = msLeft - ((tmz - 4) * msinHour );
	}
	*/
 	
 	return msLeft;

}

function showFull(left, theme) {	
	if (left <= msinDay) { showRunner(left, theme);}
	
	graphicTime(left);
}

function countdown(endDate ,theme ) {
	var remains = timeLeft( endDate );
	
	if ( remains > 0 ) {
			showFull( remains , theme );
			setTimeout("countdown('" + endDate + "',\'" + theme + "')", 1000);
	}
	
	else {
			showFull( 0, theme );
			return;
	}
}

// accepts a date 'endDate' to countdown to, the event name 'event', and the html tag 'spot' to put counter within. EndDate also accepts the value of "Off".
function superCount(endDate ,event ,spot ,theme ) {
	if (event === "off") { 
		return;
	}
	if (!document.getElementById(spot).hasChildNodes()) {layout(spot,theme);}
	
	var showcase = document.getElementById("head1");
	showcase.innerHTML = unescape(event);

	countdown(endDate ,theme )

}

function nextEp(eplist) {
	var best = Infinity;
	var next = ['Jun 11 1900',"off","boys"];
	var expire = -(msinHour/2)
	var past = expire;
	
	var epL = eplist.length;
	for (var x = 0; x < epL; x += 1) {
		var time = timeLeft(eplist[x][0]);
        if (time < expire ) {past = time;}
		if (past < time && time < best ) {
			next = eplist[x];
			best = time;
		}
    }					
	return next;
}	


function setIt(time , place , piace ) {
		if(isNaN( time )){
       		time = 0;
		}
		showTime(time , piace );
		countLite(time , place ,0);
}

function countLite(time,place,count) {	
	if (count <= time) {
		showTime(count,place);
		count += 1;
		setTimeout("countLite(" + time + ",\'" + place + "\'," + count + ")", 1000);
	}

	else { 
		return;
	}
}

function showTime(time,place) {	
	var left = smallTime(time*1000);
	document.getElementById(place).innerHTML = addZero(left[0]) + ":" + addZero(left[1]);
}

// appends a random number to an element ID to ensure it'll be unique
function uniqueID(find) {	
	var rand = Math.floor(Math.random()*2048);
	var loc = document.getElementById(find);
	loc.id += "-" + rand;
	return rand;
}

function toggleVis(me){	
	if (me.style.visibility=="hidden"){
			me.style.visibility="visible";
		}
	else {
		me.style.visibility="hidden";
	}
}
