
//
//  This began as the tutorial from
//   http://luke.breuer.com/tutorial/javascript-drag-and-drop-tutorial.aspx
//
var _startX = 0; // mouse starting positions 
var _startY = 0; 
var _offsetX = 0; // current element offset 
var _offsetY = 0; 
var _dragElement; // needs to be passed from OnMouseDown to Drag 
var _oldZIndex = 0; // we temporarily increase the z-index during drag 
var _debug = $2('debug'); // makes life easier
var debug = 0;
var _fieldposition // will be referenced in multiple places
var _elementvars = null;   // set when a user clicks on a player.  Remains while being dragged
InitDragDrop(); 
//
//
//
function $2(id) { 
//==========================================================
// this is simply a shortcut for the eyes and fingers 
//===========================================================
	return document.getElementById(id); 
}
//
//
//
function BenchStyle(el){
//===========================================
//
//  Style this object back to the bench
//
//===========================================
debugstring(el);
el.style.backgroundColor = 'transparent';
el.style.color = 'black';
}
//===========================================
//
//
//
//
function debugstring(string){
//============================================
//
//  Sets the debug innHTML to the string
//
//============================================
if(debug){
	$2('debug').innerHTML = string;
}
}
//============================================
//
//
//
function DebugNumbers(debugoutput){
//========================================+
//  This function Hides the debug table
//========================================+
var el = $2('hidden');
el.innerHTML = debugoutput;
}
//========================================+
//
//
//
//
function Drag(e) { 
//========================================================
//
// When a player has clicked on an object with the "drag" class then this code is called
//
//
//========================================================
	if (e == null) var e = window.event; 
	if(debug){
		$2('mousex').innerHTML = e.clientX;
		$2('mousey').innerHTML = e.clientY;
	}
	// this is the actual "drag code" 
	var currentx = _offsetX + e.clientX - _startX;
	var currenty = _offsetY + e.clientY - _startY;
	_dragElement.style.left = (currentx) + 'px'; 
	_dragElement.style.top = (currenty) + 'px'; 
	//
	//  This collects the current dimensions of the object being dragged
	//
	var currentpos = GetObjDimensions(_elementvars['id']);
}
//
//
//
function GetObjDimensions(objectid){
//==========================================
//  Takes an objectid and returns an array of the top right and top left
//
//==========================================
if(debug){
	$2('lastfunction').innerHTML = 'GetObjDimensions';
}

coords= new Object;
el=$2(objectid);
coords.height = el.offsetHeight;
coords.width = el.offsetWidth;
var curleft = 0;
var curtop = 0;
if(el.offsetParent){
	do{
		 curleft += el.offsetLeft;
		 curtop += el.offsetTop;
	} while ( el = el.offsetParent);
}
coords.leftx = curleft;
coords.topy = curtop;
coords.rightx =  curleft + coords.width;
coords.bottomy = curtop + coords.height;
return coords;
}
//
//  We have to use this function to initiate this global, so we cannot load it until
//  after it's called
//
//
//
function InitDragDrop() { 
//======================================================
//
//  Initializes drag and drop
//
//======================================================
	document.onmousedown = OnMouseDown; 
	document.onmouseup = OnMouseUp; 
	document.onmousemove = MouseMove;
}
//
//
//
function ExtractNumber(value) { 
//=========================================================
//  This function extracts a number from a value;
//=========================================================

	var n = parseInt(value); 
	return n == null || isNaN(n) ? 0 : n; 
} 
//
//
//
////

//===================================================
function MouseDownPlayer(set){
//==========================================================
//
//  Called when the user clicks the mousedown
//
//==========================================================
 if(e) {e.preventDefault();}
if(debug){
	$2('lastfunction').innerHTML = 'MouseDownPlayer';
}
}
//==========================================================
//
function MouseMove(e){
//==========================================================
//  This function is always called, except when an item is being dragged
//==========================================================

if (e == null) {
	e = window.event; 
}
if(debug){
	$2('mousex').innerHTML = e.clientX;
	$2('mousey').innerHTML = e.clientY;
}
}
//==========================================================
//
//
function MouseOutPlayer(set){
//===============================================
//
//  This function is triggered when the user mouses out of player on the bench
//
//===============================================
document.body.style.cursor='auto';
currentpos = GetObjDimensions(set['id']);
el = $2(set['id']);
if(PositionedOver(currentpos, _fieldposition)){
	OverFieldStyle(el);
} else {
	BenchStyle(el);
}
}
//=====================================
//
//
//
function MouseOverPlayer(set){
//===============================================
//
//  This function is triggered when the user mouses over a player
//
//===============================================
debugstring('Mouse Over Player Begins');
_elementvars = set;
document.body.style.cursor='move';
currentpos = GetObjDimensions(set['id']);
RefreshFieldPosition();
el = $2(set['id']);
el.previouscolor = el.style.color;
el.style.backgroundColor = '#eeeeee';
$2(set['id']).style.color = 'black';
debugstring('Mouse Over Player End');
}
//===============================================
//
//
//
//
function MouseUpPlayer(set){
//===============================================
//
//  This function is triggered when the user mouses over a player on the bench
//
//===============================================
if(debug){
	$2('lastfunction').innerHTML = 'Mouse Up Player';
}
var newposition = GetObjDimensions(set['id']);
if(debug){
	$2('fieldleftx').innerHTML = _fieldposition.leftx;
	$2('fieldrightx').innerHTML = _fieldposition.rightx;
	$2('fieldtopy').innerHTML = _fieldposition.topy;
	$2('fieldbottomy').innerHTML = _fieldposition.bottomy;
	$2('fieldheight').innerHTML = _fieldposition.height;
	$2('fieldwidth').innerHTML = _fieldposition.width;

}

RefreshFieldPosition();

if(!PositionedOver(newposition, _fieldposition)){
	_dragElement.style.position = 'inherit';
	_dragElement.style.left=0;
	_dragElement.style.top=0;
	_dragElement.style.position = 'relative';
	_dragElement.style.color = 'black';
} else {
	OverFieldStyle(_dragElement);	
}
UpdateInput(set);
}
//===============================================
//
//
//
function OnMouseDown(e) { 
//====================================
//   This fires every time the mouse is clicked
//====================================
	// IE is retarded and doesn't pass the event object 
	if (e == null) {
		e = window.event; 
	}
	// IE uses srcElement, others use target 
	var target = e.target != null ? e.target : e.srcElement;
	if(debug){
		$2('clickx').innerHTML = e.clientX;
		$2('clicky').innerHTML = e.clientY;
	}
//	e.preventDefault();
//	_debug.innerHTML = target.className == 'drag' 
//		? 'draggable element clicked' 
//		: 'NON-draggable element clicked'; 
		// for IE, left click == 1 
		// for Firefox, left click == 0 
		if ((e.button == 1 && window.event != null || e.button == 0) && target.className == 'drag') { 
				// grab the mouse position 
			_startX = e.clientX; 
			_startY = e.clientY; 
			//
			// grab the clicked element's position 
			//
			_offsetX = ExtractNumber(target.style.left); 
			_offsetY = ExtractNumber(target.style.top); 
			// bring the clicked element to the front while it is being dragged 
			_oldZIndex = target.style.zIndex; 
			target.style.zIndex = 10000; 
			//
			// we need to access the element in Drag 
			_dragElement = target; 
			// tell our code to start moving the element with the mouse 
			document.onmousemove = Drag; 
			// cancel out any text selections 
			document.body.focus(); 
			// prevent text selection in IE 
			document.onselectstart = function () { return false; }; 
			// prevent IE from trying to drag an image 
			target.ondragstart = function() { return false; }; 
			// prevent text selection (except IE) 
			return false; 
		} 
}
//
//
//

