var clockElement;
var next_game_epoch;
var reloadurl;
var win;


function show(elmnt){
		document.getElementById(elmnt).style.visibility="visible";
		document.getElementById(elmnt).style.display="block"
}
function hide(elmnt){
		document.getElementById(elmnt).style.visibility="hidden";
		document.getElementById(elmnt).style.display="none"
}
   
	
function setCookie (cookieName, cookieValue, expires, 
			path, domain, secure) {
  document.cookie = escape(cookieName) + '=' + escape(cookieValue) +
    (expires ? '; EXPIRES=' + expires.toGMTString() : '') +
    (path ? '; PATH=' + path : '') +
    (domain ? '; DOMAIN=' + domain : '') +
    (secure ? '; SECURE' : '');
}

function getCookie(cookieName) {
  var cookieValue = null;
  var posName = document.cookie.indexOf(escape(cookieName) + '=');

  if (posName != -1) {
    var posValue = posName + (escape(cookieName) + '=').length;
    var endPos = document.cookie.indexOf(';', posValue);
    if (endPos != -1)
      cookieValue = unescape(document.cookie.substring(posValue, endPos));
    else
      cookieValue = unescape(document.cookie.substring(posValue));
  }
  return cookieValue;
}


function dateAdd(dateToAdd, milliSecondsToAdd, debug) {
  if (debug && !win) {
	win = window.open("#", "debug",
                                "height=400,width=500,scrollbars=yes");
	win.document.open("text/plain");
  }

  if (debug) {
	win.document.writeln("---------------------------");
	win.document.writeln(dateToAdd.toString());
	win.document.writeln("milliseconds to add = " + milliSecondsToAdd);
  }

  var hoursToAdd = Math.floor(milliSecondsToAdd / (60 * 60 * 1000));
  if (hoursToAdd > 0) {
  	milliSecondsToAdd = milliSecondsToAdd - (hoursToAdd * 60 * 60 * 1000);
  }

  var minutesToAdd = Math.floor(milliSecondsToAdd / (60 * 1000) );
  if (minutesToAdd > 0) {
  	milliSecondsToAdd = milliSecondsToAdd - (minutesToAdd * (60 * 1000));
  }

  var secondsToAdd = Math.floor(milliSecondsToAdd / 1000);
  if (secondsToAdd > 0) {
  	milliSecondsToAdd = milliSecondsToAdd - (secondsToAdd * 1000);
  }

  if (debug) {
	win.document.writeln("hoursToAdd = " + hoursToAdd);
	win.document.writeln("minutesToAdd = " + minutesToAdd);
	win.document.writeln("secondsToAdd = " + secondsToAdd);
	win.document.writeln("msecsToAdd = " + milliSecondsToAdd);
	win.document.writeln();
  }

  var hoursNow = dateToAdd.getHours();
  var minutesNow = dateToAdd.getMinutes();
  var secondsNow = dateToAdd.getSeconds();
  var milliSecondsNow = dateToAdd.getMilliseconds();

  if (debug) {
	win.document.writeln("hoursNow = " + hoursNow);
	win.document.writeln("minutesNow = " + minutesNow);
	win.document.writeln("secondsNow = " + secondsNow);
	win.document.writeln("msecsNow = " + milliSecondsNow);
	win.document.writeln();
  }

  if (parseInt(milliSecondsNow) + parseInt(milliSecondsToAdd) > 999) {
	secondsToAdd++;
	var milliSeconds = parseInt(milliSecondsNow) + 
			   parseInt(milliSecondsToAdd) - 1000;
	if (debug) {
		win.document.writeln("milliSeconds = " + milliSeconds);
	}
	dateToAdd.setMilliseconds(milliSeconds);
  } else if (parseInt(milliSecondsToAdd) > 0) {
	dateToAdd.setMilliseconds(
		parseInt(milliSecondsNow) + 
		parseInt(milliSecondsToAdd)
	);
  }

  if (parseInt(secondsNow) + parseInt(secondsToAdd) > 59) {
	minutesToAdd++;
	var seconds = parseInt(secondsNow) + parseInt(secondsToAdd) - 60;
	if (debug) {
		win.document.writeln("minutes = " + seconds);
	}
	dateToAdd.setSeconds(parseInt(seconds));
  } else if (parseInt(secondsToAdd) > 0) {
	dateToAdd.setSeconds(
		parseInt(secondsNow) + 
		parseInt(secondsToAdd)
	);
  }


  if (parseInt(minutesNow) + parseInt(minutesToAdd) > 59) {
	hoursToAdd++;
	var minutes = minutesNow + minutesToAdd - 60;
	if (debug) {
		win.document.writeln("minutes = " + minutes);
		win.document.writeln();
	}
	dateToAdd.setMinutes(minutes);
  } else if (parseInt(minutesToAdd) > 0) {
	dateToAdd.setMinutes(
		parseInt(minutesNow) + 
		parseInt(minutesToAdd)
	);
  }


  if (parseInt(hoursNow) + parseInt(hoursToAdd) > 23) {
	dateToAdd.setDate(dateToAdd.getDate() + 1);	// kludge
	dateToAdd.setHours(hoursNow + hoursToAdd - 24);
  } else if (parseInt(hoursToAdd)) {
	dateToAdd.setHours(
		parseInt(hoursNow) + 
		parseInt(hoursToAdd)
	);
  }
  
  if (debug) {
	win.document.writeln(dateToAdd.toString());
	win.document.writeln();
  }
}



