
// global counters
var counterArray = [];
var timeOutClock = null;


$(document).ready(function() {

  // SENDING //
  $(".scoreButton").click(function() {
	  var me = $(this);
	  var associatedValueBox = me.attr("associatedValueBox");
	  var previewField = document.getElementById(associatedValueBox);
	  var action = me.attr("action");
	  var paramString = "action=";
	  paramString += action;
	  
	  // post the string, asking the server for the preview string using these token fields
	  $.ajax({
			 type: "POST",
			 url: "/html/scoreBoard",
			 data: paramString,
			 cache: false,
			 success: function(html) {
				 // update value
				 previewField.innerHTML = html;
			 }
	 });
	});

  $(".smallScoreButton").click(function() {
      var me = $(this);
      var associatedValueBox = me.attr("associatedValueBox");
      var previewField = document.getElementById(associatedValueBox);
      var action = me.attr("action");
      var paramString = "action=";
      paramString += action;
      
      // post the string, asking the server for the preview string using these token fields
      $.ajax({
             type: "POST",
             url: "/html/scoreBoard",
             data: paramString,
             cache: false,
             success: function(html) {
                // update value
                previewField.innerHTML = html;
             }
        });
    });
				  
	$(".switchButton").click(function() {
		   var me = $(this);
		   var action = me.attr("action");
		   var paramString = "action=";
		   paramString += action;
		   
		   $.ajax({
				  type: "POST",
				  url: "/html/scoreBoard",
				  data: paramString,
				  cache: false,
				  success: function(html) {
					  // update value
					  if (html == "1") {
						me.attr("checked","checked");
					  } else {
						me.removeAttr("checked");
					  }
				  }
				}
			);
	});

  $(".baseballInningScoreButton").click(function() {
	var me = $(this);
	var associatedValueBox = me.attr("associatedValueBox");
	var previewField = document.getElementById(associatedValueBox);
	var action = me.attr("action");
	var paramString = "action=";
	paramString += action;

	var homeAtBat = document.getElementById("homeAtBatButton");
	var visitorAtBat = document.getElementById("visitorAtBatButton");
	  // post the string, asking the server for the preview string using these token fields
	  $.ajax({
			 type: "POST",
			 url: "/html/scoreBoard",
			 data: paramString,
			 cache: false,
			 success: function(html) {
				// update value
				previewField.innerHTML = html;
				$(homeAtBat).addClass("active")
				$(visitorAtBat).removeClass("active")
				getScoring();
				getInningTable();
			 }
		});
  });
				  
  $(".baseballScoreButton").click(function() {
	  var me = $(this);
	  var associatedValueBox = me.attr("associatedValueBox");
	  var previewField = document.getElementById(associatedValueBox);
	  var action = me.attr("action");
	  var paramString = "action=";
	  paramString += action;
	  
	  // post the string, asking the server for the preview string using these token fields
	  $.ajax({
			 type: "POST",
			 url: "/html/scoreBoard",
			 data: paramString,
			 cache: false,
			 success: function(html) {
				// update value
				previewField.innerHTML = html;
				getInningTable();
			 }
		});
  });
				  
  $(".atBatButton").click(function(){
		$(".atBatButton").removeClass("active");
		$(this).addClass("active");
	});

      
  $(".penaltyButton").click(function() {
		var me = $(this);
		
		var action = me.attr("action");
		var paramString = "action=";
		paramString += action;
		var team = me.attr("team");
		paramString += "+tag="+team;
		
		var previewField = document.getElementById("playerNumber"+team);
		var playerNumber = previewField.value;
		paramString += "_"+playerNumber;
		
		var timeValueField = document.getElementById("timeValue"+team);
		var timeValue = timeValueField.value;
		paramString += "_"+timeValue;
		
		var tableContents = document.getElementById("penaltyTableContents"+team);
		
		// post the string, asking the server for the preview string using these token fields
		$.ajax({
		   type: "POST",
		   url: "/html/scoreBoard",
		   data: paramString,
		   cache: false,
		   success: function(html) {
			   previewField.value = "";
			   getPenalties(team);
		   }
		});
	});
                  
  $(".macroButton").click(function() {
	  var me = $(this);
	  var action = me.attr("action");
	  var paramString = "action=";
	  paramString += action;
	  var arguements = me.attr("tag");
	  paramString += "+tag="+arguements;
	  
	  // post the string, asking the server for the preview string using these token fields
	  $.ajax({
			 type: "POST",
			 url: "/html/scoreBoard",
			 data: paramString,
			 cache: false,
			 success: function(html) {
				//previewField.innerHTML = html;
			 }
		});
	});

  $(".possessionButton").click(function() {
						  var me = $(this);
						  var action = me.attr("action");
						  var paramString = "action=";
						  paramString += action;

						  var homePossession = document.getElementById("homePossession");
						  var visitorPossession = document.getElementById("visitorPossession");

						  // post the string, asking the server for the preview string using these token fields
						  $.ajax({
								 type: "POST",
								 url: "/html/scoreBoard",
								 data: paramString,
								 cache: false,
								 success: function(team) {
									 if (team == 0) {
								 $(homePossession).addClass("active")
								 $(visitorPossession).removeClass("active")
									 } else {
								 $(homePossession).removeClass("active")
								 $(visitorPossession).addClass("active")
									 }
								 }
							});
					});
  
	$(".scoreBoardButton").click(function() {
	   var me = $(this);
	   var paramString = "action=showHideScoreBoard+tag=1";
	   var previewField = document.getElementById("showHideScoreBoardButton");
	   // post the string, asking the server for the preview string using these token fields
		$.ajax({
		  type: "POST",
		  url: "/html/scoreBoard",
		  data: paramString,
		  cache: false,
		  success: function(onOfOff) {
			   if (onOfOff == "false") {
				  previewField.innerHTML = "Hide Scoreboard";
			   } else {
				  previewField.innerHTML = "Show Scoreboard";
			   }
		  }
		});
	});
				  
				  
	$(".startTimeButton").click(function() {
		var me = $(this);
		var associatedValueBox = me.attr("associatedValueBox");
		var previewField = document.getElementById(associatedValueBox);
		var action = me.attr("action");
		var paramString = "action=";
		paramString += action;
		var arguements = me.attr("tag");
		paramString += "+tag="+arguements;

		// post the string, asking the server for the preview string using these token fields
		$.ajax({
			type: "POST",
			url: "/html/scoreBoard",
			data: paramString,
			cache: false,
			success: function(html) {
				 // update value
				previewField.innerHTML = html;
				createCounter(me);
			}
		 });
	  });
				  

	  $(".resetTimeButton").click(function() {
		  var me = $(this);
		  var associate = me.attr("associatedValueBox");
		  var previewField = document.getElementById(associate);
		  var startID = me.attr("startButtonID");
		  var button = document.getElementById(startID);
		  var action = me.attr("action");
		  var paramString = "action=";
		  paramString += action;
		  var arguements = me.attr("tag");
		  paramString += "+tag="+arguements;
		  
		  // post the string, asking the server for the preview string using these token fields
		  $.ajax({
				 type: "POST",
				 url: "/html/scoreBoard",
				 data: paramString,
				 cache: false,
				 success: function(html) {
					 // update value
				 	 previewField.innerHTML = html;
					 button.innerHTML = "Start";
					 for (var index in counterArray) {
						 var clock = counterArray[index];
						 if (clock.id == associate) {
							 clock.stop();
							 break;
						 };
					 };
				 }
			 });
	  });
});


