/*
	HME JavaScript Engine Library
	Copyright 2007, 2008 Michał Andrzej Woźniak <rysiek_at_rysiek.ath.cx>
	Portions copyright 2005 <bfults@gmail.com>

	Dual-licensed under:
	- Creative Commons Attribution-ShareAlike License
	  [http://creativecommons.org/licenses/by-sa/2.0/]
	- Affero General Public License
	  [http://www.gnu.org/licenses/agpl.txt]

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

if (typeof HME_ENGINE_INCLUDED == 'undefined') {
	/* --- flaga "jestem" ------------------------------------------------------ */
	var HME_ENGINE_INCLUDED = true;

	/* ========================================================================= *\
	|* === [ obsługa zdarzeń ]                                               === *|
	\* ========================================================================= */
	// ToDo:
	// - wsio do jednego objecta
	// - namespaces

	/* --- tablice handlerów --------------------------------------------------- */
	// handlery window.onload
	var onLoadHandlers = new Array()
	// handlery window.onresize
	var onResizeHandlers = new Array()
	// handlery window.onscroll
	var onScrollHandlers = new Array()

	/* --- uruchamianie handlerów ---------------------------------------------- */
	// wykonujemy po kolei wszystkie handlery window.onload
	function executeOnLoadHandlers() {
		for (var i = 0; i < onLoadHandlers.length; i++) {
			onLoadHandlers[i]()
		}
	}

	// wykonujemy po kolei wszystkie handlery window.onresize
	function executeOnResizeHandlers() {
		for (var i = 0; i < onResizeHandlers.length; i++) {
			onResizeHandlers[i]()
		}
	}

	// wykonujemy po kolei wszystkie handlery window.onscroll
	function executeOnScrollHandlers() {
		for (var i = 0; i < onScrollHandlers.length; i++) {
			onScrollHandlers[i]()
		}
	}

	/* --- dodawanie handlerów ------------------------------------------------- */
	// dodajemy nowy handler do window.onload
	function addOnLoadHandler(aHandler) {
		if (!window.onload) {
			window.onload=executeOnLoadHandlers
		}
		var i = onLoadHandlers.length
		onLoadHandlers[i] = aHandler
	}

	// dodajemy nowy handler do window.onresize
	function addOnResizeHandler(aHandler) {
		if (!window.onresize) {
			window.onresize=executeOnResizeHandlers
		}
		var i = onResizeHandlers.length
		onResizeHandlers[i] = aHandler
	}

	// dodajemy nowy handler do window.onscroll
	function addOnScrollHandler(aHandler) {
		if (!window.onscroll) {
			window.onscroll=executeOnScrollHandlers
		}
		var i = onScrollHandlers.length
		onScrollHandlers[i] = aHandler
	}

	/* ========================================================================= *\
	|* === [ zabawa objectami ]                                              === *|
	\* ========================================================================= */
	//KOD ZAPOŻYCZONY Z http://www.howtocreate.co.uk/tutorials/
	/* --- znajdź obiekt po nazwie w każdej przeglądarce --- */
	function findObj (oName, oFrame, oDoc)
	{
		if (!oDoc) {
			if (oFrame) {
				oDoc = oFrame.document;
			} else {
				oDoc = window.document;
			}
		}

		// check for images, forms, layers
		if (oDoc[oName]) {
			return oDoc[oName];
		}

		// check for pDOM layers
		//check for DOM layers
		if (oDoc.all && oDoc.all[oName]) {
			return oDoc.all[oName];
		}

		// check for DOM layers
		if (oDoc.getElementById && oDoc.getElementById(oName)) {
			return oDoc.getElementById(oName);
		}

		// check for any of the above within a layer in layers browsers
		for (var x = 0; document.layers && x < oDoc.layers.length; x++) {
			var theOb = findObj (oName, null, oDoc.layers[x].document);
			if (theOb) {
				return theOb;
			}
		}
		return null;
	}

	// pierwsza child node, która jest elementem HTML DOM
	function firstHTMLChildNode(aParent) {
		for (aNode in aParent.childNodes) {
			if (aParent.childNodes[aNode].nodeType == 1) {
				return aParent.childNodes[aNode];
			}
		}
		return false
	}

	// KOD ZAPOŻYCZONY Z
	// http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256C720080D723
	/* --- czy dana zmienna jest tablicą? -------------------------------------- */
	function isArray(obj) {
		if ( !(obj) || (obj.constructor.toString().indexOf("Array") == -1) ) {
			return false
		} else {
			return true
		}
	}
	//KONIEC KODU ZAPOŻYCZONEGO

	/* ========================================================================= *\
	|* === [ zabawa DOM ]                                                    === *|
	\* ========================================================================= */
	/* Calculate the offsetLeft sum of all offsetParents.
		The result is element.style.left */
	function getoffsetLeft(element) {
		if(!element) return 0;
		return element.offsetLeft + getoffsetLeft(element.offsetParent);
	}

	/* Calculate the offsetTop sum of all offsetParents.
		The result is element.style.top */
	function getoffsetTop(element) {
		if(!element) return 0;
		return element.offsetTop + getoffsetTop(element.offsetParent);
	}

	// zapożyczone z http://www.quirksmode.org/js/findpos.html
	function findPos(obj) {
		var curleft = curtop = 0;
		if (obj.offsetParent) {
			do {
				curleft += obj.offsetLeft;
				curtop += obj.offsetTop;
			} while (obj = obj.offsetParent);
		}
		return [curleft, curtop];
	}

	/* --- ile przewinięte jest okno? ------------------------------------------ */
	function getScrollXY() {
		var scrOfX = 0, scrOfY = 0;
		if( typeof( window.pageYOffset ) == 'number' ) {
			//Netscape compliant
			scrOfY = window.pageYOffset;
			scrOfX = window.pageXOffset;
		} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
			//DOM compliant
			scrOfY = document.body.scrollTop;
			scrOfX = document.body.scrollLeft;
		} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
			//IE6 standards compliant mode
			scrOfY = document.documentElement.scrollTop;
			scrOfX = document.documentElement.scrollLeft;
		}
		return [ scrOfX, scrOfY ];
	}
	//KONIEC KODU ZAPOŻYCZONEGO

	/* --- jaki jest rozmiar okna? --------------------------------------------- */
	function getWindowSize() {
		var myWidth = 0, myHeight = 0;
		if ( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
			//IE 6+ in 'standards compliant mode'
			myWidth = document.documentElement.clientWidth;
			myHeight = document.documentElement.clientHeight;
		} else if ( typeof( window.innerWidth ) == 'number' ) {
			//Non-IE
			myWidth = window.innerWidth;
			myHeight = window.innerHeight;
		} else if ( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
			//IE 4 compatible
			myWidth = document.body.clientWidth;
			myHeight = document.body.clientHeight;
		}
		return [ myWidth, myHeight ];
	}

	/* --- jaki jest rozmiar elementu body? ------------------------------------ */
	function getBodySize() {
		var aWidth = findObj('center').clientWidth + 280
		var aHeight = getWindowSize()[1]
		if ( aWidth < document.body.clientWidth ) {
			aWidth = document.body.clientWidth
		}
		return [aWidth, aHeight]
	}

	/* ========================================================================= *\
	|* === [ zabawa plikami ]                                                === *|
	\* ========================================================================= */
	/** include - including .js files from JS - bfults@gmail.com - 2005-02-09    **
	** Code licensed under Creative Commons Attribution-ShareAlike License       **
	** http://creativecommons.org/licenses/by-sa/2.0/                            **/
	var hIncludes = null;
	function include(sURI)
	{
		if (document.getElementsByTagName) {
			if (!hIncludes) {
				hIncludes = {};
				var cScripts = document.getElementsByTagName("script");
				for (var i=0,len=cScripts.length; i < len; i++)
					if (cScripts[i].src) hIncludes[cScripts[i].src] = cScripts[i];
			}

			if (!hIncludes[sURI]) {
				var oNew = document.createElement("script");
				oNew.type = "text/javascript";
				oNew.src = sURI;
				hIncludes[sURI]=true;
				document.getElementsByTagName("head")[0].appendChild(oNew);
			}
			return hIncludes[sURI];
		}
		return false
	}

	/* --- zassanie nowego pliku css ------------------------------------------- */
	function fetchStyleSheet(aUri) {
		// ie - ech...
		if(document.createStyleSheet) {
			document.createStyleSheet(aUri)
		// standardowe, normalne, porządne przeglądarki
		} else {
			var css = document.createElement('link')
			css.rel = 'stylesheet'
			css.type = 'text/css'
			css.href = aUri
			document.getElementsByTagName("head")[0].appendChild(css)
		}
	}

	/* ========================================================================= *\
	|* === [ debug ]                                                         === *|
	\* ========================================================================= */
	// DEBUG
	var DBGDIV    = false
	var HME_DEBUG = false

	// stworzenie "konsoli"
	function dbgGetDiv(anId) {
		if (!anId) anId = 'dbg'
		if ((typeof(DBGDIV) != 'object') || !DBGDIV) {
			DBGDIV = findObj('anId') // mamy jakiegoś takiego diva?
			if ((typeof(DBGDIV) != 'object') || !DBGDIV) { // nie, nie mamy
				// zróbmy sobie diva
				DBGDIV = document.createElement('pre')
				DBGDIV.id = anId
				DBGDIV.style.position = 'absolute'
				DBGDIV.style.overflow = 'auto'
				DBGDIV.style.maxHeight = '400px'
				DBGDIV.style.visibility = 'visible'
				DBGDIV.style.top = '8px'
				DBGDIV.style.left = '350px'
				DBGDIV.style.background = 'black'
				DBGDIV.style.border = 'solid 1px #333'
				DBGDIV.style.color = '#777'
				DBGDIV.style.fontFace = 'Monospace'
				DBGDIV.style.fontSize = '9px'
				DBGDIV.style.fontWeight = 'bold'
				DBGDIV.style.width = '500px'
				DBGDIV.style.zIndex = '20'
				// rzucamy go na front
				document.body.appendChild(DBGDIV)
				// zwracamy
				return DBGDIV
			}
		} else {
			return DBGDIV
		}
	}

	// wypisanie debugu
	function dbgWrite(aText) {
		if (HME_DEBUG) {
			tmpdiv = dbgGetDiv()
			tmpdiv.innerHTML += aText + '<br/>'
			tmpdiv.scrollTop = tmpdiv.scrollHeight
		}
	}
}