//
// extrapolateGameEpoch - given reference (ref_game_time, ref_epoch)
//			extrapolate epoch for game_time
//			game_time and ref_game_time is of the format 
//				[0|1] hour:minute
//			0 is for todays game and 1 is for tomorrows game
//
function extrapolateGameEpoch(ref_epoch, ref_game_time,
                                 game_time, debug) {

	if (debug) {
		alert("ref_epoch = " + ref_epoch + ", ref_game_time = " +
				ref_game_time + ", game_time = " + game_time);
	}

	// mnemonic tt stands for TodayTomorrow
        var ref_game_tt = parseInt(ref_game_time.charAt(0));
        var colon_at = ref_game_time.indexOf(':');
        var ref_game_hour = parseInt(ref_game_time.substring(2, colon_at));
        var ref_game_min = parseInt(ref_game_time.substring(colon_at + 1));
	if (debug) {
		alert("ref_game_tt = " + ref_game_tt + ", ref_game_hour = " +
				ref_game_hour + ", ref_game_min = " +
				ref_game_min);
	}

        var game_tt = parseInt(game_time.charAt(0));
        colon_at = game_time.indexOf(':');
        var game_hour = parseInt(game_time.substring(2, colon_at));
        var game_min = parseInt(game_time.substring(colon_at + 1));
	if (debug) {
		alert("game_tt = " + game_tt + ", game_hour = " +
				game_hour + ", game_min = " + game_min);
	}


        var hour_diff;
        var min_diff;
        var add_time;


	// Are the reference game and input game scheduled for the same day?
        if ( (ref_game_tt == 0 && game_tt == 0) ||
             (ref_game_tt == 1 && game_tt == 1) ) {

		// Is the input game same as reference game
		if (ref_game_hour == game_hour &&
			ref_game_min == game_min) {
			return ref_epoch;
		}

		// Is the reference game scheduled before input game?
                if ((ref_game_hour < game_hour) ||
                    ( ref_game_hour == game_hour &&
                      ref_game_min <= game_min )) {

                        hour_diff = game_hour - ref_game_hour - 1;
                        if (hour_diff <=0)
                                hour_diff = 0;

                        if (hour_diff == 0)
                                min_diff = game_min - ref_game_min;
                        else
                                min_diff = (60 - ref_game_min) + game_min;
                        add_time = true;
                } else {        // reference game scheduled after input game
                        hour_diff = ref_game_hour - game_hour - 1;
                        if (hour_diff <= 0)
                                hour_diff = 0;


                        if (hour_diff == 0)
                                min_diff = Math.abs(ref_game_min - game_min);
                        else
                                min_diff = (60 - game_min) + ref_game_min;

                        add_time = false;
                }
        } else if (ref_game_tt == 0 && game_tt == 1) {
                hour_diff = (24 - (ref_game_hour + 1)) + game_hour;
                min_diff = (60 - ref_game_min) + game_min;
                add_time = true;
        } else if (ref_game_tt == 1 && game_tt == 0) {
                hour_diff = (24 - (game_hour + 1)) + ref_game_hour;
                min_diff = (60 - game_min) + ref_game_min;
                add_time = false;
        }

	if (debug) {
		alert("hour_diff = " + hour_diff + 
				", min_diff = " + min_diff);
	}

	var exp_epoch;
        if (hour_diff || min_diff) {
                var secs_to_adjust = (hour_diff * 60 * 60) + (min_diff * 60);
		if (debug) {
			alert("secs_to_adjust = " + secs_to_adjust + 
					", add_time = " + add_time);
		}
                if (add_time)
                        exp_epoch = parseInt(ref_epoch) + 
					(secs_to_adjust * 1000);
                else
                        exp_epoch = parseInt(ref_epoch) - 
					(secs_to_adjust * 1000);
        } else
                exp_epoch = ref_epoch;

	if (debug) {
		alert("exp_epoch = " + exp_epoch);
	}
	return exp_epoch;
}



