/*
Theme Name: CYVTM website
Author: Julia Makin and Alex Moss
*/

function warningTimeSettings(val, w1, w2, w3, w1sec, w2sec, w3sec)
{
    this.val = val;
    this.w1 = w1;
    this.w2 = w2;
    this.w3 = w3;
    this.w1sec = w1sec;
    this.w2sec = w2sec;
    this.w3sec = w3sec;
}

var time1to2 =    new warningTimeSettings("1to2min",     "one minute",   "one minute, thirty seconds",    "two minutes",  60,  90, 120);
var time2to3 =    new warningTimeSettings("2to3min",    "two minutes",  "two minutes, thirty seconds",  "three minutes", 120, 150, 180);
var time4to6 =    new warningTimeSettings("4to6min",   "four minutes",                 "five minutes",    "six minutes", 240, 300, 360);
var time5to7 =    new warningTimeSettings("5to7min",   "five minutes",                  "six minutes",  "seven minutes", 300, 360, 420);
var time8to10 =   new warningTimeSettings("8to10min", "eight minutes",                 "nine minutes",    "ten minutes", 480, 540, 600);
var time10to12 =  new warningTimeSettings("10to12min",  "ten minutes",               "eleven minutes", "twelve minutes", 600, 660, 720);

var defaultTime = new warningTimeSettings("5to7min",   "five minutes",                  "six minutes",  "seven minutes", 300, 360, 420);
var warningColours = ["black", "#bbbbbb", "#22ff22", "#ffff44", "#ff4444"];
var  warningLights = {
	_displayNodeId: 0,
	_warningColours: [warningColours[0], warningColours[1], warningColours[2], warningColours[3], warningColours[4]],
        _timeOptions: [ time1to2, time2to3, time4to6, time5to7, time8to10, time10to12 ],
	warningTimes: {
		val: "5to7min",
		w1: "five minutes",
		w2: "six minutes",
		w3: "seven minutes",
		w1sec: 300,
		w2sec: 360,
		w3sec: 420
	},
	inactive: warningColours[1],
	initial: warningColours[0],
	firstWarning: warningColours[2],
	secondWarning: warningColours[3],
	finalWarning: warningColours[4],
	
        setDisplayNodeId: function(idString) {
            if (document.getElementById(idString)) 
                this._displayNodeId = document.getElementById(idString);	
        },	
	setWarningColour: function(colourName){
	    if (this._displayNodeId !== 0) {
		    for (var i = 0; i < this._warningColours.length; i++) {
			    if (colourName == this._warningColours[i]) {
				    this._displayNodeId.style.backgroundColor = this._warningColours[i];
				    break;
			    }
		    }
		}
	},	
	setWarningTimesFromValue: function ( timeValue, elementId1, elementId2, elementId3) {
        for (var i = 0; i < this._timeOptions.length; i++) {
			if (timeValue == this._timeOptions[i].val) {
				this.warningTimes.val = this._timeOptions[i].val;
				this.warningTimes.w1 = this._timeOptions[i].w1;
				this.warningTimes.w2 = this._timeOptions[i].w2;
				this.warningTimes.w3 = this._timeOptions[i].w3;
				this.warningTimes.w1sec = this._timeOptions[i].w1sec;
				this.warningTimes.w2sec = this._timeOptions[i].w2sec;
				this.warningTimes.w3sec = this._timeOptions[i].w3sec;
				break;
			}
		} 
        if (elementId1.firstChild){
			elementId1.firstChild.nodeValue = this.warningTimes.w1;
		}
		if (elementId2.firstChild){
			elementId2.firstChild.nodeValue = this.warningTimes.w2;
		}	  
		if (elementId3.firstChild){
			elementId3.firstChild.nodeValue = this.warningTimes.w3;
		}	  
	},
        updateTime: function (seconds){
	    if (seconds >= this.warningTimes.w3sec)
	       this.setWarningColour(this.finalWarning);
	    else if (seconds >= this.warningTimes.w2sec)
	        this.setWarningColour(this.secondWarning);
	    else if (seconds >= this.warningTimes.w1sec)
                this.setWarningColour(this.firstWarning);  
        }
}

