// $Id: utils.js,v 1.19 2009-08-20 07:14:52 tmarciniak Exp $
// Janmedia Interactive

// make sure we have a language
if (typeof _lang == "string") {
	_lang = _lang.toLowerCase();
} else if (typeof (LANGUAGE) != 'undefined') {
	_lang = LANGUAGE;
} else
	_lang = 'en';

document
		.write("<script type='text/javascript' language='JavaScript' src='/sys/js/lang/"
				+ _lang + ".js'></script>");

// Functions -------------------------------------------------------------------
function generateId() {
	var d = "" + Math.random();
	return d.substr(2);

}

// TEXT FUNCTIONS ------------------------------------------------------------
function rpad(s, length) {
	if (s.length <= length)
		return s;
	return s.substr(0, length - 3) + "...";
}

// IS.... FUNCTIONS ------------------------------------------------------------
function isObject(o) {
	return (typeof (o) == "object");
}
function isArray(o) {
	return (isObject(o) && (o.length || o.length == 0) && (!isString(o)));
}
function isFunction(o) {
	return (typeof (o) == "function");
}
function isString(o) {
	return (typeof (o) == "string");
}

// Vector ----------------------------------------------------------------------
function Vector() {
	this.elements = new Array();
}

Vector.prototype.size = function() {
	return this.elements.length;
}

Vector.prototype.add = function(element) {
	this.elements[this.elements.length] = element;
}

Vector.prototype.get = function(offset) {
	if (offset >= this.size() || offset < 0) {
		alert("Invalid offset: " + offset);
		return (null);
	}
	return this.elements[offset];
}

// HashMap ---------------------------------------------------------------------
function HashMap() {
	this.elements = new Array();
}

HashMap.prototype.size = function() {
	return this.elements.length;
}

HashMap.prototype.put = function(key, value) {
	var a = this._getItem(key);
	if (a) {
		a[1] = value;
	} else {
		a = new Array();
		a[0] = key;
		a[1] = value;
		this.elements[this.elements.length] = a;
	}
}

HashMap.prototype.remove = function(key) {
	var aa = this.elements;
	for (i = 0; i < aa.length; i++) {
		a = aa[i];
		if (a[0] == key) {
			if (i == 0) {
				this.elements = this.elements.slice(1);
			} else {
				this.elements = (new Array()).concat(this.elements.slice(0, i),
						this.elements.slice(i + 1, this.elements.length));
			}
		}
	}
}

HashMap.prototype.get = function(key) {
	var a = this._getItem(key);
	if (!a)
		return null;
	return a[1];
}

HashMap.prototype._getItem = function(key) {
	var aa = this.elements;
	for (i = 0; i < aa.length; i++) {
		a = aa[i];
		if (a[0] == key)
			return aa[i];
	}
	return null;
}

HashMap.prototype.getKey = function(offset) {
	if (offset >= this.size() || offset < 0) {
		alert("Invalid offset: " + offset);
		return (null);
	}
	var a = this.elements[offset];
	return a[0];
}

HashMap.prototype.getValue = function(offset) {
	if (offset >= this.size() || offset < 0) {
		alert("Invalid offset: " + offset);
		return (null);
	}
	var a = this.elements[offset];
	return a[1];
}

// StringTokenizer--------------------------------------------------------------
function StringTokenizer(s, tokens) {
	this.s = s;
	this.tokens = tokens;
	this.elements = new Array();

	var i = 0, token = '', ch;
	while (i < s.length) {
		ch = s.charAt(i);
		if (tokens.indexOf(ch) == -1)
			token += ch;
		else {
			this.elements[this.elements.length] = token;
			token = '';
		}
		i++;
	}

	if (token != '')
		this.elements[this.elements.length] = token;
}

StringTokenizer.prototype.size = function() {
	return this.elements.length;
}

StringTokenizer.prototype.get = function(offset) {
	if (offset >= this.size() || offset < 0) {
		alert("Invalid offset: " + offset);
		return (null);
	}
	return this.elements[offset];
}