// A Counter constructor function
var Counter = (function() {
   // The actual constructor (our return value)
   function Counter(id, timeString, tableRowIdString) {
       var hours, minutes, seconds;
       var timeComponents = timeString.split(":");
       if(timeComponents.length == 3){
           hours   = parseInt(timeComponents[0]);
           minutes = parseInt(timeComponents[1]);
           seconds = parseInt(timeComponents[2]);
       }else if (timeComponents.length == 2){
           hours   = 0;
           minutes = parseInt(timeComponents[0]);
           seconds = parseInt(timeComponents[1]);
       } else {
           hours   = 0;
           minutes = 0;
           seconds = parseInt(timeComponents[0]);
       }
       this.id = id;
       this.tableRowId = tableRowIdString;
       this.minutes = minutes || 0;
       this.seconds = seconds || 0;
       //console.log("this.id = "+this.id);
   }
   
   // Shortcut to the prototype
   var p = Counter.prototype;
			   
   
   // Start a counter
   p.start = Counter_start;
   function Counter_start() {
       var me = this;
       
       // Find the time (in ms since The Epoch) at which
       // this item expires
       this.timeout = new Date().getTime() + (((this.minutes * 60) + this.seconds+1) * 1000);
       
       // Get this counter's target element
       this.element = document.getElementById(this.id);
       if (this.element) {
           // Do the first update
           // tick(this);
           
           // Schedule the remaining ones to happen *roughly*
           // every quarter second. (Once a second will look rough).
            this.timer = setInterval(function() { tick(me); }, 250);
            //console.log("setInterval: "+this.timer);
       }else{
           //console.log("no document.getElementById: "+this.id);
       }
   }
   
   // Stop a counter
   p.stop = Counter_stop;
   function Counter_stop() {
       if (this.timer) {
            clearInterval(this.timer);
            //console.log("clearInterval: "+this.timer);

           this.timer = null;
           delete this.timer;
       }
       //delete this.element;
   }
   
   // The function we use to update a counter; not exported
   // on the Counter prototype because we only need one for
   // all counters.
   function tick(counter) {
        var remaining, str, minutes, seconds;
       
       // How many seconds left?
       remaining = Math.floor((counter.timeout - new Date().getTime()) / 1000);
       
       // Same as last time?
       if (remaining != counter.lastRemaining) {
            // No, do an update
            counter.lastRemaining = remaining;
            if (remaining <= 0 && counter.element != null) {
                // Done! Stop the counter.
                str = "00:00";
                counter.element.innerHTML = str;

                //console.log("tick: "+counter);

                // remove the table row
                var table = counter.element.parentNode.parentNode;
                $("#"+counter.tableRowId).remove();
   
                // insert blank row
                var row = table.insertRow(5);
                var newCell  = row.insertCell(0);
                newCell  = row.insertCell(1);
                newCell  = row.insertCell(2);
                counter.stop();
           } else {
               minutes = Math.floor(remaining / 60);
			   str = padLeft(minutes,2)

               // Truncate the minutes, just leave seconds (0..59)
               remaining %= 60;
			   seconds = Math.floor(remaining);
			   str += ":"+padLeft(seconds,2)
            }
       
           // Write to the element
           counter.element.innerHTML = str;
           //console.log(counter.element);
       }
   }
   // Return the constructor function reference. This
   // gets assigned to the external var, which is how
   // everyone calls it.
   return Counter;
})();


