var _startX = 0;            // mouse starting positions
var _startY = 0;
var _offsetX = 0;           // current element offset
var _offsetY = 0;

// Three variables that will be used as quick references to properties of the currently dragged object.

var _object;	// stores the currently dragged object.
var _id;		// stores the ID of the currently dragged object.
var _class;		// stores the Class Names of the currently dragged object.

var offsetX;
var trashHover = 0;

var _currentZIndex = 5;
var _dragTopLeft = 0;
var _dragTopRight = 0;
var _dragBottomLeft = 0;
var _dragBottomRight = 0;

var _DIVwidth = 100;
var _DIVheight = 30;

var _oldClass;	// temporarily stores the Class names of the currently dragged element
var _defaultClassMainWidget = "widg_main"; // default class for main widgets.

var content;

var factor;
var file;

var currentPageString = "";
var pageCountID = "";

var temp;	// Used for any temporary data;
var temp2;	// Used for any temporary data;

// Preloading images

_imgTrashOvr = new Image(100,110);	_imgTrashOvr.src = "gfx/trashcan_hover.png";
_imgTrashOut = new Image(100,110);	_imgTrashOut.src = "gfx/trashcan.png";

window.onload = function() {
	setShortHands();	// Will set short hands for frequently used objects.
	initAll();			// Initializes or recalculates values for global variables.
}

/* setShortHands
This function runs onLoad and sets all global short hands for frequently used objects.
*/
function setShortHands() {
	trashcan = document.getElementById("trashcan");
	shopping = document.getElementById("shopping");
	pricetag = document.getElementById("pricetag");
	shadow = document.getElementById("shadow");

	document.onmousedown = OnMouseDown;
	document.onmouseup = OnMouseUp;
}

function initAll() {
// Set variables that holds the browser area dimensions;
	_pageWidth = document.documentElement.clientWidth;
	_pageHeight = document.documentElement.clientHeight;

	// Since Opera handles things a little different when it comes to the document height we need to replace the height value;
	if (navigator.appName == "Opera") { _pageHeight = document.body.clientHeight; }

// Move the Trashcan to the bottom right corner of the Shopping Floor;
	tcTop = _pageHeight - (trashcan.offsetHeight) - 80;
	tcLeft = _pageWidth - (trashcan.clientWidth+10);

	trashcan.style.top = tcTop + "px";
	trashcan.style.left = tcLeft + "px";

// Move the Shopping Cart to the upper right corner of the Shopping Floor;
	scTop  = 30;
	scLeft = _pageWidth - (shopping.clientWidth+10);
	scBottom = scTop + shopping.offsetHeight;

	shopping.style.top = scTop + "px";
	shopping.style.left = scLeft + "px";

// Move PRICE TAG to below the SHOPPING CART
	ptTop = scTop + shopping.clientHeight;
	ptLeft = scLeft;
	
	pricetag.style.top = ptTop-20 + "px";
	pricetag.style.left = ptLeft-10 + "px";

// Calculate the SAFE ZONE
	safeZone = _pageWidth-120;

// Position the function bar
	var funcbar = document.getElementById("area_topp_menu");
	
	funcbar.style.left = _pageWidth-650 + "px";
	funcbar.style.display = "block";

// Position bottom edge

	document.getElementById("edgeBottom").style.top = _pageHeight-10 + "px";
	document.getElementById("edgeRight").style.left = _pageWidth-10 + "px";
}