//
function OnMouseUp(e) { 	
//======================================================
//
//  This is called as the mouse goes up.
//
//======================================================
document.onmousemove = MouseMove; 
if (_dragElement != null) { _dragElement.style.zIndex = _oldZIndex; 
	// we're done with these events until the next OnMouseDown 
	document.onselectstart = null; 
	_dragElement.ondragstart = null; 
	// this is how we know we're not dragging 
	_dragElement = null; 
	_debug.innerHTML = 'mouse up'; 
}
_fieldpostion = GetObjDimension('field'); 
}
function OverFieldStyle(obj){
//====================================================
//
//  set _dragElement equal to the over field style
//
//====================================================
	obj.style.color='white';
	obj.style.backgroundColor = 'transparent';
	RefreshFieldPosition();
	var left = ExtractNumber(obj.style.left) + 'px';
}
//====================================================
function PositionedOver(Object, Container){
//=======================================================
//
//  if the Object is over the Container then it returns true
//
//=======================================================
if(debug){
	$2('lastfunction').innerHTML = 'PositionedOver';
}
if(
		Object.leftx>Container.leftx
			&&
		Object.rightx<Container.rightx
			&&
		Object.topy>Container.topy
			&&
		Object.bottomy<Container.bottomy
			
	){
	return true;
} else {

	return false;
}
//=======================================================
}
//
function RefreshFieldPosition(){
//=======================================================
//  Update the _fieldposition global
//
//=======================================================
debugstring('Refresh Field Position begins');
_fieldposition = GetObjDimensions('field');
debugstring('after GetObjDimension in RFP');
//alert(fieldinput);
var fieldinput;
fieldinput = $2('fieldinput');
debugstring('after fieldinput chosen');
fieldinput.value = _fieldposition.leftx + ',' + _fieldposition.topy + ',' + _fieldposition.rightx +  ',' + _fieldposition.bottomy;
debugstring('Refresh field position: ' + fieldinput.value);
}
//=======================================================
//
//
function RestorePosition(set){
//=======================================================
//
//  Someone has submitted the form to make a picture or whatnot.  Therefore,
//	 we know where they had the picture.  Lets put it back where it was before
//  the refresh
//
//=======================================================
debugstring('restorepostion');
RefreshFieldPosition();
el = $2(set['id']);
debugstring(el);
el.style.position  = 'absolute';
el.style.left = set['leftx'];
el.style.top = set['topy'];
OverFieldStyle(el);
UpdateInput(set);
debugstring('Restore Position:' + set['leftx'] + ', ' + set['topy']);
}
//=======================================================
//
//
function UpdateInput(set){
//=======================================================
//
//  We've moved the player, so lets update the input form
//
//  We're going to pass a series of commas that will be exploded on the 
//  otherside to get different information  We will pass
//
//   As a reminder, offset is the difference between where the original position 
//   and where the image has been moved to.
//  
//  "leftx, topy, offsetx, offsety"
//
//
//=======================================================
//
//  First, get the object
//
playerobj = $2(set['id']);
//
//  Lets find its absolutes
//
//
//  read it into a string for debugging
//
currentpos = GetObjDimensions(set['id']);
var inputvalue = playerobj.offsetLeft + ',' + playerobj.offsetTop;
inputobject = $2('input' + set['key']);
debugstring(inputvalue);
if(PositionedOver(currentpos, _fieldposition)){
	inputobject.value = inputvalue;
} else {
	inputobject.value = "";
}

}
//=======================================================
//
//