function padLeft(nr, n, str){
	return Array(n-String(nr).length+1).join(str||'0')+nr;
}


// A Counter constructor function
var SoccerCounter = (function() {
   // The actual constructor (our return value)
   function Counter(id, timeString, entTimeString) {
       var hours, minutes, seconds;
       var timeComponents = timeString.split(":");
       if(timeComponents.length == 3){
           hours   = parseInt(timeComponents[0]);
           minutes = parseInt(timeComponents[1]);
           seconds = parseInt(timeComponents[2]);
       }else if (timeComponents.length == 2){
           hours   = 0;
           minutes = parseInt(timeComponents[0]);
           seconds = parseInt(timeComponents[1]);
       } else {
           hours   = 0;
           minutes = 0;
           seconds = parseInt(timeComponents[0]);
       }
       this.id = id;
       this.minutes = minutes || 0;
       this.seconds = seconds || 0;
       this.endTime = entTimeString;
   }
   
   // Shortcut to the prototype
   var p = Counter.prototype;
   
   // Start a counter
   p.start = Counter_start;
   function Counter_start() {
       var me = this;
       
   // (0.5 seems to compensate for discrepancy between ProPresenter and local web
   this.startTime = new Date().getTime() + (((this.minutes * 60) + this.seconds - 0.5) * 1000);
       
       this.currentInterval = ((this.minutes * 60) + this.seconds);
       // Get this counter's target element
       this.element = document.getElementById(this.id);
       if (this.element) {
           // Do the first update
            tick(this);
           
           // Schedule the remaining ones to happen *roughly*
           // every quarter second. (Once a second will look rough).
           this.timer = setInterval(function() { tick(me); }, 250);
           //console.log("setInterval: "+this.timer);
       }
   }
   
   // Stop a counter
   p.stop = Counter_stop;
   function Counter_stop() {
       if (this.timer) {
           clearInterval(this.timer);
           //console.log("clearInterval: "+this.timer);
           
           this.timer = null;
           delete this.timer;
       }
        delete this.element;
   }
   
   // The function we use to update a counter; not exported
   // on the Counter prototype because we only need one for
   // all counters.
   function tick(counter) {
       var currentTime, str, minutes, seconds;
       str = "";
       var now = new Date().getTime() + (((counter.minutes * 60) + counter.seconds) * 1000);
       
       currentTime = Math.floor((now-counter.startTime)/1000);
       currentTime += ((counter.minutes * 60) + counter.seconds)
       if(counter.currentInterval != currentTime){
           counter.currentInterval = currentTime;
           
           minutes = Math.floor(currentTime / 60);
           str += minutes+":";
           // Truncate the minutes, just leave seconds (0..59)
           seconds = currentTime % 60;
           str += padLeft(seconds,2)
           counter.element.innerHTML = str;

           if(str == counter.endTime){
                counter.stop();
           }
       }
   }
   // Return the constructor function reference. This
   // gets assigned to the external var, which is how
   // everyone calls it.
   return Counter;
})();