function OnMouseDown(e) {
	// IE is different 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;

	// for IE, left click == 1
	// for Firefox, left click == 0

	if (target.id == "slideHandle") {
		sliding = 1;
		document.onmousemove = adjustPage;
		document.body.focus();
		document.onselectstart = function () { return false; };
		return false;
	}
	
	if (target.id.substr(0,5) == "pages") {
		currentPageString = target.innerHTML;
		document.getElementById("slideHandle").style.left = "190px";
		pageCountID = target.id;
		selectPage(target.id,target.className);
	}
	
	if (target.id.substr(0,5) == "func_") {
		fIcon = document.getElementById("functionIcon");
		fRefl = document.getElementById("functionShadow");
		fIcon.className = fIcon.className + " " + target.className;
		fIcon.style.backgroundImage = "url('gfx/" + target.id.substr(5) + ".png')";
		fRefl.style.backgroundImage = "url('gfx/" + target.id.substr(5) + ".png')";

		var widgets = document.getElementsByTagName("DIV");
		widgetArray.length = 0;
		
		var counter = 0;
		for (var i=0; i<widgets.length; i++) {
			if (checkForClass(widgets[i],"widget") && widgets[i].style.display == "block") {
				widgetArray[counter] = widgets[i];
				counter++;
			}	
		}

		document.onmousemove = moveFunction;
		document.body.focus();
		document.onselectstart = function () { return false; };
		return false;
	}
	
	if (icon != "empty") {
		document.onmousemove = moveItem;
		document.body.focus();
		document.onselectstart = function () { return false; };
		return false;
	}
	
	if (dragItem != "nothing") {
		document.onmousemove = moveInfo;
		document.body.focus();
		document.onselectstart = function () { return false; };
		return false;	
	}
	
	if ((e.button == 1 && window.event != null || e.button == 0) && target.id.substr(0,4) == 'drag') { // all dragable elements need to have an ID that starts with the letters "drag";

	// grab the mouse position

	_startX = e.clientX;
	_startY = e.clientY;

	// grab the clicked element's position

	_offsetX = parseInt(target.style.left);
	_offsetY = parseInt(target.style.top);

	setPosition(shadow,_offsetX+4,_offsetY+4);

	// increase the z-index of the element that's being dragged. This will always bring the latest dragged element to the top.

	_currentZIndex++;
	target.style.zIndex = _currentZIndex;
	shadow.style.zIndex = _currentZIndex;
        
	// we need to access the element in OnMouseMove

	_object = target;
	_id = _object.id;
	_class = _object.className;

	// extract file name information from the dragged element.

	file = _id.substr(5);			// Grab the ID of the button, including the order number ....
	file = removeNumbers(file);		// ... get rid of the order number ...
	file = file.replace(" ","");	// ... as well as any spaces in the name ...
	file = file.toLowerCase();		// ... and turn the whole name into small caps ...
		
	factor = removeLetters(_id);	// Grab the order number from the ID.

	// Associate the "content"-variable to the DIV associated with the currently dragged 
	
	content = document.getElementById("drag_" + file);

	// tell our code to start moving the element with the mouse

	document.onmousemove = OnMouseMove;
        
	// cancel out any text selections

	document.body.focus();

	// prevent text selection in IE

	document.onselectstart = function () { return false; };

	// prevent text selection (except IE)

	return false;

	}

}