var webPageRehearsalTimer = {
    saved: false,
    showTimerOnly: false,
    timeVisible: true,
    docElement: function(elementId){
      return document.getElementById(elementId);
    },
    showInstructions: function(isVisible){
        /*  var instructions = "Instructions\n\n";
        instructions = instructions +
        "Use this timer like a stop-watch that shows minutes and seconds.\n" +
        "The 'Rese' button sets the time to zero, that is: 0:00. The 'Stop' button pauses the seconds count." +
        "The 'Start' button starts or re-starts the seconds count from where it was.\n\n";
        window.confirm(instructions);
        */
        if (isVisible) {
            this.docElement("instructions").style.display = "block";
            //    docElement("sidebar").style.display = "block";
            //    docElement("content").style.marginLeft = "200px";
            //    docElement("headercontent").style.display = "block";
            this.docElement("instructshow").firstChild.nodeValue = "Hide Instructions";
        } else {
            this.docElement("instructions").style.display = "none";
            //    docElement("sidebar").style.display = "none";
            //    docElement("content").style.marginLeft = "0";
            //    docElement("headercontent").style.display = "none";
            this.docElement("instructshow").firstChild.nodeValue = "Show Instructions";
        }
    },
	saveSettings: function ( currState ){
        var expiresOn = new Date();
        if (!(this.saved)){
            expiresOn.setMonth(expiresOn.getMonth() + 3);
            if (currState != ""){
	        document.cookie = "setting=warningTimes:" + currState + ";path=/;expires=" + expiresOn.toGMTString() + "domain:localhost";    
            }
            //alert('saved');
            this.saved = true;
        }
    },
    getSavedPageState: function (){
        var validData = false;
        var cookieData = "";
        var searchString = "setting="
        var cookieItem = "";
	    if (document.cookie != "") {	
            var cookies = document.cookie.split(';');
		    for (var i = 0; i<cookies.length; i++) {
	            if(cookies[i].substring(0, searchString.length) == searchString) {
	  	            cookieItem = cookies[i];
		            break;
	            }
	        }
            if (cookieItem != ""){
	            cookieData = cookieItem.split(":")[1];
	        }
	  	for (var i=0; i< warningLights._timeOptions.length;i++)	{
	            if(cookieData == warningLights._timeOptions[i].val) {
	  	            validData = true;
		            break;
	            }	  	
	        } 
        }
        if (validData)  {
            return(cookieData);
        } else  {
            return(defaultTime.val);
        }
    }	 	
}

function pageSetup(){
    var savedData = webPageRehearsalTimer.getSavedPageState();
    warningLights.setDisplayNodeId("timedisplay");
    warningLights.setWarningColour(warningLights.inactive);
    var warningTimesInput = document.getElementsByTagName("input");  
    for(var i = 0; i < warningTimesInput.length; i++ ){
        if (savedData == warningTimesInput[i].value){
            warningTimesInput[i].checked = "checked";
            warningLights.setWarningTimesFromValue(savedData, 
			                                       webPageRehearsalTimer.docElement("wtime1"),
												   webPageRehearsalTimer.docElement("wtime2"),
												   webPageRehearsalTimer.docElement("wtime3"));
            break;
        }
    }
    webPageRehearsalTimer.showInstructions(false);
    displayTime.setDisplayNodeId("digtime");
}