function createTimeOutCounter() {
	// get time out clock
	var clockDuration = document.getElementById("timeOutClock").innerHTML;
	var clock = new Counter("timeOutClock", clockDuration);
	timeOutClock = clock;
	
	updateTimeOut();
}

function startClock() {
    var paramString = "action=startStopClock";
    var clockContents = document.getElementById("gameClockForm");
    //console.log("clockContents: "+clockContents);
    // post the string, asking the server for the preview string using these token fields
    $.ajax({
           type: "POST",
           url: "/html/scoreBoard",
           data: paramString,
           cache: false,
           success: function(html) {
           		clockContents.innerHTML = html;
                //console.log("html: "+html);
           		createCounters();
           }
    });

}

function startTimeOutClock() {
	var paramString = "action=startStopTimeOutClock";
	var clockContents = document.getElementById("timeOutClockForm");
	//console.log("clockContents: "+clockContents);
	// post the string, asking the server for the preview string using these token fields
	$.ajax({
		   type: "POST",
		   url: "/html/scoreBoard",
		   data: paramString,
		   cache: false,
		   success: function(html) {
				clockContents.innerHTML = html;
				//console.log("html: "+html);
			   createCounters(); // this will stop current clocks 
			   createTimeOutCounter();
		   }
	});
	
}

function updateCounters() {
    $.ajax({
           type: "POST",
           url: "/html/scoreBoard",
           data: "action=clockStatus",
           cache: false,
           success: function(html) {
               //console.log("updateCounters");
               // get game clock button
               var gameClockButton = document.getElementById("gameClockButton");
               var iteratedClock;
               if(parseInt(html) == 1){
                   gameClockButton.innerHTML = "Stop";
                   for (iteratedClock in counterArray) {
                        //console.log("start iteratedClock "+counterArray[iteratedClock]);
                        counterArray[iteratedClock].start();
                   };
               }else{
                   gameClockButton.innerHTML = "Start";
                   for (iteratedClock in counterArray) {
                       //console.log("stop iteratedClock "+counterArray[iteratedClock]);
                       counterArray[iteratedClock].stop();
                   };
                   if (typeof getPenalties() == 'function') {
                       getPenalties(0);
                       getPenalties(1);
                   }
               }
           }
    });
}