function OnMouseMove(e) {

	if (e == null) { var e = window.event; }

	if (!checkForClass(_object,"transparent")) {
		_class += " transparent";
		_object.className = _class;
	}
	
	// this is the actual "drag code"

	var posX = _offsetX + e.clientX - _startX;
	var posY = _offsetY + e.clientY - _startY;
	
	setPosition(_object,posX,posY)
	
	temp = document.getElementById("area_menu").clientHeight-10;	// store the coordinates of the menu bar
	
	// Test if the dragged object is over the menu bar.

	if (findMenu(posY)) {
		if (shadow.style.display == "block") { shadow.style.display = "none"; }	// Hide shadow;
		
		if (checkForClass(_object,"floor")) {
			temp = removeNumbers(_object.id) + findIndex(_object);	// construct the ID of the button and store it in "temp".
			
			_object.style.display = "none";
			_object = document.getElementById(temp);
			_object.style.display = "block";

			_class = _class.replace(" widget"," button");
			_object.className = _class;
		}

	} else {

		if (!checkForClass(_object,"floor")) {
			_class += " floor";
			_object.className = _class;
		}

		if (checkForClass(_object,"shadow")) {
			setSize(shadow,350,460)
			shadow.style.display = "block";
			mimicObject(_object,shadow);
		}
		
		if (checkForClass(_object,"button") && !checkForClass(_object,"shadow")) {
			temp = removeNumbers(_object.id);	// construct the ID of the widget and store it in "temp".

			mimicObject(_object,document.getElementById(temp));
			
			_object.style.display = "none";
			_object = document.getElementById(temp);

			_class = _class.replace(" button"," widget");
			_object.className = _class;
			_object.style.display = "block";
		}

		// Compare mouse position with the trashcan position;
		if (findTrashcan(e) && !checkForClass(_object,"button")) { hoverTrashcan(1); } else { hoverTrashcan(0); }
	}

	// store position of each corner of the dragged element into global variables.

	if (shadow.style.display == "block") { offsetX = shadow.offsetWidth; }
	else if (content.style.display == "block") { offsetX = content.offsetWidth; }
	
	_dragTopLeft = parseInt(_object.style.top);
	_dragTopRight = parseInt(_object.style.left) + offsetX ;
	_dragBottomLeft = parseInt(_object.style.left);
	_dragBottomRight = parseInt(_object.style.top) + _DIVheight + 70;

	// Prevent element from being dragged over the menu area;
		if (_dragTopLeft <= 0) {
			setPosition(_object,"","0");
			setPosition(shadow,"","0");
		}
	// Prevent element from being dragged off the right edge of the Shopping Floor.
		if (_dragTopRight >= _pageWidth) {

			temp = _pageWidth-offsetX;

			setPosition(_object,temp,"");
			setPosition(shadow,temp,"");
			setPosition(content,temp,"");
		}
	// Prevent element from being dragged off the left edge of the Shopping Floor.
		if (_dragBottomLeft <= 0) {
			setPosition(_object,"0","");
			setPosition(shadow,"0","");
		}
	// Prevent element from being dragged off the bottom edge of the Shopping Floor. The formula grabs the height of both the menu and the widget-bars.
		if (_dragBottomRight >= _pageHeight) {
			temp = _pageHeight-(document.getElementById("area_topp").clientHeight + document.getElementById("area_menu").clientHeight)+10;

			setPosition(_object,"",temp);
			setPosition(shadow,"",temp);
		}
}

