//---------------------------------+
//  CARPE  S l i d e r        1.5  |
//  2006 - 01 - 03                 |
//  By Tom Hermansson Snickars     |
//  Copyright CARPE Design         |
//  http://carpe.ambiprospect.com/ |
//  Contact for custom scripts     |
//  or implementation help.        |
//---------------------------------+

// Global vars. You don't need to make changes here to change your sliders.
// Changing the attributes in your (X)HTML file is enough.
var carpeDefaultSliderLength      = 100
var carpeSliderDefaultOrientation = 'horizontal'
var carpeSliderClassName          = 'carpe_slider'
var carpeSliderDisplayClassName   = 'carpe_slider_display'

// carpeGetElementsByClass: Cross-browser function that returns
// an array with all elements that have a class attribute that
// contains className
function carpeGetElementsByClass(className)
{
	var classElements = new Array()
		var els = document.getElementsByTagName("*")
		var elsLen = els.length
		var pattern = new RegExp("\\b" + className + "\\b")
		for (i = 0, j = 0; i < elsLen; i++) {
			if ( pattern.test(els[i].className) ) {
				classElements[j] = els[i]
					j++
			}
		}
	return classElements;
}
// carpeLeft: Cross-browser version of "element.style.left"
// Returns or sets the horizontal position of an element.
function carpeLeft(elmnt, pos)
{
	if (!(elmnt = document.getElementById(elmnt))) return 0;
	if (elmnt.style && (typeof(elmnt.style.left) == 'string')) {
		if (typeof(pos) == 'number') elmnt.style.left = pos + 'px';
		else {
			pos = parseInt(elmnt.style.left);
			if (isNaN(pos)) pos = 0;
		}
	}
	else if (elmnt.style && elmnt.style.pixelLeft) {
		if (typeof(pos) == 'number') elmnt.style.pixelLeft = pos;
		else pos = elmnt.style.pixelLeft;
	}
	return pos;
}
// carpeTop: Cross-browser version of "element.style.top"
// Returns or sets the vertical position of an element.
function carpeTop(elmnt, pos)
{
	if (!(elmnt = document.getElementById(elmnt))) return 0;
	if (elmnt.style && (typeof(elmnt.style.top) == 'string')) {
		if (typeof(pos) == 'number') elmnt.style.top = pos + 'px';
		else {
			pos = parseInt(elmnt.style.top);
			if (isNaN(pos)) pos = 0;
		}
	}
	else if (elmnt.style && elmnt.style.pixelTop) {
		if (typeof(pos) == 'number') elmnt.style.pixelTop = pos;
		else pos = elmnt.style.pixelTop;
	}
	return pos;
}
// moveSlider: Handles slider and display while dragging
function moveSlider(evnt)
{
	var evnt = (!evnt) ? window.event : evnt; // The mousemove event
	if (mouseover) { // Only if slider is dragged
		x = slider.startOffsetX + evnt.screenX // Horizontal mouse position relative to allowed slider positions
		y = slider.startOffsetY + evnt.screenY // Horizontal mouse position relative to allowed slider positions
		if (x > slider.xMax) x = slider.xMax // Limit horizontal movement
		if (x < 0) x = 0 // Limit horizontal movement
		if (y > slider.yMax) y = slider.yMax // Limit vertical movement
		if (y < 0) y = 0 // Limit vertical movement
		carpeLeft(slider.id, x)  // move slider to new horizontal position
		carpeTop(slider.id, y) // move slider to new vertical position
		sliderVal = x + y // pixel value of slider regardless of orientation
		sliderPos = (slider.distance / display.valuecount) * 
		Math.round(display.valuecount * sliderVal / slider.distance)
		v = Math.round((sliderPos * slider.scale + slider.from) * // calculate display value
				Math.pow(10, display.decimals)) / Math.pow(10, display.decimals)
		display.value = v // put the new value in the slider display element
		eval(sliderCb);
		return false
	}
	return
}
// slide: Handles the start of a slider move.
function slide(evnt)
{
	if (!evnt) evnt = window.event; // Get the mouse event causing the slider activation.
	slider = (evnt.target) ? evnt.target : evnt.srcElement; // Get the activated slider element.
	sliderCb = slider.getAttribute('cb');
	dist = parseInt(slider.getAttribute('distance')) // The allowed slider movement in pixels.
	slider.distance = dist ? dist : carpeDefaultSliderLength // Deafault distance from global var.
	ori = slider.getAttribute('orientation') // Slider orientation: 'horizontal' or 'vertical'.
	orientation = ((ori == 'horizontal') || (ori == 'vertical')) ? ori : carpeSliderDefaultOrientation
	// Default orientation from global variable.
	displayId = slider.getAttribute('display') // ID of associated display element.
	display = document.getElementById(displayId) // Get the associated display element.
	display.sliderId = slider.id // Associate the display with the correct slider.
	dec = parseInt(display.getAttribute('decimals')) // Number of decimals to be displayed.
	display.decimals = dec ? dec : 0 // Default number of decimals: 0.
	val = parseInt(display.getAttribute('valuecount'))  // Allowed number of values in the interval.
	display.valuecount = val ? val : slider.distance + 1 // Default number of values: the sliding distance.
	from = parseFloat(display.getAttribute('from')) // Min/start value for the display.
	from = from ? from : 0 // Default min/start value: 0.
	to = parseFloat(display.getAttribute('to')) // Max value for the display.
	to = to ? to : slider.distance // Default number of values: the sliding distance.
	slider.scale = (to - from) / slider.distance // Slider-display scale [value-change per pixel of movement].
	if (orientation == 'vertical') { // Set limits and scale for vertical sliders.
		slider.from = to // Invert for vertical sliders. "Higher is more."
		slider.xMax = 0
		slider.yMax = slider.distance
		slider.scale = -slider.scale // Invert scale for vertical sliders. "Higher is more."
	}
	else { // Set limits for horizontal sliders.
		slider.from = from
		slider.xMax = slider.distance
		slider.yMax = 0
	}
	slider.startOffsetX = carpeLeft(slider.id) - evnt.screenX // Slider-mouse horizontal offset at start of slide.
	slider.startOffsetY = carpeTop(slider.id) - evnt.screenY // Slider-mouse vertical offset at start of slide.

	mouseover = true
	document.onmousemove = moveSlider // Start the action if the mouse is dragged.
	document.onmouseup = sliderMouseUp // Stop sliding.
	return false
}
// sliderMouseUp: Handles the mouseup event after moving a slider.
// Snaps the slider position to allowed/displayed value. 
function sliderMouseUp()
{
	if (mouseover) {
		v = (display.value) ? display.value : 0 // Find last display value.
			pos = (v - slider.from)/(slider.scale) // Calculate slider position (regardless of orientation).
			if (slider.yMax == 0) {
				pos = (pos > slider.xMax) ? slider.xMax : pos
				pos = (pos < 0) ? 0 : pos
				carpeLeft(slider.id, pos) // Snap horizontal slider to corresponding display position.
			}
		if (slider.xMax == 0) {
			pos = (pos > slider.yMax) ? slider.yMax : pos
			pos = (pos < 0) ? 0 : pos
			carpeTop(slider.id, pos) // Snap vertical slider to corresponding display position.
		}
		if (document.removeEventListener) { // Remove event listeners from 'document' (W3C).
			document.removeEventListener('mousemove', moveSlider, false)
			document.removeEventListener('mouseup', sliderMouseUp, false)
		}
		else if (document.detachEvent) { // Remove event listeners from 'document' (IE).
			document.detachEvent('onmousemove', moveSlider)
			document.detachEvent('onmouseup', sliderMouseUp)
		}
	}
	mouseover = false // Stop the sliding.
}
function focusDisplay(evnt)
{
	if (!evnt) evnt = window.event; // Get the mouse event causing the display activation.
	display = (evnt.target) ? evnt.target : evnt.srcElement; // Get the activated display element.
	lock = display.getAttribute('typelock') // Is the user allowed to type into the display?
	if (lock == 'on') {
		display.blur()
	}
	return
}
window.onload = function() // Set up the sliders and the displays.
{
	sliders = carpeGetElementsByClass(carpeSliderClassName) // Find the horizontal sliders.
	for (i = 0; i < sliders.length; i++) {
		sliders[i].onmousedown = slide // Attach event listener.
	}
	displays = carpeGetElementsByClass(carpeSliderDisplayClassName) // Find the displays.
	for (i = 0; i < displays.length; i++) {
		displays[i].onfocus = focusDisplay // Attach event listener.
	}
}