var displayTime = {
	
    _displayNodeId: 0,
    displayMinSec: function(seconds){
  	    if (this._displayNodeId){
/*		    this._displayNodeId.firstChild.nodeValue = this.parseMinSec(seconds);*/
		    this._displayNodeId.innerHTML = this.parseMinSec(seconds);
	    }
            //$('#digtime').html('');
            /*$('#digtime').html(this.parseMinSec(seconds));*/
 
            
    },
    parseMinSec: function( seconds ){
        var timeHours = parseInt(seconds / 3600);
        var remainder = seconds - timeHours * 3600;
        var timeMinutes = parseInt( remainder / 60);
        remainder = remainder - timeMinutes * 60;

        if (remainder < 10) {
            remainder = "0" + remainder;
        }
        return (timeMinutes + ":" + remainder);  
    },
    setDisplayNodeId: function(idString) {
        if (document.getElementById(idString)) 
            this._displayNodeId = document.getElementById(idString);
    },
	setVisible: function (isVisible){
	    if(isVisible){
			this._displayNodeId.style.visibility = "visible";
		}
		else{
			this._displayNodeId.style.visibility = "hidden";			
		}	
	}
}
 	
var pageTimer = {

	_intervalId: 0,
	_active: false,
	_tickCount: 0,
	_secs: 0,
	//manually set clock period (msec) and clock periods per second
	_tickInterval: 200,
	_ticksPerSec: 5,
	
	enable: function(activate){
		if (activate) {
			if (!this._active) {
				this._active = true;
				this._intervalId = window.setInterval(timeTick, this._tickInterval);
				this.onEnable();
			}
		}
		else {
			if (this._active) {
				this._active = false;
				window.clearInterval(this._intervalId);
				this.onDisable();
			}
		}
	},
	reset: function(){
		this.enable(false);
		this._tickCount = 0;
		this._secs = 0;
		this.onSecsChange();
	},
	onTimeTick: function(){
		this._tickCount++;
		if (0 == (this._tickCount % this._ticksPerSec)) {
			this._tickCount = 0;
			this._secs++;
			this.onSecsChange();
		}
	},
	onEnable: function(){
        if (this._secs < warningLights.warningTimes.w1sec)
            warningLights.setWarningColour(warningLights.initial);	
	},
	onDisable: function() {
            warningLights.setWarningColour(warningLights.inactive); 	
	},
	onSecsChange: function(){
		warningLights.updateTime(this._secs);
                displayTime.displayMinSec(this._secs);
	}
}

function changeTimes(timeSelect){
  warningLights.setWarningTimesFromValue(timeSelect, 
                                         webPageRehearsalTimer.docElement("wtime1"),
										 webPageRehearsalTimer.docElement("wtime2"),
										 webPageRehearsalTimer.docElement("wtime3"));
}

function startTimer(){
    pageTimer.enable(true);
    setTimerButtonToStop();

	//webPageRehearsalTimer.docElement("timerstop").focus();
}

function stopTimer(){
    pageTimer.enable(false);
    setTimerButtonToStart();
        
}

function resetTimer(){
    pageTimer.reset();
    $("#timerstart").html("Start");
    $('#timerstart').unbind();
    $('#timerstart').bind('click', function() {
       startTimer();
     });


}

function timeTick(){
	pageTimer.onTimeTick();
}

function changeInstructionVisibility(){
    webPageRehearsalTimer.showTimerOnly = !webPageRehearsalTimer.showTimerOnly;
    webPageRehearsalTimer.showInstructions(webPageRehearsalTimer.showTimerOnly);
}

function changeTimeVisibility(){
    webPageRehearsalTimer.timeVisible = !webPageRehearsalTimer.timeVisible;
    showTime(webPageRehearsalTimer.timeVisible);
}
 
function showTime(isVisible){

    displayTime.setVisible(isVisible);
    if (!isVisible)
    {
        webPageRehearsalTimer.docElement("digtimehead").style.visibility = "hidden";
        webPageRehearsalTimer.docElement("timeshow").firstChild.nodeValue = "Show Time";
    }
    else
    {
        webPageRehearsalTimer.docElement("digtimehead").style.visibility = "visible";
        webPageRehearsalTimer.docElement("timeshow").firstChild.nodeValue = "Hide Time";
    }
}

function pageClose(){
  webPageRehearsalTimer.saveSettings(warningLights.warningTimes.val);
}