function OnMouseUp(e) {

	if (sliding == 1) { releaseSlider(e); }
	if (fIcon != "none") { releaseFunction(e); }
	if (icon != "empty") { releaseItem(e); }
	if (dragItem != "nothing") { releaseInfo(e); }

	if (_object != null) {

	// Test if the dragged element is within the widget-bar area. If it is it will be docked using an animation function;

		temp2 = removeNumbers(_object.id) + findIndex(_object);	// construct the ID of the button and store it in "temp2".
		factor = removeLetters(temp2);

		_class = _class.replace(" transparent","");		// Remove the "transparent"-class from the dragged object;
		_object.className = _class;

		temp = document.getElementById("area_menu").clientHeight+15;

// Test if the dragged object was dropped on top of the menu bar:
		if (_dragTopLeft < temp) {

			_class = _class.replace(" floor","");
			_class += " shadow";
			_object.className = _class;
		
			setPosition(_object,"","0");

			if (file == "search") { document.getElementById("searchHint").innerHTML = "-widget needed"; }

			var startPos = getNum(_object.style.left);
			var stoppPos = 10+105*factor;							// Calculate the stopp position. Each main widget is 100 pixels wide.
			
			tweenButton(startPos,stoppPos,temp2);

		} else {

			// Remove the "shadow"-class from the dragged object and hide the shadow;
			if (checkForClass(_object,"shadow")) {
				_class = _class.replace(" shadow","");
				_object.className = _class;
				shadow.style.display = "none";
			}
			// Replace the "button"-class with the "widget"-class:
			if (checkForClass(_object,"button")) {
				_class = _class.replace(" button"," widget");
				_object.className = _class;

				if (file == "search") {
					document.getElementById("searchHint").innerHTML = "";
					if (document.getElementById("searchParameter").value != "") { updateSearch(); }
				} else {

					// launch AJAX
					content.innerHTML = loadingImage;
			
					var fileName = "php/" + file + ".php";		// ... and add full search path and file extension to the name. We now have the full name of the file we want to load into the dropped element.
				
					// Some pages uses parameters to send to Amazon. With this switch test we set the querystring for each file;
				
					var querystring = "";
				
					switch (file) {
						case "topsellers" : querystring = "&page=" + eval("wO." + file + "[0]") + "&sort=" + eval("wO." + file + "[1]") + "&node=" + eval("wO." + file + "[2]"); break;
						case "upcoming" : querystring = "&sort=daterank&node=501866"; break;
						case "shoppingcart" :	var cartContent = shoppingCart.toString();
												querystring = "&content=" + removeCharacter(cartContent,",");
												break;
					}
				
					updatePage(fileName,content.id,"&id=" + content.id + querystring);
				}
			}
			
			content.style.display = "block";
			content.style.zIndex = _currentZIndex;
			content.className = content.className.replace(" transparent","");

			setPosition(content,parseInt(_object.style.left),parseInt(_object.style.top))
				
			_object.style.display = "none";
			_object = content;
			_object.style.display = "block";
			
			// Detect if the dragged object was dropped over the Trashcan
			if (trashHover == 1) {
				trashcan.src = _imgTrashOut.src;
				removeMainWidget(_object,factor,e);
				if (file == "search") { document.getElementById("searchHint").innerHTML = "-widget needed"; }
			}

			if (shadow.style.display == "block") { temp = shadow.offsetWidth; }
			else if (content.style.display == "block") { temp = content.offsetWidth; }

			temp = _pageWidth-temp-120;
	
			if (getNum(content.style.left) >= temp) { content.style.left = temp + "px"; }

		}
		
// we're done with these events until the next OnMouseDown

		document.onmousemove = null;
		document.onselectstart = null;

// this is how we know we're not dragging

		_object = null;
	}
}

function mimicObject(ORIGINAL,COPY) {
	COPY.style.top = ORIGINAL.style.top;
	COPY.style.left = ORIGINAL.style.left;
}

function switchObject() {

	if (checkForClass(_object,"button")) {	// Check if the "button" class is applied to the dragged object.
		_class = _object.className.replace(" widget","");
		_object.className = _class;
	} else if (checkForClass(_object,"widget")) {
		_class = _object.className.replace("button","");
		_object.className = _class;
	}
}

var animates = 0;	// Keep track of many times the interval have run. Used to force the interval to end after 100 loops.
var lastSTOPP;
var lastID;

function tweenButton(START,STOPP,ID) {

	if (animates == 1) {
		clearInterval(tween);
		document.getElementById(lastID).style.left = lastSTOPP;
	}

// set default direction of the animation.
	var direction = "left";

// change the direction in case the start-position is lower than the stop position.
	if (START < STOPP) { direction = "right"; }

// associate the animation with the tween-variable

	animates = 1;
	tween = setInterval("goTween(" + START + "," + STOPP + ",'" + ID + "',20,'" + direction + "')",10);
	
	lastSTOPP = STOPP
	lastID = ID;
}

function goTween(START,STOPP,ID,SPEED,DIRECTION) {
// store the current position of the element;
	var currentPos = getNum(document.getElementById(ID).style.left);

// Test the direction to see whether the position should be increased or decreased
	if (DIRECTION == "left") {
		document.getElementById(ID).style.left = currentPos-SPEED + "px";
	// Test to see if the element has passed the stop-position. If so the position is adjusted to match the stop-position. This may give a little bouncing effect at the end.
		if (currentPos < STOPP) {
			document.getElementById(ID).style.left = STOPP + "px";
			clearInterval(tween);	// End the animation.
			animates = 0;
		}
	} else {
		document.getElementById(ID).style.left = currentPos+SPEED + "px";
		if (currentPos > STOPP) {
			document.getElementById(ID).style.left = STOPP + "px";
			clearInterval(tween);
			animates = 0;
		}
	}
}

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




