//////////////// end of CARPE stuff 

var lastTurnNum;
var timeoutVar;

function DisplayTurn()
{
	if (display.value != lastTurnNum) {
		turnNum = display.value;
		document.getElementById('arena').innerHTML = sttdturn[turnNum];
		lastTurnNum = turnNum;
	}
}

function PlaybackTurnFwd()
{
	StopPlayback();
	display.value = Number(display.value) + 1;
	DisplayTurn();
	timeoutVar = setTimeout('PlaybackTurnFwd()', 250);
}

function PlaybackTurnBack()
{
	StopPlayback();
	if (Number(display.value) > 1) {
		display.value = Number(display.value) - 1;
		DisplayTurn();
		timeoutVar = setTimeout('PlaybackTurnBack()', 250);
	}
}

function StopPlayback()
{
	clearTimeout(timeoutVar);
}

function TimeLeftToStr(timeVal)
{
	var timeStr = "";
	var hours = 0;
	var minutes = 0;
	if (timeVal > 3600) {
		hours = Math.floor(timeVal/3600);
		timeStr = hours + " hours";
		timeVal -= 3600*hours;
	}
	if (timeVal > 60) {
		minutes = Math.floor(timeVal/60);
		if (timeStr != "") {
			timeStr += ", ";
		}
		timeStr = timeStr + minutes + " minutes";
		timeVal -= 60*minutes;
	}
	if ((timeVal > 0) && (hours == 0)) {
		if (timeStr != "")
			timeStr += ", ";
		timeStr += timeVal + " seconds";
	}
	return timeStr;
}

