// JavaScript Document
/**************************************************************************************
*
* Slider.js
* This script is designed to act as the manipulator of a "sliding bar" consisting of
* 2 div's - where one is the scale bar, containing the other one, the actual slider.
*
* Author: Paul-Inge Flakstad -- paulflakstad@gmail.com
*
**************************************************************************************/
var mouseDownX = 0;			// the x-coordinate of the last mouse-click
var mouseDownY = 0;			// the y-coordinate of the last mouse-click
var sliderPosX = 0;			// the slider position (actually the margin-left property)
var sliding = false;		// if the user is sliding
var offset = 0;				// offset used to make the slider correctly alligned to the mouse pointer (set in init function)
var scaleWidth = 0;			// the width of the scale element
var sliderWidth = 0;		// the width of the slider element
var scaleArea = 0;			// the area of the scale (the interval of the margin style attribute for the slider)
var percentage = 0;			// the value, in percent, of the slider (imagine "the volume")
var itemID = 0;				// the ID of the item (game, movie, etc) that's being rated/adjusted by the slider
var processURL = null;		// URL to the script that is to be called for processing

//
// Setting up the basics
//
function init(initialSliderVal, id, processingScriptURL) {
	// setting the ID
	itemID = id;

	// setting the processing script address
	processURL = processingScriptURL

	// setting the width of the scale
	width = document.getElementById("scale").style.width;
	width = width.substr(0, width.length - 2);
	scaleWidth = parseInt(width);

	// setting the width of the slider
	width = document.getElementById("slider").style.width;
	width = width.substr(0, width.length - 2);
	sliderWidth = parseInt(width);

	// setting the scale area
	scaleArea = scaleWidth - sliderWidth;
	// setting the offset - IMPORTANT
	// this is the part that makes it possible to place the slider anywhere on the page, and inside any hierarchy of div's or similar
	sliderPosition = getObjectPosition(document.getElementById("scale"));

	// set the offset, we need only care about the offset in the x-direction
	offset = (sliderWidth / 2) + sliderPosition[0];

	// set the slider to the initial position
	moveSlider(((scaleArea / 100) * initialSliderVal) + offset);

	if (itemID != null)
	{
		document.getElementById("sliderHeading").innerHTML = "Slider bar for ID " + itemID;
	}

	// HELPER
	//document.getElementById("scaleWidth").innerHTML = "Skala-bredde: " + scaleWidth;
	//document.getElementById("sliderWidth").innerHTML = "Glider-bredde: " + sliderWidth;
	//document.getElementById("bodyAttribs").innerHTML = "Offset for slider: " + sliderPosition[0] + "x / " + sliderPosition[1] + "y";
	// HELPER STOP
}

//
// Starts the slide process
//
function slide(event)
{
	// get the event object for IE
	if (!event) {event = window.event}

	// telling the script that the user is trying to drag the slider (actions while dragging: see the drag function)
	sliding = true;

	// HELPER
	// getting the mouse posistion of the mousedown action
	mouseDownX = event.clientX;
	mouseDownY = event.clientY;

	//document.getElementById("mouseDownPos").innerHTML = "Siste klikk-posisjon: " + event.clientX + "x / " + event.clientY + "y";
	//document.getElementById("dragStatus").innerHTML = "Gliderstatus: aktiv";
	// HELPER STOP
}

//
// Stops the dragging of the slider
//
function stopDrag(event)
{
	// get the event object for IE
	if (!event) {event = window.event}

	// HELPER
	//document.getElementById("mousePos").innerHTML = "Musepeker-posisjon: " + event.clientX + "x / " + event.clientY + "y";
	//document.getElementById("dragStatus").innerHTML = "Gliderstatus: inaktiv";
	// HELPER STOP

	// if we are dragging the slider
	if (sliding) {
		// telling the script that the user has released the slider
		sliding = false;
	}
}

//
// Starts the dragging of the slider
//
function drag(event)
{
	// get the event object for IE
	if (!event) {event = window.event}

	// if the user is trying to drag the slider
	if (sliding)
	{
		// dist is the distance we want to move the slider
		dist = event.clientX - sliderPosX;
		// move the slider
		moveSlider(dist);
		// HELPER
		//document.getElementById("mousePos").innerHTML = "Musepeker-posisjon: " + event.clientX + "x / " + event.clientY + "y";
		// HELPER STOP
	}
	// HELPER
	else
	{
	// adding the mouse position in text, inside the div "mousePos"
	//document.getElementById("mousePos").innerHTML = "Musepeker-posisjon: " + event.clientX + "x / " + event.clientY + "y";
	}
	// HELPER STOP
}