// LOGING ----------------------------------------------------------------------
function log(s) {
	if (!document.body) {
		alert(s);
		return;
	}

	var element = document.getElementById("log");
	if (!element) {

		var div = document.createElement("div");
		div.setAttribute("id", "logDiv");
		// fwo, nie dzia??a w IE
		// div.setAttribute("style","position: absolute; top:10; left:10;
		// background:black; border:1px outset;");
		div.style.position = 'absolute';
		div.style.top = '10';
		div.style.left = '10';
		div.style.backgroundColor = 'black';
		div.style.border = '1px outset';

		var divHeader = document.createElement("div");
		// fwo, nie dzia??a w IE
		// divHeader.setAttribute("style","height:16; background:blue;
		// color:white; font-weight:bold; font-family: courier; font-size:
		// 14px");
		with (divHeader.style) {
			height = "16";
			backgroundColor = "blue";
			color = "white";
			fontWeight = "bold";
			fontFamily = "courier";
			fontSize = "14px";
			cursor = "hand";
		}
		divHeader.appendChild(document.createTextNode(".:JavaScript Log:."));
		div.appendChild(divHeader);
		divHeader.onmousedown = logOnMouseDown;
		div.onmousemove = logOnMouseMove;
		divHeader.onmouseup = logOnMouseUp;
		window.onmousemove = windowOnMouseMove;

		element = document.createElement("textarea");
		element.setAttribute("id", "log");
		element.setAttribute("cols", "80");
		element.setAttribute("rows", "15");
		element.setAttribute("wrap", "off");

		// element.setAttribute("style","position: absolute; top:16; left:1");
		with (element.style) {
			position = 'absolute';
			top = '16';
			left = '1';
			width = '400';
			height = '200';
			fontFamily = "courier";
			fontSize = "10px";
		}

		var textarea = element;
		div.appendChild(element);

		document.body.appendChild(div);
		var element = document.getElementById("log");

		div.style.width = textarea.offsetWidth + 2;
		div.style.height = textarea.offsetHeight + 18;

	}
	element.value = element.value + "\n" + s;

}

function logOnMouseDown(event) {
	var element = document.getElementById("logDiv");
	if (!element)
		return;

	window.movedObject = element;

	// IE compatibility
	if (!event) {
		event = window.event;
		event.pageX = event.x;
		event.pageY = event.y;
	}

	element.pageX = event.pageX;
	element.pageY = event.pageY;
	element.oldLeft = element.offsetLeft;
	element.oldTop = element.offsetTop;
}

function logOnMouseMove(event) {
	if (!window.movedObject)
		return;
	var element = document.getElementById("logDiv");
	if (!element)
		return;

	// IE compatibility
	if (!event) {
		event = window.event;
		event.pageX = event.x;
		event.pageY = event.y;
	}

	var i = element.oldLeft + (event.pageX - element.pageX);
	if (i < 0)
		element.style.left = 0;
	else
		element.style.left = i;

	i = element.oldTop + (event.pageY - element.pageY);
	if (i < 0)
		element.style.top = 0;
	else
		element.style.top = i;

	window.status = element.style.top;

}

function logOnMouseUp(event) {
	window.movedObject = null;
}

function windowOnMouseMove(event) {
	if (window.movedObject && window.movedObject.onmousemove)
		window.movedObject.onmousemove(event, true);
}

function logObject(obj) {
	if (isArray(obj)) {
		logArray(obj);
		return;
	}

	var i, j;
	var array = new Array();
	for (e in obj) {
		if (!e)
			continue;
		if (e + "" == "undefined")
			continue;
		for (i = 0; i < array.length; i++)
			if (array[i] > e)
				break;

		for (j = array.length; j >= i; j--)
			array[j + 1] = array[j];

		array[i] = e;
	}
	var s = obj;
	for (i = 0; i < array.length; i++) {
		if (!array[i])
			continue;
		if (array[i] + "" == "undefined")
			continue;
		var label = rpad(array[i], 19);
		s += "\n    " + label;
		if (label.length < 19)
			s += "                                ".substring(0,
					19 - label.length);

		var value;
		try {
			eval("value = obj." + array[i]);
			if (isFunction(value)) {
				s += "<function>";
			} else {
				s += rpad(("" + value).replace("\n", "").replace("\r", ""), 30);
			}
		} catch (exception) {
			s += "<???>";
		}

	}
	log(s);
}

function logArray(obj) {
	log("[array, size: " + obj.length + "]");
	for ( var i = 0; i < obj.length; i++)
		log("   [\"" + obj[i] + "\"]" + (i != obj.length - 1 ? "," : ""));
}
/*
 * ============================================================================
 * =============================================================================
 */