function updateTimeOut() {
	$.ajax({
		   type: "POST",
		   url: "/html/scoreBoard",
		   data: "action=timeOutClockStatus",
		   cache: false,
		   success: function(html) {
				   var timeOutClockButton = document.getElementById("timeOutClockButton");
				   if(parseInt(html) == 1){
						timeOutClockButton.innerHTML = "Stop";
						timeOutClock.start();
				   }else{
						timeOutClockButton.innerHTML = "Start";
						timeOutClock.stop();
				   }
			}
	});
}

function newGame(index=-1) {
	var msg = "Are you sure you want to start a new game?";
	if (index >= 0) {
		msg = "Are you sure you want to start a new game for [Group " + (index+1) + "]?";
	}
    var r = confirm(msg);
	
    if (r==true) {
        $.ajax({
               type: "POST",
               url: "/html/scoreBoard",
               data: "action=newGame+tag="+index,
               cache: false,
               success: function(html) {
                    // reload page
                    location.reload();
               }
        });
    }
}

function setTeamName(team) {
    var anElement = document.getElementById("team"+team+"Name");
    var nameString = anElement.value;
    var paramString = "action=setTeamName+tag="+team+"_"+nameString;
    
    // post the string, asking the server for the preview string using these token fields
    $.ajax({
           type: "POST",
           url: "/html/scoreBoard",
           data: paramString,
           cache: false,
           success: function(html) {
           // no update
           }
    });
}

function soundHorn() {
	$.ajax({
		   type: "POST",
		   url: "/html/scoreBoard",
		   data: "action=soundHorn",
		   cache: false,
		   success: function(html) {
		   // no update
		   }
	});
}

function resetClock() {
    var me = $(this);
    var paramString = "action=resetClock";
    paramString += "+tag="+document.getElementById("clockDuration").value;
    var endTimeObject = document.getElementById("clockEnd");
    if(endTimeObject){
        paramString += "_"+endTimeObject.value;
    }
    var clockContents = document.getElementById("gameClockForm");
    
    // post the string, asking the server for the preview string using these token fields
    $.ajax({
           type: "POST",
           url: "/html/scoreBoard",
           data: paramString,
           cache: false,
           success: function(html) {
			   clockContents.innerHTML = html;
			   createCounters();
           }
    });
};

function resetTimeOutClock() {
	var me = $(this);
	var paramString = "action=resetTimeOutClock";
	paramString += "+tag="+document.getElementById("timeOutDuration").value;
	var clockContents = document.getElementById("timeOutClockForm");
	
	// post the string, asking the server for the preview string using these token fields
	$.ajax({
		   type: "POST",
		   url: "/html/scoreBoard",
		   data: paramString,
		   cache: false,
		   success: function(html) {
			   clockContents.innerHTML = html;
			   createTimeOutCounter();
		   }
	});
};


function updateTimeValues() {
    document.getElementById('clockDuration').value=document.getElementById('clockStartSelector').value;
    document.getElementById('clockEndSelector').selectedIndex=document.getElementById('clockStartSelector').selectedIndex;
    document.getElementById('clockEnd').value=document.getElementById('clockEndSelector').value;
};


function formatTimeString(me, event) {
    //console.log(event.keyCode);
    if(event.keyCode != 8){
        var timeString = me.value;
        var cleanString = timeString.replace(":", "");
        var newString = "";
        var colonCount = 0;
        var m = cleanString.length;
        for(i=m; i>=0; i--){
            if(colonCount==2){
                newString = ":"+newString;
                colonCount = 0;
            }
            newString = cleanString.charAt(i)+newString;
            colonCount++;
        }
        me.value = newString;
    }
}