function escapediv(str){
	var re=/[ \.]/g
	return str.replace(re, function(m){return escapedivchar(m)});
}
function escapedivchar(match){
	if (match==".")
		return "\\."
	if (match==" ")
		return "\\ "
}

function html2entities(str){
	var re=/[<>"'&]/g
	return str.replace(re, function(m){return replacechar(m)});
}

function replacechar(match){
	if (match=="<")
		return "&lt;"
	else if (match==">")
		return "&gt;"
	else if (match=="\"")
		return "&quot;"
	else if (match=="'")
		return "&#039;"
	else if (match=="&")
		return "&amp;"
}

function UpdateCChat(response, channels, chatterList)
{
	var chatText = "";
	var chatters = "<ul class='chattersList'>";
	var updateArray = response.getElementsByTagName("chat");
	for (var n = 0; n < updateArray.length; n++) {
		if (updateArray[n].getAttribute("OpType") == 0) { // Actual chat text
			if (updateArray[n].getAttribute("Admin") != undefined) {
				var chan = updateArray[n].getAttribute("Sender");
				if (chan == cc_user) chan = updateArray[n].getAttribute("Receiver");
				if (typeof channels[chan] == "undefined") {
					channels[chan] = {};
					channels[chan].chatText = "";
					channels[chan].hidden = false;
				}
				channels[chan].chatText += "<li class='chatList'>" + updateArray[n].getAttribute("Sender") + ": " + html2entities(UnicodeToAscii(base64decode(updateArray[n].getAttribute("Admin")))) + "</li>";
				channels[chan].dirty = true;
				channels[chan].hidden = false;
			} else if (updateArray[n].getAttribute("Text") != undefined) {
				channels['CaravelNet'].chatText += "<li class='chatList'>" + updateArray[n].getAttribute("Sender") + ": " + html2entities(UnicodeToAscii(base64decode(updateArray[n].getAttribute("Text")))) + "</li>";
				channels['CaravelNet'].dirty = true;
			}

			if (updateArray[n].getAttribute("ID") != undefined) {
				if (updateArray[n].getAttribute("ID") > cc_lastId) {
					cc_lastId = updateArray[n].getAttribute("ID");
				}
			}
		} else if (updateArray[n].getAttribute("OpType") == 2) { // chatters
			chatters += "<li class='chattersList'>" + updateArray[n].getAttribute("Sender") + "</li><input type='hidden' id='Chatters"+n+"' value='"+updateArray[n].getAttribute("ID")+"'/>\n";
			chatterList[updateArray[n].getAttribute("Sender")] = updateArray[n].getAttribute("ID");
		}
	}
	chatters += "</ul>";
//	if (chatText != "") {
//		$("#theChatList").append(chatText);
//		$("#theChat").animate({ scrollTop: $("#theChat").attr("scrollHeight") - $('#theChat').height() }, 500);
//	}
	$("#chatters").html(chatters);
	$("li.chattersList").each(function(index) {
		$(this).click(function() {
			OpenChatTab($(this)[0].innerHTML);
		});
	});
}

var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var base64DecodeChars = new Array(
	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
	52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
	-1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
	15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
	-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
	41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);

function base64encode(str) {
	var out, i, len;
	var c1, c2, c3;

	len = str.length;
	i = 0;
	out = "";
	while(i < len) {
		c1 = str.charCodeAt(i++) & 0xff;
		if(i == len)
		{
			out += base64EncodeChars.charAt(c1 >> 2);
			out += base64EncodeChars.charAt((c1 & 0x3) << 4);
			out += "==";
			break;
		}
		c2 = str.charCodeAt(i++);
		if(i == len)
		{
			out += base64EncodeChars.charAt(c1 >> 2);
			out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
			out += base64EncodeChars.charAt((c2 & 0xF) << 2);
			out += "=";
			break;
		}
		c3 = str.charCodeAt(i++);
		out += base64EncodeChars.charAt(c1 >> 2);
		out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
		out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6));
		out += base64EncodeChars.charAt(c3 & 0x3F);
	}
	return out;
}