//
// Moves the slider a specific distance
//
function moveSlider(distance)
{
	// calculating the slider position
	sliderPosX += (distance - offset);

	// do not allow for the slider to be dragged outside the bounds of the scale
	if (sliderPosX > (scaleArea))
	{
		sliderPosX = scaleArea;
	}
	else if (sliderPosX < 0)
	{
		sliderPosX = 0;
	}

	// setting up the string to put into the html
	margin = "" + sliderPosX + "px";
	// change the margin style attribute for the div "slider"
	document.getElementById("slider").style.marginLeft = margin;

	newPercentage = parseInt((sliderPosX / scaleArea) * 100);
	//increase = newPercentage >= percentage ? true : false;
	percentage = newPercentage;

	// loop for turning lights on / off
	for (i = 1; i <= 20; i++)
	{
		if (i < parseInt(percentage / 5) + 1)
		{
			// turn ON light by setting the background-position of the image
			bg_p = document.getElementById("slider_" + i).style.backgroundPosition.split(" ");
			document.getElementById("slider_" + i).style.backgroundPosition = bg_p[0] + " 0px";
		}
		else
		{
			// turn OFF light by setting the background-position of the image
			bg_p = document.getElementById("slider_" + i).style.backgroundPosition.split(" ");
			document.getElementById("slider_" + i).style.backgroundPosition = bg_p[0] + " -24px";
		}
	}

	// HELPER
	document.getElementById("percentage").innerHTML = "<h2>" + percentage + "</h2>";
	// HELPER STOP
}

//
// Gets an objects position (offset) and returns it as an array.
//
function getObjectPosition(obj)
{
	// start the counters at zero
	var curleft = curtop = 0;

	// if the object has a parent
	if (obj.offsetParent)
	{
		do
		{
			// add the horizontal...
			curleft += obj.offsetLeft;
			// ...and the vertical offset to the variables, respectively
			curtop += obj.offsetTop;
		}
		// and repeat this step for "all parents" of the object (parents of parents of parents and so on)
		while (obj = obj.offsetParent);
	}
	// return an array with the object's position
	return [curleft,curtop];
}


/******************************
// 		AJAX experimenting
//****************************/

//
// Getting the XMLHttpRequest object - done differently in different browsers
//
function getHTTPObject() {
    if (typeof XMLHttpRequest != 'undefined') {
        return new XMLHttpRequest();
    }
    try {
        return new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            return new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
    }
    return false;
}

function registerRating() {
	var httpObj = getHTTPObject();
	httpObj.open("POST", processURL, true);

	httpObj.onreadystatechange = function()
	{
		if (httpObj.readyState == 4)
		{
			if (httpObj.status == 200)
			{
				//document.getElementById("serverResponse").innerHTML = "Server: mottatt og prosessert verdi <strong>" +
					//httpObj.responseXML.getElementsByTagName("slidervalue")[0].firstChild.data +
					//"</strong> for ID <strong>" +
					//httpObj.responseXML.getElementsByTagName("itemID")[0].firstChild.data + "</strong> - <strong>statuskode " +
					//httpObj.responseXML.getElementsByTagName("result")[0].firstChild.data + "</strong>";
				// hide the slider after the server query has been performed
				document.getElementById("rightSide").style.display = "none";
				//document.getElementById("rightSide").style.display = "none";
				//document.getElementById("submitRatingButton").innerHTML = "Your vote was registered!";
			}
			else
			{
				//document.getElementById("serverResponse").innerHTML = "Server: feil under lagring!";
			}
		}
	}

	// sending the POST to the server
	httpObj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	httpObj.send("itemID=" + itemID + "&val=" + percentage);
}





// event handlers
document.onmousemove = drag;
// The following can not be in the html because it requires the user to release with the mouse on the slider to work properly.
// We want to allow the user to release anywhere on the page.
document.onmouseup = stopDrag;