function clockInit(form, next_game_date, next_game_time, 
			est_now_date, setNextGameCookie) {
                               // next_game_time in the format [0|1] hh:mm

    var next_game_epoch = getCookie("next_game_epoch");
    var cookie_next_game_time = getCookie("next_game_time");
                                        // in the format [0|1] hh:mm

    var doCalc = false;

    if (!next_game_epoch)  // set epoch cookie is not already set
        doCalc = true;      // calculate and set cookies
    else if (cookie_next_game_time != next_game_time) {
                        // first load of this page with no cookies
                        // set in the browser will have next_game_time = null
                        // and condition will test false
                        // null != next_game_time

                        // when loading this page through back/forward button
                        // next_game_time cookie would have been set
                        // and cookie_next_game_time != next_game_time
			// when clock in some other page had ticked down
			// to zero which cause next_game_time cookie to be
			// updated
 
                        // this condition will be true when
                        // this page is reloaded and the reload brings in
                        // a different next_game_time
        next_game_epoch = extrapolateGameEpoch(
                        next_game_epoch, cookie_next_game_time,
                        next_game_time);

        doCalc = false;
	if (setNextGameCookie) {
        	setCookie("next_game_epoch", next_game_epoch);
        	setCookie("next_game_time", next_game_time);
	}
    }


    if (doCalc) {
        next_game_epoch = next_game_date.getTime();

        var time_request_sent = getCookie("time_request_sent");
        setCookie("time_request_sent", "", new Date());
        var time_response_recvd = (new Date()).getTime();

        var proc_time = form.proc_time.value;
        var elapsed_time =
              (time_response_recvd - time_request_sent - proc_time) / 2;

	// est_now_epoch is the approximate calculation of EST in server
	// now. est_now_date is EST in server when this page was generated.
        var est_now_epoch = est_now_date.getTime() + elapsed_time;


        now_epoch = (new Date()).getTime();

        // find how much time is left for next_game_time and add it to
	// time in local clock(i.e. now_epoch)
        next_game_epoch = now_epoch +
                                (next_game_epoch - est_now_epoch);


	if (setNextGameCookie) {
        	setCookie("next_game_epoch", next_game_epoch);
        	setCookie("next_game_time", next_game_time);
	}
     }

     return next_game_epoch;
}