function base64decode(str) {
	var c1, c2, c3, c4;
	var i, len, out;

	len = str.length;
	i = 0;
	out = "";
	while(i < len) {
		/* c1 */
		do {
			c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
		} while(i < len && c1 == -1);
		if(c1 == -1)
			break;

		/* c2 */
		do {
			c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
		} while(i < len && c2 == -1);
		if(c2 == -1)
			break;

		out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));

		/* c3 */
		do {
			c3 = str.charCodeAt(i++) & 0xff;
			if(c3 == 61)
				return out;
			c3 = base64DecodeChars[c3];
		} while(i < len && c3 == -1);
		if(c3 == -1)
			break;

		out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));

		/* c4 */
		do {
			c4 = str.charCodeAt(i++) & 0xff;
			if(c4 == 61)
				return out;
			c4 = base64DecodeChars[c4];
		} while(i < len && c4 == -1);
		if(c4 == -1)
			break;
		out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
	}
	return out;
}

function UnicodeToAscii(uni)
{
	var out = "";
	var len = uni.length;
	var x;
	for (x = 0; x < len; x+=2) {
		out += uni[x];
	}
	return out;
}
function AsciiToUnicode(asc)
{
	var out = "";
	var len = asc.length;
	var x;
	for (x = 0; x < len; x++) {
		out += asc[x]+String.fromCharCode(0);
	}
	return out;
}

