
/* INITIALIZATION
----------------------------------*/

var wordArray, wordIndex=0, defaut_speed=12, speed_multip=defaut_speed, pauseSpeed=16, timeOutID, debug, paused=true, play_pause_button, text_area_focused=false;
var sliderEnd = 400-30


function update_text(dontStartPlay) {
	clearTimeout(timeOutID)
	initWordArray();
	wordIndex=0
	
	word_previous = document.getElementById("previous")
	word_now = document.getElementById("now")
	word_next = document.getElementById("next")
	debug = document.getElementById("debug")
	if (!dontStartPlay) play()
	else initWord()
}

/* INIT WORDS
----------------------------------*/
function initWordArray() {
	wordArray = new Array();
	tempArray = document.getElementById("new_text_box").value.split(/ |\n/);
	var punctuation_mark, punctuation_delay
	for (var i=0; i < tempArray.length; i++) {
		if (tempArray[i] == "") {
			wordArray.push(["", 7]) // paragraph break
			continue
		}
		punctuation_mark = ""
		var last_char = tempArray[i].charAt(tempArray[i].length-1)
		if (last_char=='.' || last_char=='!' || last_char==',') {
			punctuation_mark = tempArray[i].charAt(tempArray[i].length-1)
			punctuation_delay = (last_char=='.' || last_char=='!') ? 8 : 6
			tempArray[i] = tempArray[i].substr(0,tempArray[i].length-1)
		}
		
		//var prev_length = tempArray[i-1] ? tempArray[i-1].length : 0
		//var next_length = tempArray[i+1] ? tempArray[i+1].length : 0
		var word_length_time = tempArray[i].length //3* + prev_length // + next_length
		
		wordArray.push([tempArray[i], word_length_time])
		
		if (punctuation_mark != "") {
			wordArray.push([punctuation_mark, punctuation_delay])
		}
	}
}

function initWord() {
	clearTimeout(timeOutID)
	
	// update words (and check minimum width for main word):
	if (wordArray[wordIndex][0] == "") {
		word_previous.innerHTML = word_now.innerHTML = word_next.innerHTML = ""
	}
	else {
		word_previous.innerHTML = (wordArray[wordIndex-2] ? wordArray[wordIndex-2][0] : "") + " " + (wordArray[wordIndex-1] ? wordArray[wordIndex-1][0] : "")
		word_next.innerHTML = (wordArray[wordIndex+1] ? wordArray[wordIndex+1][0] : "") + " " + (wordArray[wordIndex+2] ? wordArray[wordIndex+2][0] : "")
		word_now.style.width = ""
		word_now.innerHTML = wordArray[wordIndex][0]
		word_now.style.width = word_now.offsetWidth < 50 ? "50px" : word_now.offsetWidth + "px"
	}
	// update slider position:
	var slider = document.getElementById("slider")
	var offsetLeft = (wordIndex * sliderEnd / (wordArray.length-1)) | 0
	slider.style.left = offsetLeft + "px";
	
	// update word positions:
	//word_now.offsetWidth = 100
	margin = 15
	now_start = (document.body.clientWidth/2 - word_now.offsetWidth/2)
	word_previous.style.left = now_start - margin - word_previous.offsetWidth + 'px'
	word_now.style.left = now_start + 'px'
	word_next.style.left = now_start + word_now.offsetWidth + margin + 'px'
	
	if (!paused) nextWord(true)
}

function nextWord() {
	// calculate delay and set timeout for next word
	var speed = speed_multip < pauseSpeed ? speed_multip : (2*pauseSpeed-speed_multip <= 1 ? 1 : 2*pauseSpeed-speed_multip)
	var time_ms = speed * (20 + 3*wordArray[wordIndex][1]) // defaut delay for all words + length bonus
	timeOutID = setTimeout("initWord(false);", time_ms);
	
	// change to next index (backwards if speed multiplyer > pauseSpeed)
	if (speed_multip < pauseSpeed)
		wordIndex = wordIndex >= wordArray.length-1 ? wordArray.length-1 : wordIndex+1
	else if (speed_multip > pauseSpeed)
		wordIndex = wordIndex <= 0 ? 0 : wordIndex-1
	
// 	debug.innerHTML = "wordArray.length:"+wordArray.length+" time:"+time_ms
}


/* PLAY / PAUSE
---------------------------------------*/

function playPauseButton() {
	if (paused) play();
	else pause();
}

function play() {
// 	if (wordArray==undefined) { update_text(); return; }
	play_pause_button.src = "pause_button.gif"
	paused = false
	if (speed_multip == pauseSpeed) speed_multip = default_speed
	initWord()
}

function pause() {
// 	clearTimeout(timeOutID)
	play_pause_button.src = "play_button.gif"
	paused = true
}


/* WINDOW LOAD
---------------------------------------*/

window.onload = window.onresize = function() {
	//var ball = document.getElementById("red_ball")
	//ball.style.left = (document.body.clientWidth/2 - ball.offsetWidth/2)+"px"
	hookEvent("scrollContent", "mousewheel", speedModifier);
	// set events on html:
	play_pause_button = document.getElementById("play_pause_button")
	play_pause_button.onclick = playPauseButton
	document.getElementById("speed_down_button").onclick = speedDown
	document.getElementById("speed_up_button").onclick = speedUp
	update_text(true)
	updateWordsPerMinute()
	
	var textArea = document.getElementById("new_text_box")
	textArea.onfocus = function() {
		text_area_focused = true;
	};
  textArea.onblur = function() {
		text_area_focused = false;
	};
}