function getBrowserInfo() {
	var browser = new Object();

	browser.isNetscape = false;
	browser.isMicrosoft = false;

	if (navigator.appName.indexOf("Netscape") != -1)
		browser.isNetscape = true;

	if (navigator.appName.indexOf("Microsoft") != -1)
		browser.isMicrosoft = true;

	return browser;
}

//function clockUpdate(clockElement, next_game_epoch, reloadURL) {
function clockUpdate() {
        var now_epoch = (new Date()).getTime();

        var msecs_to_game = next_game_epoch - now_epoch;

	var msecs_left = msecs_to_game;

	if (msecs_to_game <= 0) 
		msecs_to_game = 0;


        var hours_left = Math.floor(msecs_to_game / (60 * 60 * 1000));
        msecs_to_game = msecs_to_game - (hours_left * 60 * 60 * 1000);

        var minutes_left = Math.floor(msecs_to_game / (60 * 1000) );
        msecs_to_game = msecs_to_game - (minutes_left * (60 * 1000));

        var seconds_left = Math.round(msecs_to_game/1000);

	var browser = getBrowserInfo();

	if (browser.isMicrosoft) {
        	clockElement.value = hours_left + "hr  " +
                                        minutes_left + "min  " +
                                        seconds_left + "secs";
	} else if (browser.isNetscape) {
        	clockElement.value = hours_left + "hr " +
                                        minutes_left + "min " +
                                        seconds_left + "secs";
	}


        if (msecs_left <= 0) {
//		if (reloadURL) 
//                	top.location.replace(reloadURL);
		if (reloadurl)
                	top.location.replace(reloadurl);
		else
			submitForm();
                return;
        }

//	var callBackFunc = function() {
//		clockUpdate( clockElement, next_game_epoch, reloadURL);
//	};

//        setTimeout(callBackFunc, 1 * 1000);
        setTimeout("clockUpdate()", 1 * 1000);

}


function getPrefix() {
  var path = location.pathname;
  var lastSlash = path.lastIndexOf('/');
  var dir = path.substring(0, lastSlash);

  var prefix = location.protocol + "//" + location.host;
  prefix += dir + "/";
  return prefix;
}


function init_clock(form, next_game_date, next_game_time, est_now_date,
			reloadURL, setNextGameCookie) {

//	  next_game_epoch =
//                clockInit(form, next_game_date, next_game_time, est_now_date,
//					setNextGameCookie);

	var serverEpoch = getServerEpoch(server_time);
	var epochDiff = next_game_date.getTime() - serverEpoch;
	next_game_epoch = client_epoch + epochDiff;

	document.getElementById('when_next').innerHTML='&nbsp;&nbsp;'+next_game_time;

	clockElement = form.timeLeft;
	reloadurl = reloadURL;
//        clockUpdate(form.timeLeft, next_game_epoch, reloadURL);
	clockUpdate();

	
	
	return next_game_epoch;
}


function rotateImages() {
        var previous_left_image = document.left_image.src;
        var previous_middle_image = document.middle_image.src;
        var previous_right_image = document.right_image.src;
        var previous_hidden_image = hidden_image.src;

        document.left_image.src = previous_hidden_image;
        document.middle_image.src = previous_left_image;
        document.right_image.src = previous_middle_image;
        hidden_image.src = previous_right_image;

        setTimeout("rotateImages()", 5 * 1000);
}


function getServerDate(server_time, debug) {
	// server_time is in the format 
	//	month day year hour min second
	var values = server_time.split(' ');

	if (debug) {
		alert("server_time = " + server_time);
		var msg = "Date(" + values[2] + 
			  ", " + values[0] + ", " + values[1] +
			  ", " + values[3] + ", " + values[4] +
			  ", " + values[5] + ", 0)";
		alert(msg);
	}

	var serverDate = new Date(values[2], values[0], values[1],	
				values[3], values[4], values[5], 0
	);

	if (debug) {
		alert("server_epoch = " + serverDate.getTime());
	}

	return serverDate;
}	