function setTimerButtonToStart(){
    $("#timerstart").html("Start");
    $('#timerstart').unbind();   
    $('#timerstart').bind('click', function() {
       startTimer();
     });    
}

function setTimerButtonToStop(){
    $("#timerstart").html("Stop");
    $('#timerstart').unbind('click', function() {
       startTimer();   
     })
    $('#timerstart').bind('click', function() {
       stopTimer();
     })    
}

//jQuery section - will transfer more of the above to jQuery as time permits
$(window).load(function(){
    //alert('setup');
    pageSetup();
});
//window.unload = pageClose();
$(window).unload(function(){
    //alert('window unload');
    pageClose();
    //webPageRehearsalTimer.saved = false;
});


$(document).ready(function(){
    $(".timelbl").mouseover(function(){
        $(this).css("padding", "2px");         
        $(this).css("background-color","#3e5e88");
        $(this).css("box-shadow", "2px 4px 2px #333333");
    });
    $(".timelbl").mouseout(function(){
        $(".timelbl").css("background-color","transparent") 
        //$(".timelbl").css("border", "none");
        $(".timelbl").css("box-shadow", "0 0 0 #333333");
    });
    $(".timelbl").mousedown(function(){
        $(this).css("padding","0 4px 4px 0");
        $(this).css("box-shadow", "0px 0px 0px #333333");
        //$(".timelbl").css("border", "none");        
    })
    $(".timelbl").mouseup(function(){
        $(this).css("padding", "2px");
        $(this).css("box-shadow", "2px 4px 0px #333333");   
    })
  
});

$(function( ){
    $(window).bind('beforeunload', function() {
        //alert('window b4unload');   
        //pageClose();
    })
    $('#timeop1') . bind('click', function(event) {
        changeTimes('1to2min');
    });
    $('#timeop2') . bind('click', function(event) {
        changeTimes('2to3min');
    });
    $('#timeop4') . bind('click', function(event) {
        changeTimes('4to6min');
    });
    $('#timeop5') . bind('click', function(event) {
        changeTimes('5to7min');
    });
    $('#timeop8') . bind('click', function(event) {
        changeTimes('8to10min');
    });   
    $('#timeop10') . bind('click', function(event) {
        changeTimes('10to12min');
    });
    
    $('#instructshow') . bind('click', function(event) {
       changeInstructionVisibility(); 
    });
    
    $('#timerstart') . bind('click', function(event) {
       startTimer();
       
    });
    
    $('#timerstop') . bind('click', function(event) {
       stopTimer(); 
    });
    
    $('#timerreset') . bind('click', function(event) {
       resetTimer(); 
    });
    
    $('#timeshow') . bind('click', function(event) {
       changeTimeVisibility(); 
    });
    
});
    /*
    function changeTimes(timeSelect){
  warningLights.setWarningTimesFromValue(timeSelect, 
                                         webPageRehearsalTimer.docElement("wtime1"),
										 webPageRehearsalTimer.docElement("wtime2"),
										 webPageRehearsalTimer.docElement("wtime3"));
}

<li><a href="#" class="timercontrolsop, roundcorners" id="instructshow" name="instructshow" tabindex="5" onclick="changeInstructionVisibility();">Show Instructions</a></li>

*/
    //onclick="changeTimes('1to2min');" onclick="changeTimes('2to3min');"onclick="changeTimes('4to6min');" 
    //onclick="changeTimes('5to7min');"onclick="changeTimes('8to10min');" onclick="changeTimes('10to12min');"
    //onclick="changeInstructionVisibility();"
    //<li><a href="#" id="timerstart" tabindex="1" accesskey="k" onclick="startTimer();">Start</a></li>
    //<li><a href="#" id="timerstop" tabindex="2" accesskey="P" onclick="stopTimer();">Stop</a></li>
    //<li><a href="#" id="timerreset" tabindex="3" accesskey="q" onclick="resetTimer();">Reset</a></li>
    //<li><a href="#" id="timeshow" tabindex="4" onclick="changeTimeVisibility();">Hide Time</a></li>


