/*************************************************************
 * Magnetic AJAX - Version 1.9
 * (C) 2005 - Garrison Locke
 *
 * This is like the magnetic poetry things. If you use this
 * code, please give me credit and a link to my site would be nice.
 * http://www.broken-notebook.com.
 *
 * Copyright (c) 2005, Garrison Locke
 * All rights reserved.
 *
 * Portions (c) 2006, Nathan Blume
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the documentation
 *     and/or other materials provided with the distribution.
 *   * Neither the name of the http://www.broken-notebook.com nor the names of its
 *     contributors may be used to endorse or promote products derived from this
 *     software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 *
 *************************************************************/

var currentlyHeldTile = "";
var globalX = 0;
var globalY = 0;
var waitingTile = "";
var timedOut = false;
var startTime = 0;
var interval, s=7;

function initTiles(){
	for(i=1; i<=numWords; i++){
		var currentTile = document.getElementById("w_" + i);
		var x1 = parseInt(document.getElementById("board").style.left) - 2;
		var x2 = parseInt(document.getElementById("board").style.width) - parseInt(currentTile.style.width) - 6;
		var y1 = parseInt(document.getElementById("board").style.top);
		var y2 = parseInt(document.getElementById("board").style.height) - parseInt(currentTile.style.height) - 6;
		Drag.init(currentTile, null, x1, x2, y1, y2);
		currentTile.onDragStart = function(x,y) { dragStart(this.id, x, y); };
		currentTile.onDragEnd = function(x,y) { dragEnd(this.id, x, y); };
		if(currentTile.className == "multiTile") currentTile.ondblclick = function() { changeTense(this.id); };
	}
};

function dragStart(obj, x, y) {
	currentlyHeldTile = obj;
	globalX = x;
	globalY = y;
};

function dragEnd(obj, x, y) {
	currentlyHeldTile = "";
	if(globalX != x || globalY != y)
		cpaint_call('magnetic-ajax.php', 'POST', 'saveTileLocation', obj, x, y, saveTileLocation_cb);
	resetTimeout();
};

function changeTense(tileID) {
	obj = document.getElementById(tileID);
	oldState = obj.getAttribute("multi");
	tileID = tileID.substr(2)-1;
    if(oldState == multiWords[tileID].length){
    	newText = multiWords[tileID][0];
		newState = "1";
    }else{
    	newText = multiWords[tileID][oldState];
   		newState = parseInt(oldState)+1;
    }
    obj.innerHTML = newText;
    obj.setAttribute("multi",newState);
    obj.style.width = newText.length * 7;
	cpaint_call('magnetic-ajax.php', 'POST', 'changeTense', tileID, newState, changeTense_cb);
};

function changeTense_cb(returnedData) {
	//alert(returnedData);
};

function saveTileLocation_cb(returnedData) {
	//alert(returnedData);
};

function updateCounter(){
	cpaint_call('magnetic-ajax.php', 'POST', 'readCounter', null, updateCounter_cb);
};

function updateCounter_cb(returnedData){
	if(returnedData.length > 0){
		document.getElementById("counter").innerHTML = returnedData;
	}
	if(timedOut == true){
		document.getElementById("counter").innerHTML = "Session timed out";
	}
};

function updatePositions(){
	cpaint_call('magnetic-ajax.php', 'POST', 'repaintBoard', null, repaintBoard_cb);
  	setTimeout("updateCounter()",4000);
};

function repaintBoard_cb(returnedData){
	lines = returnedData.split("|");
		for(i=0; i<numWords; i++){
			if(lines[i]!=null){
				lines[i] = lines[i].split(":");
				wordID = i+1;
				if("w_" + wordID != currentlyHeldTile){
					if(lines[i][2] != 0){
					    obj = document.getElementById("w_" + wordID);
					    try{
						if(obj.getAttribute("multi") != lines[i][2]){
						    obj.setAttribute("multi",lines[i][2]);
							obj.innerHTML = multiWords[wordID-1][parseInt(lines[i][2])-1];
						    obj.style.width = multiWords[wordID-1][parseInt(lines[i][2])-1].length * 7;
						}
						}
						catch(e){
						    alert(e + "\n" + multiWords[wordID-1][lines[i][2]]);
						}
					}
					if(parseInt(document.getElementById("w_" + wordID).style.top) != lines[i][0] || parseInt(document.getElementById("w_" + wordID).style.left) != lines[i][1]){
						startMove("w_" + wordID,lines[i][1],lines[i][0]);
						//document.getElementById("w_" + wordID).style.top = lines[i][0] + "px";
						//document.getElementById("w_" + wordID).style.left = lines[i][1] + "px";
					}
				}
			}
		}
};

// smooth move functions by Nathan Blume for poetry.detrave.net
function startMove(elemId,endX,endY){
	var elem = document.getElementById(elemId);
	var curX = elem.style.left.substr(0,elem.style.left.length-2);
	var curY = elem.style.top.substr(0,elem.style.top.length-2);
	var disX = parseInt(endX - curX);
	var disY = parseInt(endY - curY);
	var stepY = disY / 10;
	var stepX = disX / 10;
	var dirX = (disX < 0) ? 0 : 1;
	var dirY = (disY < 0) ? 0 : 1;
	smoothMove(elemId,endX,endY,stepY,stepX,dirX,dirY,0);
};
function smoothMove(elemId,endX,endY,stepY,stepX,dirX,dirY,cnt){
	if(endX && endY){
		var elem = document.getElementById(elemId);
		var curX = parseInt(elem.style.left.substr(0,elem.style.left.length-2));
		var curY = parseInt(elem.style.top.substr(0,elem.style.top.length-2));
		if(cnt < 10){
			elem.style.left = curX+stepX+"px";
			elem.style.top = curY+stepY+"px";
			setTimeout("smoothMove('"+elemId+"',"+endX+","+endY+","+stepY+","+stepX+","+dirX+","+dirY+","+(++cnt)+")",25);
		}else{
			elem.style.left = endX+"px";
			elem.style.top = endY+"px";
		}
	}
};
// end NB

function countdown() {
	if(s==0){
		updatePositions();
		watchTimeout();
		s = 5;
		return;
	}
	s-=1;
};

function watchTimeout() {
	if(startTime == 0){
		var d = new Date();
		startTime = d.getTime();
	}else{
		var d = new Date();
		if(d.getTime() - startTime > 900000){
			timedOut = true;
			clearInterval(interval);
		}
	}
};

function resetTimeout() {
	var d = new Date();
	startTime = d.getTime();
	if(timedOut == true){
		initTiles();
		startTimer();
	}
};

function startTimer(){
	interval=setInterval('countdown();',1000);
};