function getServerEpoch(server_time, debug) {
	// server_time is in the format 
	//	month day year hour min second
	var values = server_time.split(' ');

	if (debug) {
		alert("server_time = " + server_time);
		var msg = "Date(" + values[2] + 
			  ", " + values[0] + ", " + values[1] +
			  ", " + values[3] + ", " + values[4] +
			  ", " + values[5] + ", 0)";
		alert(msg);
	}

	var serverDate = new Date(values[2], values[0], values[1],	
				values[3], values[4], values[5], 0
	);

	if (debug) {
		alert("server_epoch = " + serverDate.getTime());
	}

	return serverDate.getTime();
}	

function getServerTime(serverEpoch) {
	var date = new Date(serverEpoch);
	return date.getMonth() + " " + date.getDate() + " " +
		date.getFullYear() + " " + date.getHours() + " " +
		date.getMinutes() + " " + date.getSeconds() + " " +
		date.getMilliseconds();
}

function printServerTimeNow(server_time, client_epoch) {
        var now_epoch = (new Date()).getTime();
        var epoch_diff = now_epoch - client_epoch;
        var server_epoch = getServerEpoch(server_time) + epoch_diff;

	var serverDate = new Date(server_epoch);
        var month = serverDate.getMonth() + 1;
        var time = month + "/" + serverDate.getDate() + "/";
        time += serverDate.getFullYear() + " " + serverDate.getHours();
        time += ":" + serverDate.getMinutes() + ":";
        time += serverDate.getSeconds() + ":" ;
        time += serverDate.getMilliseconds();

        status = "server time now = " + time;
        setTimeout("printServerTimeNow(\"" + server_time + "\", " +
				client_epoch + ")", 500);
}


  // go over line to add newlines whereever there are more than
  // lineLength characters continuously without newline
  // preserve existing new lines in line

  function addNewLines(line, lineLength) {
	var replacedLine = "";

	// put each char in line into lineArray
	var lineArray = line.split('');

	var currentIndex = 0;
	var currentLineChars = 0;
	var newLineStartIndex = 0;

	var separateLine;

	while (currentIndex < lineArray.length ) {
		// preserve existing newlines
		if (lineArray[currentIndex] == '\n') {
			separateLine = 
				lineArray.slice(newLineStartIndex,
					currentIndex+1).join('');

			replacedLine += separateLine;

			newLineStartIndex = currentIndex + 1;
			currentLineChars = 0;

			currentIndex++;
		} else if (currentLineChars >= lineLength) {
			// go back to end of previous word
			// and make a new line 
			while (lineArray[currentIndex] != ' ' &&
				currentIndex > newLineStartIndex) {
				currentIndex--;
				currentLineChars--;
			}

			if (currentIndex == newLineStartIndex) {
				// no space in current line, break it
				// after 80 chars
				currentIndex += lineLength - 1;
			} 

			separateLine = 
				lineArray.slice(newLineStartIndex,
					currentIndex+1).join('');
			replacedLine += separateLine + '\n';

			newLineStartIndex = currentIndex + 1;
			currentLineChars = 0;

			currentIndex++;
		} else { 
			currentIndex++;
			currentLineChars++;
		}
	}

	var separateLine = lineArray.slice(newLineStartIndex,
					currentIndex+1).join('');
	replacedLine += separateLine;

	return replacedLine;
  }
  function datingPopup (c) {
				window.open(c,
				'comments',
				'width=480,height=480,scrollbars=yes,status=yes');
}

function link_server_time (url) {
	url=url+"?server_time="+escape(server_time) + "&client_epoch=" + escape(client_epoch);
	top.location.href=url;
}