function trim(inputString) {
	// Removes leading and trailing spaces from the passed string. Also removes
	// consecutive spaces and replaces it with one space. If something besides
	// a string is passed in (null, custom object, etc.) then return the input.
	if (typeof inputString != "string")
		return inputString;

	var retValue = inputString;
	var ch = retValue.substring(0, 1);
	while (ch == " ") { // Check for spaces at the beginning of the string
		retValue = retValue.substring(1, retValue.length);
		ch = retValue.substring(0, 1);
	}
	ch = retValue.substring(retValue.length - 1, retValue.length);
	while (ch == " ") { // Check for spaces at the end of the string
		retValue = retValue.substring(0, retValue.length - 1);
		ch = retValue.substring(retValue.length - 1, retValue.length);
	}
	while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in
		// the string - look for multiple
		// spaces within the string
		retValue = retValue.substring(0, retValue.indexOf("  "))
				+ retValue.substring(retValue.indexOf("  ") + 1,
						retValue.length); // Again, there are two spaces in
		// each of the strings
	}
	return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function

// checking if given character is a white space
// @return boolean
function IsWhiteSpace(s) {
	var i;

	if (IsEmpty(s))
		return true;
	for (i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if (whiteSpace.indexOf(c) == -1)
			return false;
	}

	return true;
}

// ADDING MULTIPLE EVENT TO OBJ
// ----------------------------------------------------------------------
function addEvent(obj, evType, fn) {
	if (obj.addEventListener) {
		obj.addEventListener(evType, fn, false);
		return true;
	} else if (obj.attachEvent)
		return obj.attachEvent('on' + evType, fn);
	else
		return false;
}

// CAPSLOCK
// ----------------------------------------------------------------------
function checkCapslockForPassword() {
	var inputs = document.getElementsByTagName("input");
	for ( var i = 0; i < inputs.length; i++) {
		// some people are to lazy to insert obligatory attribute type
		// into input tag :P
		if (!inputs[i].getAttribute("type"))
			continue;

		if (inputs[i].getAttribute("type").toLowerCase() == "password") {
			inputs[i].br = false;
			inputs[i].onkeypress = capsDetect;
		}
	}
}

function capsDetect(e) {
	var noteId = "capslock_helper";

	if (!e)
		e = window.event;
	if (!e) {
		MWJ_say_Caps(false);
		return;
	}
	// what (case sensitive in good browsers) key was pressed
	var theKey = e.which ? e.which : (e.keyCode ? e.keyCode
			: (e.charCode ? e.charCode : 0));
	// was the shift key was pressed
	var theShift = e.shiftKey || (e.modifiers && (e.modifiers & 4)); // bitWise
	// AND
	// if upper case, check if shift is not pressed. if lower case, check if
	// shift is pressed
	if ((theKey > 64 && theKey < 91 && !theShift)
			|| (theKey > 96 && theKey < 123 && theShift))
		showNote(this, noteId);
	else
		hideNote(noteId);
}

function showNote(element, noteId) {
	var note = document.getElementById(noteId);
	if (note) {
		note.style.display = "block";
		return;
	}

	var msg = JScript["capslock"];
	// "<p><b>Caps Lock is On</b></p><p>Having Caps Lock on may cause you to
	// enter your password incorrectly.</p><p>You should press Caps Lock to turn
	// it off before entering your password.</p>";

	note = document.createElement("div");
	note.id = noteId;
	note.innerHTML = msg;
	note.appendChild(document.createElement("div"));

	note.style.position = "absolute";
	note.style.left = (parseInt(findPosX(element)) + 5) + "px"
	note.style.top = (parseInt(findPosY(element)) + 22) + "px"
	note.style.display = "block";

	note.onclick = function() {
		this.style.display = "none";
	}
	document.body.appendChild(note);
}

function hideNote(noteId) {
	var note = document.getElementById(noteId);
	if (note) {
		note.style.display = "none";
		return;
	}
}

function findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent)
		while (obj.offsetParent) {
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent)
		while (obj.offsetParent) {
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}
addEvent(window, 'load', checkCapslockForPassword);

// WYSIWYG functions----------------------------------
function wysiwygEnable(textareaId) {
	if (WYSIWYG_TYPE == 2)
		tinyMCE.addMCEControl(tinyMCE._getElementById(textareaId), textareaId);
	else {
		var editor = getHTMLArea(textareaId);
		if (typeof editor != "undefined")
			editor.show();
		else
			HTMLArea.replace(textareaId);
	}
	// ma byc czyszczony HTML po stronie serwera
	//var element = document.getElementById('_html_area');
	//if (element)
	//	element.value = textareaId;

}
function wysiwygDisable(textareaId) {
	if (WYSIWYG_TYPE == 2)
		tinyMCE.removeMCEControl(textareaId);
	else {
		var editor = getHTMLArea(textareaId);
		if (typeof editor != "undefined")
			editor.hide();
	}
	// nie ma byc czyszczony HTML po stronie serwera
	//var element = document.getElementById('_html_area');
	//if (element)
	//	element.value = "";
}