/* KEY PRESSED
-------------------------------------*/

document.onkeypress = function() {
	if (!text_area_focused) {
		playPauseButton()
		return false
	}
}



/* TEXT SPEED
---------------------------------------*/

function speedUp() {
	speed_multip -= speed_multip <= 6 ? 1 : 2
	if (speed_multip < 1) speed_multip = 1
	updateWordsPerMinute()
}
function speedDown() {
	speed_multip += speed_multip < 6 ? 1 : 2
	if (speed_multip > 2*pauseSpeed) speed_multip = 2*pauseSpeed
	updateWordsPerMinute()
}

function updateWordsPerMinute() {
	var speed, speed_info = document.getElementById("speed_info")
	if (speed_multip < pauseSpeed) {
		speed = speed_multip
		word_now.style.color="black"
		speed_info.style.color="black"
	}
	else if (speed_multip == pauseSpeed) {
		speed = 0
		word_now.style.color="black"
		speed_info.style.color="black"
	}
	else { // speed_multip > pauseSpeed
		speed = (2*pauseSpeed-speed_multip <= 1 ? 1 : 2*pauseSpeed-speed_multip)
		word_now.style.color="red"
		speed_info.style.color="red"
	}

	var time_ms = speed * (20 + 3*5) // lenght of average word = 4,5
	var wordsPerMinute = (60000/time_ms) | 0
	speed_info.innerHTML = "~ "+wordsPerMinute+" w/min"
}

/* MOUSE WHEEL
-------------------------------------------------------------*/

function hookEvent(element, eventName, callback)
{
  if(typeof(element) == "string") element = document.getElementById(element);
  if(element == null)
    return;
  if(element.addEventListener)
  {
    if(eventName == 'mousewheel') {
      element.addEventListener('DOMMouseScroll', callback, false);  
    }
    element.addEventListener(eventName, callback, false);
  }
  else if(element.attachEvent)
    element.attachEvent("on" + eventName, callback);
}

function cancelEvent(e)
{
  e = e ? e : window.event;
  if(e.stopPropagation)
    e.stopPropagation();
  if(e.preventDefault)
    e.preventDefault();
  e.cancelBubble = true;
  e.cancel = true;
  e.returnValue = false;
  return false;
}

function speedModifier(e)
{
  e = e ? e : window.event;
  var wheelData = e.detail ? e.detail * -1 : e.wheelDelta / 40;
	
	var startAfter = (speed_multip==pauseSpeed)
	
	var direction = wheelData / 3
	if (direction > 0) speedUp()
	else speedDown()
	
	if (speed_multip==pauseSpeed) pause()
	else if (startAfter) play()
	
  return cancelEvent(e);
}




/* SLIDER DRAG
------------------------------------------------------------*/

function isIE() {
 	if (navigator.userAgent.indexOf("MSIE") >= 0) return true;
  else return false;
}

var dragObj = new Object();
dragObj.zIndex = 0;

function dragStart(event) {

	if (wordArray==undefined) return;
	pause()
	
  var el;
  var x, y;

  if (isIE()) {
    dragObj.elNode = window.event.srcElement;
    x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
  }
  else {
  	dragObj.elNode = event.target;
    x = event.clientX + window.scrollX;
  }

	dragObj.cursorStartX = x;
  dragObj.elStartLeft  = parseInt(dragObj.elNode.style.left, 10);

  if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
	
	// Update element's z-index.
	dragObj.elNode.style.zIndex = ++dragObj.zIndex;
	
	// Capture mousemove and mouseup events on the page.
	if (isIE()) {
		document.attachEvent("onmousemove", dragGo);
		document.attachEvent("onmouseup",   dragStop);
		window.event.cancelBubble = true;
		window.event.returnValue = false;
	}
	else {
    document.addEventListener("mousemove", dragGo,   true);
    document.addEventListener("mouseup",   dragStop, true);
    event.preventDefault();
  }
}

function dragGo(event) {

  var x, y;

  // Get cursor position with respect to the page.
	if (isIE()) {
    x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  else {
    x = event.clientX + window.scrollX;
    event.preventDefault();
  }

	// Move drag element by the same amount the cursor has moved.
	var pos = dragObj.elStartLeft + x - dragObj.cursorStartX
	pos = pos < 0 ? 0 : pos
	pos = pos > sliderEnd ? sliderEnd : pos // slider
  wordIndex = ((wordArray.length-1) * pos / sliderEnd) | 0
  initWord()
  
  //debug.innerHTML = "wordArray.length"+wordArray.length +"  wordInd: "+wordIndex
}

function dragStop(event) {

  // Stop capturing mousemove and mouseup events.
  if (isIE()) {
    document.detachEvent("onmousemove", dragGo);
    document.detachEvent("onmouseup",   dragStop);
  }
  else {
    document.removeEventListener("mousemove", dragGo,   true);
    document.removeEventListener("mouseup",   dragStop, true);
  }
	play()
}
