// ../script/ACRunActiveContent.js -> kinyomva	
// ../script/ajax.js -> kinyomva	
// ../script/dialogManager.js -> kinyomva	
// ../script/ja-transmenu.js -> kinyomva	
// ../script/scripthu.js -> kinyomva	
//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2007 Adobe Systems Incorporated.  All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			
			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '';
  if (isIE && isWin && !isOpera)
  {
    str += '<object ';
    for (var i in objAttrs)
    {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params)
    {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  }
  else
  {
    str += '<embed ';
    for (var i in embedAttrs)
    {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }

  document.write(str);
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}
	
	
var ajaxcomm = 0;
var ajaxArray = new Array();
var cSearch = "";
var color2 = "";

function fClickFlashUzlet(ccsopid,cuzid){	
	fClickUzlet2(cuzid);
	color2 = fGetObject('csop_'+String(ccsopid)+'_c').innerHTML;
	fClickCsoport2(ccsopid, color2);
	window.location.href = "#jump";
}

function fClickUzlet2(cid){
	fGetObject("uzletleiras").innerHTML = "frissítés...";	
	ajaxArray.push(Array("../doajax.php?type=shop_select","&cid="+String(cid),"commGateSelectUzlet"));
	fCallxmlhttpPost();
	fGetObject('uzletlogo').src = '';
	fGetObject('uzletlogo').alt = '';
	fGetObject('uzletnev').innerHTML = '';
	fGetObject('uzletlink').href = '';
	fGetObject('uzletlink').innerHTML = '';
	fGetObject('weblink').style.display = 'none';
	h = 99;
	while(h<400){
		if(fGetObject('uzlet_'+String(h)))
			fGetObject('uzlet_'+String(h)).style.textDecoration='none';
		if(fGetObject('uzlet_'+String(h)+'a'))
			fGetObject('uzlet_'+String(h)+'a').style.textDecoration='none';
		if(fGetObject('uzlet_'+String(h)+'b'))
			fGetObject('uzlet_'+String(h)+'b').style.textDecoration='none';
		h++;
	}
	fGetObject('uzlet_'+String(cid)).style.textDecoration='underline';
}

function fClickUzlet(cid){
	fCallFlash('uzletkereso','clickUzlet',cid);
	fGetObject("uzletleiras").innerHTML = "frissítés...";	
	ajaxArray.push(Array("../doajax.php?type=shop_select","&cid="+String(cid),"commGateSelectUzlet"));
	fCallxmlhttpPost();
	fGetObject('uzletlogo').src = '';
	fGetObject('uzletlogo').alt = '';
	fGetObject('uzletnev').innerHTML = '';
	fGetObject('uzletlink').href = '';
	fGetObject('uzletlink').innerHTML = '';
	fGetObject('weblink').style.display = 'none';
	h = 99;
	while(h<400){
		if(fGetObject('uzlet_'+String(h)))
			fGetObject('uzlet_'+String(h)).style.textDecoration='none';
		if(fGetObject('uzlet_'+String(h)+'a'))
			fGetObject('uzlet_'+String(h)+'a').style.textDecoration='none';
		if(fGetObject('uzlet_'+String(h)+'b'))
			fGetObject('uzlet_'+String(h)+'b').style.textDecoration='none';
		h++;
	}
	fGetObject('uzlet_'+String(cid)).style.textDecoration='underline';
}

function commGateSelectUzlet(str){
	ajaxcomm = 0;
	var aTmp = fGetToken(str, "<agriapark>");
	if (aTmp[0] != ""){
		fGetObject('uzletlogo').src = '../file_uzletek/'+String(aTmp[0]);
	}
	if (aTmp[1] != ""){
		fGetObject('uzletlogo').alt = String(aTmp[1]);
		fGetObject('uzletnev').innerHTML = String(aTmp[1]);		
	}else{
		fGetObject('uzletlogo').alt = '';
		fGetObject('uzletnev').innerHTML = '-';		
	}
	if (aTmp[2] != ""){
		fGetObject('uzletleiras').innerHTML = String(aTmp[2]);
	}else{
		fGetObject('uzletleiras').innerHTML = '-'
	}
	if (aTmp[3] != "" && aTmp[3] != "-"){
		fGetObject('weblink').style.display = 'block';
		fGetObject('uzletlink').style.display = "block;"
		fGetObject('uzletlink').href = String(aTmp[3]);
		var slink = String(aTmp[3]);
		//link.substr(7, (link.length-7);
		//fGetObject('uzletlink').innerHTML = String(aTmp[3]);
		fGetObject('uzletlink').innerHTML = slink.substr(7, (slink.length-7));
	}else{
		fGetObject('uzletlink').style.display = "none;"
	}	
}


function fSearch(obj){
	if(obj.value != cSearch){	
		obj2 = fGetObject("content");
		if(obj2)
			obj2.style.display = "none";
			
		obj2 = fGetObject("searchresult");
		if(obj2)
			obj2.style.display = "block";
			
		cSearch = obj.value;
		if(obj.value.length > 2){
			fGetObject("searchresult").innerHTML = '<h1>Találatok</h1><div class="tppad10 btpad10" align="left">frissítés...</div>';
			xmlhttpPostSearch("../doajax.php?type=search", "str_search="+String(obj.value), "commGateSearch");
		}else if(obj.value.length > 0){
			tmp = '<h1>Találatok</h1><div class="tppad10 btpad10" align="left">a keresés a harmadik leütött karaktertol indul</div>';
			obj2 = fGetObject("searchresult");
			if(obj)
				obj2.innerHTML = tmp;
		}else{
			obj2 = fGetObject("searchresult");
			if(obj2)
				obj2.style.display = "none";
				
			obj2 = fGetObject("content");
			if(obj2)
				obj2.style.display = "block";
		}
	}
}

function commGateSearch(str){
	var aTmp = fGetToken(str, "<agriapark>");
	var aSearch = new Array;
	var vszam = new Number(0);
		
	tmp = '<h1>Találatok</h1>';
	
	if(aTmp[0] == -1)
		tmp += '<div class="tppad10 btpad10" align="left">nincs a keresési feltételnek megfelelő tétel</div>';
	else{
		for(q=1; q<aTmp.length; q++){
			tmp += '<div class="tppad10">'+aTmp[q]+'<br /><a href=../'+aTmp[++q]+' class="tovabbkeres">Tovább</a><br /><img src="../img/verticallenia.jpg" align="center" style="padding:10px 0px;" alt="Agria Park | Lenia" /></div>';
		}		
	}
	obj2 = fGetObject("searchresult");
	if(obj2)
		obj2.innerHTML = tmp;
}

function commGateGeneral(str){
	ajaxcomm = 0;
	var aTmp = fGetToken(str, "<agriapark>");
	if(aTmp[0] != -1)
		eval(aTmp[1]);
}

function fCallxmlhttpPost(){
	if(ajaxcomm == 0 && ajaxArray.length>0){
		ajaxcomm = 1;
		param = ajaxArray.shift()
		xmlhttpPost(param[0], param[1], param[2]);
	}else if(ajaxcomm == 1 && ajaxArray.length>0){
		setTimeout("fCallxmlhttpPost()", 500);
	}	
}

function fGetToken(pStr, pToken){
	var str = new String(pStr);
	return str.split(pToken);
}
function xmlhttpPost(strUrl, strQuery, strCallBack) {
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strUrl, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4){
			eval(strCallBack + "(self.xmlHttpReq.responseText)");
        }
    }
    self.xmlHttpReq.send(strQuery);
}

function xmlhttpPostSearch(strUrl, strQuery, strCallBack) {
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strUrl, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4){
			eval(strCallBack + "(self.xmlHttpReq.responseText)");
        }
    }
    self.xmlHttpReq.send(strQuery);
}

function commGateChangeDropDown(str){
	ajaxcomm = 0;
	var aTmp = fGetToken(str, "<agriapark>");
	
	tmp = "<select id='"+ aTmp[0] +"' name='"+ aTmp[0] +"' class='input' onchange='" + aTmp[1] + "'>";		
	
	for(q=2; q<aTmp.length; q++)
		tmp += "<option value='"+aTmp[q]+"' id='"+aTmp[++q]+"'>"+aTmp[q]+"</option>";
		
	tmp += "</select>";
	
	obj = fGetObject("div_" + aTmp[0]);
	if(obj)
		obj.innerHTML = tmp;
}

function commGateChangeDropDownSearch(str){
	var aTmp = fGetToken(str, "<agriapark>");
	
	tmp = "<select id='"+ aTmp[0] +"' name='"+ aTmp[0] +"' class='input' onchange='" + aTmp[1] + "'>";		
	
	for(q=2; q<aTmp.length; q++)
		tmp += "<option value='"+aTmp[q]+"' id='"+aTmp[++q]+"'>"+aTmp[q]+"</option>";
		
	tmp += "</select>";
	
	obj = fGetObject("div_" + aTmp[0]);
	if(obj)
		obj.innerHTML = tmp;
}	
	
/*a html oldalba a </body> elé kell betenni

<div id="DialogBox" style="display: none;">
	<div class="dialogBoxBorder">
		<div id="dialogContent" class="dialogBoxContent"> </div>
	</div>
</div>
<div id="DialogPreLoading" style="display: none;">
	<center>
		<img class="preSpin" alt="loading" src="../img/preSpin.gif"/>
	</center>
</div>
<div id="DialogBackground" style="display: none;"> </div>
*/

/*a html oldalba be kell linkelni a dialogbox.css-t

<link href="path/dialogbox.css" rel="stylesheet" type="text/css" />

*/

/*template fileokat (kiterjesztésük .tmpl) valahavoa felmásolni és az elérését beállítani

TemplateManager.URL = "../dialogtemplate/";

*/

/*Példák a hazsnálathoz:

dialogManager.add(new Dialog('Üzenet ami megjelenik!', 'alert'));

dialogManager.add(new Dialog(
				"Biztosan törölni akarod?",
				"confirm",
				[ null, function () { self.removeMessage(messageId, folder, true); }, null ],
				[ "", "Igen", "Nem" ])
				);
*/



/**
 * Converts object's properties to Map, except functions
 * @return Converted object
 * @type Map
 * @author Cser Dániel
 */
Object.prototype.toMap = function() {
	var map = new Map();
	
	for (var key in this) {
		if (typeof(this[key]) != "function") {
			map.put(key, this[key]);
		}
	}
	
	return map;
}

/** 
 * Collection used to store data by key-value pairs.
 * @constructor
 * @author Cser Dániel
 */
function Map() {
	
	/**
	 * Data holding maps elements
	 * @type Array
	 */
	var data;
	
	/**
	 * Pointer to this
	 * @type Map
	 */
	var self = this;
	
	/**
	 * Put a value by a given key. If the key already exists, it will be overridden.
	 * @param String Key of data
	 * @param mixed Value of data
	 */
	this.put = function(elementKey, elementValue) {
		for (var i = 0; i < data.length; i++) {
			if (data[i].getKey() == elementKey) {
				data[i].setValue(elementValue);
				return;
			}
		}
		
		data.push(new MapElement(elementKey, elementValue));
	}
	
	/**
	 * Returns value by a given key.
	 * @param String Key of value
	 * @return Found value
	 * @type mixed
	 */
	this.get = function(elementKey) {
		for (var i = 0; i < data.length; i++) {
			if (data[i].getKey() == elementKey) {
				return data[i].getValue();
			}
		}
		
		return null;
	}
	
	/**
	 * Returns true when key is exists in the map
	 * @param String Key of value
	 * @return True when key exists
	 * @type boolean
	 */
	this.containsKey = function(elementKey) {
		for (var i = 0; i < data.length; i++) {
			if (data[i].getKey() == elementKey) {
				return true;
			}
		}
		
		return false;
	}
	
	/**
	 * Returns true when value is exists in the map
	 * @param mixed Value
	 * @return True when value exists
	 * @type boolean
	 */
	this.containsValue = function(elementValue) {
		for (var i = 0; i < data.length; i++) {
			if (data[i].getValue() == elementValue) {
				return true;
			}
		}
		
		return false;
	}
	
	/**
	 * Returns the keyset of thew map
	 * @return Keyset of the map
	 * @type Set
	 */
	this.keys = function() {
		var set = new Set();
		
		for (var i = 0; i < data.length; i++) {
			set.add(data[i].getKey());
		}
		
		return set;
	}
	
	/**
	 * Returns the keyset of thew map
	 * @return Keyset of the map
	 * @type Array
	 */
	this.keysArray = function() {
		var array = new Array();
		
		for (var i = 0; i < data.length; i++) {
			array.push(data[i].getKey());
		}
		
		return array;
	}
	
	/**
	 * Returns the valueset of the map
	 * @return Valueset of the map
	 * @type Set
	 */
	this.values = function() {
		var set = new Set();
		
		for (var i = 0; i < data.length; i++) {
			set.add(data[i].getValue());
		}
		
		return set;
	}
	
	/**
	 * Returns the valueset of the map
	 * @return Valueset of the map
	 * @type Array
	 */
	this.valuesArray = function() {
		var array = new Array();
		
		for (var i = 0; i < data.length; i++) {
			array.push(data[i].getValue());
		}
		
		return array;
	}
	
	/**
	 * Removes an element by the given key
	 * @param String key
	 */
	this.remove = function(elementKey) {
		var newData = new Array();
		
		for (var i = 0; i < data.length; i++) {
			if (data[i].getKey() != elementKey) {
				newData.push(data[i]);
			}
		}
		
		data = newData;
	}
	
	/**
	 * Empties the map
	 */
	this.clear = function() {
		data = new Array();
	}
	
	/**
	 * Returns true when map is empty
	 * @return True when map is empty
	 * @type boolean
	 */
	this.isEmpty = function() {
		return data.length == 0;
	}
	
	/**
	 * Returns the size of the map
	 * @return Size of the map
	 * @type Number
	 */
	this.size = function() {
		return data.length;
	}
	
	/**
	 * Converts map to object
	 * @return Converted map
	 * @type Object
	 */
	this.toObject = function() {
		var obj = new Object();
		
		for (var i = 0; i < data.length; i++) {
			obj[data[i].getKey()] = data[i].getValue();
		}
		
		return obj;
	}
	
	/**
	 * Sorts contained elements by the given function
	 * @param Function Function used to sort
	 */
	this.sort = function(sortBy) {
		data = data.sort(sortBy);
	}
	
	/**
	 * Calls callback on every element of the map
	 * @param Function Callback function
	 */
	this.map = function(callback) {
		for (var i = 0; i < data.length; i++) {
			callback(data[i].getValue());
		}
	}
	
	/**
	 * Returns true if keys and values of maps are equal
	 * @return True if keys and values of maps are equal
	 * @type Boolean
	 */
	this.equalsTo = function(otherMap) {
		if (! checkType(otherMap, Map)) {
			return false;
		}
		
		if (! self.keys().equalsTo(otherMap.keys()) || ! self.values().equalsTo(otherMap.values())) {
			return false;
		}
		
		return true;
	}
	
	/**
	 * Returns the next element relative to the given
	 * @param mixed Key of element
	 * @return The next element relative to the given
	 * @type mixed
	 */
	this.nextElement = function(elementKey) {
		for (var i = 0; i < data.length; i++) {
			if (data[i].getKey() == elementKey) {
				return (data[i + 1] != undefined ? data[i + 1].getValue() : null);
			}
		}
		
		return null;
	}
	
	/**
	 * Returns the previous element relative to the given
	 * @param mixed Key of element
	 * @return The previous element relative to the given
	 * @type mixed
	 */
	this.prevElement = function(elementKey) {
		for (var i = 0; i < data.length; i++) {
			if (data[i].getKey() == elementKey) {
				return (data[i - 1] != undefined ? data[i - 1].getValue() : null);
			}
		}
		
		return null;
	}
	
	//Initialize
	data = new Array();
	
	/**
	 * Internal class for holding a key-value pair
	 * @param String Key of element
	 * @param mixed Value of element
	 */
	function MapElement(elementKey, elementValue) {
		
		/**
		 * Key of element
		 * @type String
		 */
		var key = elementKey;
		
		/**
		 * Value of element
		 * @type mixed
		 */
		var value = elementValue;
		
		/**
		 * Return the key of element
		 * @return Key of element
		 * @type String
		 */
		this.getKey = function() {
			return key;
		}
		
		/**
		 * Returns the value of element
		 * @return Value of element
		 * @type mixed
		 */
		this.getValue = function() {
			return value;
		}
		
		/**
		 * Set the new value of element
		 * @param mixed New value
		 */
		this.setValue = function(elementValue) {
			value = elementValue;
		}
		
	}
	
}

/**
 * Prototype.js style getElementById
 * @param String Id of DOM object
 * @return Found DOM object
 * @type Object
 */
function $(id) {
	return document.getElementById(id);
}

/**
 * Check if the variable is not null and is defined
 * @param mixed Variable to check
 * @return True if it's OK
 * @type Boolean
 */
function check(variable) {
	return (variable != null && variable != undefined);
}

/**
 * Check if the variable is not null and is defined and is instanceof type
 * @param mixed Variable to check
 * @return True if it's OK
 * @type Boolean
 */
function checkType(variable, type) {
	return (variable != null && variable != undefined && variable instanceof type);
}


/**
 * Returns a file content by a given URL
 * @param String URL of file
 * @throws When URL is null
 * @throws When XMLHttpRequest object cannot be created.
 * @return File content
 * @type String
 */
function getStringByUrl(url){
	if (! check(url) || url.length == 0)
		alert("getStringByUrl(): Invalid parameters.");
		
	var randomSeed = Math.floor(Math.random() * (10001));
	
	var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
	
	self.xmlHttpReq.open('GET', url + "?random=" + randomSeed, false);
	self.xmlHttpReq.send(null);
	
	if (self.xmlHttpReq.status != 200) {
		//TODO: Log error
		return;
	}

	return self.xmlHttpReq.responseText;
}


/**
 * Represents an element in the dialog queue
 * @param String Message
 * @param String Type
 * @param Array Callbacks
 * @param Array Captions
 * @author Cser Dániel
 */
function Dialog(dialogMessage, dialogType, dialogCallbacks, dialogCaptions) {
	
	/**
	 * Message
	 * @type String
	 */
	var message;
	
	/**
	 * Type
	 * @type Number
	 */
	var type;
	
	/**
	 * Callbacks
	 * @type Array
	 */
	var callbacks;
	
	/**
	 * Captions
	 * @type Array
	 */
	var captions;
	
	/**
	 * OK constant for captions and callbacks
	 * @type Number
	 */
	Dialog.OK = 0;
	
	/**
	 * YES constant for captions and callbacks
	 * @type Number
	 */
	Dialog.YES = 1;
	
	/**
	 * NO constant for captions and callbacks
	 * @type Number
	 */
	Dialog.NO = 2;
	
	/**
	 * Returns message
	 * @return Message
	 * @type String
	 */
	this.getMessage = function() {
		return message;
	}
	
	/**
	 * Sets message
	 * @param String Message
	 */
	this.setMessage = function(dialogMessage) {
		if (! dialogMessage) {
			//TODO: Log error
			return;
		}
		
		message = String(dialogMessage);
	}
	
	/**
	 * Returns type
	 * @return Type
	 * @type Number
	 */
	this.getType = function() {
		return type;
	}
	
	/**
	 * Sets type
	 * @param Number Type
	 */
	this.setType = function(dialogType) {
		if (! dialogType) {
			//TODO: Log error
			return;
		}
		
		type = Number(dialogType);
	}
	
	/**
	 * Returns the requested callback
	 * @param Number Which callback
	 * @return Requested callback
	 * @type String
	 */
	this.getCallback = function(callbackType) {
		//az összes callback állítása esetén ez nem tömb, ezért ezzel csak az x karaktert adja vissza,
		//mivel String tömbként kezeli, így ezt vizsgálni és kezelni kell
		//return callbacks[Number(callbackType)];
		if( callbacks instanceof Array )
			return callbacks[Number(callbackType)];	
		else
			return callbacks;
	}
	
	/**
	 * Sets the given callback
	 * @param Number Which callback
	 * @param Function Callback function
	 */
	this.setCallback = function(callbackType, dialogCallback) {
		if (! callbackType || ! dialogCallback) {
			//TODO: Log error
			return;
		}
		
		callbacks[Number(callbackType)] = dialogCallback;
	}
	
	/**
	 * Sets all callbacks
	 * @param Array Callback array
	 */
	this.setCallbacks = function(dialogCallbacks) {
		if (! dialogCallbacks || ! dialogCallbacks instanceof Array) {
			//TODO: Log error
			return;
		}
		
		callbacks = dialogCallbacks;
	}
	
	/**
	 * Returns the requested caption
	 * @param Number Which caption
	 * @return Requested caption
	 * @type String
	 */
	this.getCaption = function(captionType) {
		return captions[Number(captionType)];
	}
	
	/**
	 * Sets the given caption
	 * @param Number Which caption
	 * @param String Caption
	 */
	this.setCaption = function(captionType, dialogCaption) {
		if (! captionType || ! dialogCaption) {
			//TODO: Log error
			return;
		}
		
		captions[Number(captionType)] = String(dialogCaption);
	}
	
	/**
	 * Sets all captions
	 * @param Array Captions array
	 */
	this.setCaptions = function(dialogCaptions) {
		if (! dialogCaptions || ! dialogCaptions instanceof Array) {
			//TODO: Log error
			return;
		}
		
		captions = dialogCaptions;
	}
	
	//Initialize
	message = dialogMessage || "";
	type = dialogType || "";
	callbacks = dialogCallbacks || [null, null, null];
	captions = dialogCaptions || ["Ok", "Igen", "Nem"];
	
}

/**
 * Default parser used to parse template
 * @constructor
 * @author Cser Dániel
 */
var DefaultParser = {
	
	/**
	 * Object containing statements
	 * @type Object
	 */
	statements: {
		"if":      { delta: 1,  prefix: "if (", suffix: ") {\n", minParams: 1 },
		
		"elseif":  { delta: 0,  prefix: "} else if (", suffix: ") {\n" },
		
		"else":    { delta: 0,  prefix: "} else {\n" },
		
		"/if":     { delta: -1, prefix: "}\n" },
		
		"for":     {
			delta: 1,
			
			prefix: function(parameters) {
				if (parameters[1] != "in") {
					throw new TemplateParseError("Error parsing template " + name + ", loop with bad parameters: " + parameters.join(" ") + ".");
				}
				
				return [
					"if (typeof(_FORS) == \"undefined\" || ! _FORS.length) {\n  var _FORS = [];\n}\n",
					"_FORS.push(0);\n",
					"if (typeof(" + parameters[2] + ") != \"undefined\" && " + parameters[2] + " instanceof Array) {\n",
					"  var " + parameters[0] + "Array = " + parameters[2] + ";\n",
					"  for (var " + parameters[0] + "Iterator = 0; " + parameters[0] + "Iterator < " + parameters[0] + "Array.length; " + parameters[0] + "Iterator++) {\n",
					"    var " + parameters[0] + " = " + parameters[0] + "Array[" + parameters[0] + "Iterator];\n",
					"    _FORS[_FORS.length - 1]++;\n"].join("");
			},
			
			minParams: 3
		},
		
		"forelse": { delta: 0,  prefix: "  }\n}\n if (_FORS[_FORS.length - 1] == 0) {\n  if (true) {\n" },
		
		"/for":    { delta: -1, prefix: "  }\n}\n" },
		
		"eat":     { delta: 1, prefix: "/*\n" },
		
		"/eat":    { delta: -1, prefix: "*/\n" },
		
		"include": {
			delta: 0,
			
			prefix: function(parameters) {
				var templateName = parameters.shift();
				var templateWith = parameters.shift();
				
				if (templateWith != "with") {
					throw new TemplateParseError("Error parsing template " + name + ", include with bad parameters: " + parameters.join(" ") + ".");
				}
				
				return "_OUT.push(templateManager.getTemplate(" + templateName + ").process({ " + parameters.join(" ") + " }));\n";
			},
			
			minParams: 3 }
	},
	
	/**
	 * Object containing modifiers
	 * @type Object
	 */
	modifiers: {
		//Eats the whole string
		"eat":        function(s) { return ""; },
		
		//Upper-cases string
		"upperCase":  function(s) { return String(s).toUpperCase(); },
		
		//Lower-cases string
		"lowerCase":  function(s) { return String(s).toLowerCase(); },
		
		//Return first param if that is not a nullstring, second param else
		"default":    function(s1, s2) { return String(s1).length > 0 ? s1 : s2; },
		
		//Upper-cases first characters of every word
		"capitalize": function(s) {
			var words = String(s).split(" ");
			var capitalized = [];
			
			for (var i = 0; i < words.length; i++) {
				capitalized.push(this["ucFirst"](words[i]));
			}
			
			return capitalized.join(" ");
		},
		
		//Upper-cases first character
		"ucFirst":    function(s) {
			var oldStr = String(s);
			var newStr = String(oldStr[0]).toUpperCase();
			
			for (var i = 1; i < oldStr.length; i++) {
				newStr += oldStr[i];
			}
			
			return newStr;
		},
		
		//Lower-cases first character
		"lcFirst":    function(s) {
			var oldStr = String(s);
			var newStr = String(oldStr[0]).toLowerCase();
			
			for (var i = 0; i < oldStr.length; i++) {
				newStr += oldStr[i];
			}
			
			return newStr;
		},
		
		//Trims whitespaces form the beginning and end of the string
		"trim":       function(s) { return String(s).replace(/^\s+|\s+$/, ''); }
	}
	
}



/**
 * Represents a parsed template
 * @constructor
 * @author Cser Dániel
 */
function Template(templateName, tmpl, templateParser) {
	
	/**
	 * Template source
	 * @type String
	 */
	var source;
	
	/**
	 * Parsed string
	 * @type String
	 */
	var template;
	
	/**
	 * Name of template
	 * @type String
	 */
	var name;
	
	/**
	 * Template parser object
	 * @type Object
	 */
	var parser;
	
	/**
	 * Temp variable to check the number of start/end tags
	 * @type Number
	 */
	var delta;
	
	/**
	 * Parses the whole template and return the parsed and eval'd code
	 * @param String Template to parse
	 * @throws TemplateParseError on template parsing errors
	 * @return Parsed template
	 * @type String
	 */
	function parse(tmpl) {
		tmpl = new String(tmpl);
		
		tmpl = tmpl.replace(/\t/g, "    "); //convert \t to four spaces
		tmpl = tmpl.replace(/\r\n/g, "\n"); //convert windows line delimiters to unix style
		tmpl = tmpl.replace(/\r/g, "\n"); //convert macosx line delimiters to unix style
		
		var actualPos = -1;
		var parsed = ["function evalTmpl(_OUT, _CONTEXT, _MODIFIERS) { with (_CONTEXT) {\n"];
		
		while (actualPos + 1 < tmpl.length) {
			var statementStart = tmpl.indexOf("{", actualPos);
			
			if (statementStart < 0) {
				break;
			}
			
			var statementEnd = tmpl.indexOf("}", statementStart + 1);
			
			if (statementEnd < 0) {
				break;
			}
			
			if (tmpl.charAt(statementStart - 1) == "$") { //expression which will be shown
				parseText(parsed, tmpl.substring(actualPos, statementStart - 1));
				parseExpression(parsed, tmpl.substring(statementStart + 1, statementEnd));
			} else { //statement
				parseText(parsed, tmpl.substring(actualPos, statementStart));
				parseStatement(parsed, tmpl.substring(statementStart + 1, statementEnd));
			}
			
			actualPos = statementEnd + 1;
		}
		
		if (delta != 0) {
			throw new TemplateParseError("Error parsing template " + name + ", tag start/end tags number are not the same.");
		}
		
		//last piece of text
		parseText(parsed, tmpl.substring(actualPos, tmpl.length));
		
		parsed.push("} }");
		
		eval(parsed.join(""));
		
		return evalTmpl;
	}
	
	/**
	 * Parses the text
	 * @param Array Array to push results
	 * @param String Text to parse
	 */
	function parseText(out, text) {
		if (! text && text.length == 0) {
			return "";
		}
		
		var nlPrefix = 0; //index to first non-newline in prefix.
	    var nlSuffix = text.length - 1; //index to first non-space/tab in suffix.
	    
	    while (nlPrefix < text.length && text.charAt(nlPrefix) == "\n") {
	    	nlPrefix++;
	    }
	    
	    while (nlSuffix >= 0 && (text.charAt(nlSuffix) == " " || text.charAt(nlSuffix) == "\t")) {
	    	nlSuffix--;
	    }
	    
	    if (nlSuffix < nlPrefix) {
	    	nlSuffix = nlPrefix;
	    }
	    
	    var lines = text.substring(nlPrefix, nlSuffix + 1).split("\n");
	    
	    for (var i = 0; i < lines.length; i++) {
			out.push("_OUT.push(\"" + lines[i].replace(/"/g, "\\\"") + "\");\n");
			
			if (i < lines.length - 1) {
	            out.push('_OUT.push("\\n");\n');
	        }
		}
	}
	
	/**
	 * Parses the expressions
	 * @param Array Array to push results
	 * @param String Expression to parse
	 * @throws TemplateParseError on template parsing errors
	 */
	function parseExpression(out, expression) {
		if (! expression && expression.length == 0) {
			return "";
		}
		
		var modifiers = expression.split("|");
		expression = modifiers.shift();
		
		var expr = expression;
		var parts;
		var modifier;
		
		for (var i = 0; i < modifiers.length; i++) {
			parts = modifiers[i].split(":");
			modifier = parts.shift();
			
			if (parser.modifiers[modifier] == null) {
				throw new TemplateParseError("Error parsing template " + name + ", no such modifier: " + modifier + ".");
			}
			
			expr = "_MODIFIERS[\"" + modifier + "\"](" + expr + (parts.length > 0 ? ", " + parts[0].replace(/"/g, "\"") : "") + ")";
		}
		
		out.push("_OUT.push(" + expr + ");\n");
	}
	
	/**
	 * Parses the statements
	 * @param Array Array to push results
	 * @param String Statements to parse
	 * @throws TemplateParseError on template parsing errors
	 */
	function parseStatement(out, stmt) {
		if (! stmt && stmt.length == 0) {
			return;
		}
		
		parameters = stmt.split(" ");
		statement = parameters.shift();
		
		statement = parser.statements[statement];
		
		if (statement == null) {
			parseText(out, stmt);
		}
		
		delta += statement.delta;
		
		if (delta < 0) {
			throw new TemplateParseError("Error parsing template " + name + ", fewer start tags then end tags.");
		}
		
		if (statement.minParams != null && statement.minParams > parameters.length) {
			throw new TemplateParseError("Error parsing template " + name + ", too few parameters.");
		}
		
		if (typeof(statement.prefix) == "function") {
			out.push(statement.prefix(parameters));
		} else {
			out.push(statement.prefix);
		}
		
		if (statement.suffix != null) {
			out.push(parameters.join(" "));
			out.push(statement.suffix);
		}
	}
	
	/**
	 * Processes the template with the given context
	 * @param Object Context of template
	 * @throws TemplateProcessError template on processing errors
	 * @return Ready-to-use template
	 * @type String
	 */
	this.process = function(context) {
		if (! context || ! template) {
			return "";
		}
		
		var processed = [];
		
		try {
			template(processed, context, parser.modifiers);
		} catch(e) {
			throw new TemplateProcessError(e.message, e.fileName, e.lineNumber, e.stack);
		}
		
		return processed.join("");
	}
	
	/**
	 * Returns HTML source
	 * @return HTML source
	 * @type String
	 */
	this.getSource = function() {
		return source;
	}
	
	//Initialize
	if (! tmpl || ! templateName || tmpl.length == 0 || templateName.length == 0) {
		return null;
	}
	
	if (templateParser != null) {
		parser = templateParser;
	} else {
		parser = DefaultParser;
	}
	
	name = templateName;
	delta = 0;
	source = new String(tmpl);
	template = parse(tmpl);
	
}
/**
 * Loads and caches templates.
 * @constructor
 * @author Cser Dániel
 */
function TemplateManager() {
	
	/**
	 * Base dir of templates.
	 * Set in config.js
	 * @type String
	 */
	TemplateManager.URL = String(utvonal)+"dialogtemplate/";
	
	/**
	 * Map to store templates
	 * @type Map
	 */
	var templates;
	
	/**
	 * Corrects the name of template
	 */
	function correctName(templateName) {
		return String(templateName).toLowerCase();
	}
	
	/**
	 * Returns the template and loads it when necessary
	 * @param String Name of template
	 * @throws On parsing errors
	 * @return Template
	 * @type Template
	 */
	function get(templateName) {
		templateName = correctName(templateName);
		if (! templates.containsKey(templateName)) {
			if (! check(TemplateManager.URL)) {
				//TODO: Log error
				return null;
			}
			
			var templateUrl = TemplateManager.URL + templateName.replace(/_/g, "/") + ".tmpl";
			
			try {
				var templateData = getStringByUrl(templateUrl);
			} catch (e) {
				alert("TemplateHandler.get(): Couldn't read file " + templateUrl + ".");
				//throw new TemplateParseError("TemplateHandler.get(): Couldn't read file " + templateUrl + ".");
			}
			templates.put(templateName, new Template(templateName, templateData));
		}
		return templates.get(templateName);
	}
	
	/**
	 * Returns the given template
	 * @param String Name of template
	 * @throws On parsing errors
	 * @return Template
	 * @type Template
	 */
	this.getTemplate = function(templateName) {
		return get(templateName);
	}
	
	/**
	 * Processes the given template with the given context, then puts it into the given DOM object
	 * @param String Name of template
	 * @param Object Template context
	 * @param String Id of DOM object to put the template
	 * @throws On parsing errors
	 */
	this.processTemplate = function(templateName, templateData, domId) {
		$(domId).innerHTML = get(templateName).process(templateData);
	}
	
	//Initialize
	templates = new Map();
	
}
/**
 * Represents a template parsing error.
 * @constructor
 * @author Cser Dániel
 */
function TemplateParseError(message, fileName, lineNumber, stack) {
	
	/**
	 * Message of error
	 * @type String
	 */
	this.message = message;
	
	/**
	 * Name of the file where the error occured
	 * @type String
	 */
	this.fileName = fileName;
	
	/**
	 * Number of line where the error occured
	 * @type String
	 */
	this.lineNumber = lineNumber;
	
	/**
	 * Stact trace of error
	 * @type Object
	 */
	this.stack = stack;
	
	/**
	 * Name of error
	 * @type String
	 */
	this.name = "TemplateParseError";
	
}
/**
 * Represents a template processing error.
 * @constructor
 * @author Cser Dániel
 */
function TemplateProcessError(message, fileName, lineNumber, stack) {
	
	/**
	 * Message of error
	 * @type String
	 */
	this.message = message;
	
	/**
	 * Name of the file where the error occured
	 * @type String
	 */
	this.fileName = fileName;
	
	/**
	 * Number of line where the error occured
	 * @type String
	 */
	this.lineNumber = lineNumber;
	
	/**
	 * Stact trace of error
	 * @type Object
	 */
	this.stack = stack;
	
	/**
	 * Name of error
	 * @type String
	 */
	this.name = "TemplateProcessError";
	
}




/**
 * Dialog window manager class.
 * @constructor
 * @author Cser Dániel
 */
function DialogManager() {
	
	/**
	 * DialogBox width size
	 * @type integer
	 */
	var width = 310;
	
	/**
	 * DialogBox height size
	 * @type integer
	 */
	var height = 180;

	/**
	 * Array of disabled selects
	 * @type Array
	 */
	var disabledSelects;
	
	/**
	 * Queue array
	 * @type Array
	 */
	var queue;
	
	/**
	 * Running state
	 * @type Boolean
	 */
	var running;
	
	/**
	 * Adds a new task
	 * @param Dialog Dialog to add
	 */
	this.add = function(dialog) {
		//when this is a progress or there's no progress in the queue
		queue.push(dialog);
		//return when already displaying or there's nothing to display
		if (running) {
			return;
		}
		
		//start showing
		this.running = true;
	    
	    //disable active selects
		var allSelects = document.getElementsByTagName("select");
		for (i = 0; i < allSelects.length; i++) {
    		if (allSelects[i].disabled == false) {
    			disabledSelects[i] = allSelects[i];
    			disabledSelects[i].disabled = true;
    		}
			allSelects[i].style.visibility = 'hidden';
    	}
	    
	    //hider div
	    var pageSize = getPageSize();
	    setOpacity( $("DialogBackground"), 0.9 );
	    $("DialogBackground").style.height = pageSize.pageHeight+'px';
	    $("DialogBackground").style.display = "block";
	    
	    //dialog box
	    getWindow( height, width );
	    
	    //start showing
	    show();
	}
	
	/**
	 * Shows a task
	 */
	function show() {
		try {
			window.scrollBy(0, 0);
		    templateManager.processTemplate(queue[0].getType(), { dialog: queue[0] }, "dialogContent");
		} catch(e) {
			//TODO: Log error
		}
	}
	
	/**
	 * One task ended
	 * @param Number Result code
	 */
	this.done = function(result) {		
		
		if (queue.length == 0 || result == null || result == undefined) {
			//TODO: Log error
			return;
		}
		
		var fn = queue[0].getCallback(result);
		if (typeof(fn) == "function") {
			try {
				fn();
			} catch(e) {
				//TODO: Log error
			}
		}
	    //remove first element
	    queue.shift();
	    //when this was the last one in queue
	    if (queue.length == 0) {
	    	running = false;
	    	
			//hide dialog and bakground
			$("DialogBackground").style.display = "none";
			$("DialogBox").style.display = "none";
			$("dialogContent").innerHTML = "";
			//enable all disabled selects and clear the array holding them
	    	for (var i = 0; i < disabledSelects.length; i++) {
		    	disabledSelects[i].disabled = false;
				disabledSelects[i].style.visibility = 'visible';
	    	}
	    	
	    	disabledSelects = new Array();
			
		    return;
	    }
	    show();
	}
	
	/**
	 *
	 */
	this.showBackground = function() {
		var pageSize = getPageSize();
	    setOpacity( $("DialogBackground"), 0.3 );
	    $("DialogBackground").style.height = pageSize.pageHeight + 'px';
	    $("DialogBackground").style.display = "block";
		return;
	}
	
	/**
	 *
	 */
	this.hideBackground = function() {
		$("DialogBackground").style.display = "none";
		return;
	}
	
	/**
	* set DialogBackground style
	* @param htmlObject 
	* @param opacity value
	*/
	function setOpacity(element, value) {
	    if (typeof element == 'string')
		element= $(element);
	    if (value == 1) {
		element.style.opacity = (/Gecko/.test(navigator.userAgent) && !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 0.999999 : 1.0 ;
		if(/MSIE/.test(navigator.userAgent) && !window.opera)
		    element.style.filter = element.style.filter.replace(/alpha\([^\)]*\)/gi,'');
	    } else {
		if(value < 0.00001) value = 0;
		    element.style.opacity = value;
		if(/MSIE/.test(navigator.userAgent) && !window.opera)
		    element.style.filter = element.style.filter.replace(/alpha\([^\)]*\)/gi,'') + 'alpha(opacity='+value*100+')';
	    }
	    return element;
	}
	
	
	/**
	* set DialogBox style and position
	* @param box height
	* @param box width
	*/
	function getWindow(height, width) {
	    var DialogBox = $("DialogBox");
	    var pageSize = getPageSize();
	    var pos = realOffset(document.body);
	    
	    DialogBox.style.top = (pageSize.windowHeight/2 - height/2 + pos[1])+'px';
	    DialogBox.style.left = (pageSize.windowWidth/2 - width/2 + pos[0])+'px';
	    
	    DialogBox.style.display = "block";
	}
	
	/**
	* set DialogBox real position
	* @return top, left size
	* @type Array
	*/
	function realOffset(element) {
	    var valueT = 0, valueL = 0;
	    do {
		valueT += element.scrollTop  || 0;
		valueL += element.scrollLeft || 0;
		element = element.parentNode;
	    } while (element);
	    return [valueL, valueT];
	}
	
	
	/**
	* get page, widow, scroll height and width size 
	* @return size data
	* @type object
	*/
	function getPageSize() {
	    var xScroll, yScroll;
            if (window.innerHeight && window.scrollMaxY) {
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	    } else if (document.body.scrollHeight > document.body.offsetHeight) {
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	    } else {
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	    }
	    
	    var windowWidth, windowHeight;
	    if (self.innerHeight) {
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	    } else if (document.documentElement && document.documentElement.clientHeight) {
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	    } else if (document.body) {
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	    }
	    
	    if(yScroll < windowHeight) {
		pageHeight = windowHeight;
	    } else {
		pageHeight = yScroll;
	    }
            if(xScroll < windowWidth) {
	        pageWidth = windowWidth;
	    } else {
		pageWidth = xScroll;
	    }
	    return {
		'pageWidth':pageWidth,
		'pageHeight':pageHeight,
		'windowWidth':windowWidth,
		'windowHeight':windowHeight,
		'yScroll':yScroll,
		'xScroll':xScroll
	    }
	}
	
	//Initialize
	disabledSelects = new Array();
	queue = new Array();
	running = false;
	
}

templateManager = new TemplateManager();
dialogManager = new DialogManager();	
	
/* =================================================================================================
 * TransMenu 
 * March, 2003
 *
 * Customizable multi-level animated DHTML menus with transparency.
 *
 * Copyright 2003-2004, Aaron Boodman (www.youngpup.net)
 * =================================================================================================
 * "Can I use this?"
 * 
 * Use of this library is governed by the Creative Commons Attribution 2.0 License. You can check it 
 * out at: http://creativecommons.org/licenses/by/2.0/
 *
 * Basically: You may copy, distribute, and eat this code as you wish. But you must give me credit 
 * for writing it. You may not misrepresent yourself as the author of this code.
 * =================================================================================================
 * "It's kinda hard to read, though"
 *
 * The uncompressed, commented version of this script can be found at: 
 * http://youngpup.net/projects/transMenus
 * =================================================================================================
 * updates:
 * 04.19.04 fixed cascade problem with menus nested greater than two levels.
 * 12.23.03 added hideCurrent for menu actuators with no menus. renamed to TransMenu.
 * 04.18.03	fixed render bug in IE 5.0 Mac by removing that browser from compatibility table ;)
 *			also made gecko check a little more strict by specifying build no.
 * ============================================================================================== */



//==================================================================================================
// Configuration properties
//==================================================================================================
//==================================================================================================
TransMenu.spacerGif = "";                     // path to a transparent spacer gif
TransMenu.dingbatOn = "";            // path to the active sub menu dingbat
TransMenu.dingbatOff = "";          // path to the inactive sub menu dingbat
TransMenu.dingbatSize = 8;                            // size of the dingbat (square shape assumed)
TransMenu.menuPadding = 0;                             // padding between menu border and items grid
TransMenu.itemPadding = 5;                             // additional padding around each item
TransMenu.shadowSize = 0;                              // size of shadow under menu
TransMenu.shadowOffset = 0;                            // distance shadow should be offset from leading edge
TransMenu.shadowColor = "";                        // color of shadow (transparency is set in CSS)
TransMenu.shadowPng = "";               // a PNG graphic to serve as the shadow for mac IE5
TransMenu.backgroundColor = "";                   // color of the background (transparency set in CSS)
TransMenu.backgroundPng = "";          // a PNG graphic to server as the background for mac IE5
TransMenu.hideDelay = 1000;                            // number of milliseconds to wait before hiding a menu
TransMenu.slideTime = 400;                             // number of milliseconds it takes to open and close a menu
TransMenu.subpad_x = 0;								   // Horizontal Padding between top right corner of item menu and its submenu (level > 2)
TransMenu.subpad_y = -2;							   // Vertical Padding between top right corner of item menu and its submenu (level > 2)

//==================================================================================================
// Internal use properties
//==================================================================================================
TransMenu.reference = {topLeft:1,topRight:2,bottomLeft:3,bottomRight:4};
TransMenu.direction = {down:1,right:2};
TransMenu.registry = [];
TransMenu._maxZ = 100;

TransMenu.updateImgPath = function (imgPath){
	TransMenu.spacerGif = imgPath + TransMenu.spacerGif;
	TransMenu.dingbatOn = imgPath + TransMenu.dingbatOn;
	TransMenu.dingbatOff = imgPath + TransMenu.dingbatOff;
	TransMenu.shadowPng = imgPath + TransMenu.shadowPng;
	TransMenu.backgroundPng = imgPath + TransMenu.backgroundPng;
}

//==================================================================================================
// Static methods
//==================================================================================================
// supporting win ie5+, mac ie5.1+ and gecko >= mozilla 1.0
TransMenu.isSupported = function() {
        var ua = navigator.userAgent.toLowerCase();
		var pf = navigator.platform.toLowerCase();
        var an = navigator.appName;
        var r = false;

        if (ua.indexOf("gecko") > -1 && navigator.productSub >= 20020605) r = true; // gecko >= moz 1.0
        else if (an == "Microsoft Internet Explorer") {
                if (document.getElementById) { // ie5.1+ mac,win
                        if (pf.indexOf("mac") == 0) {
							r = /msie (\d(.\d*)?)/.test(ua) && Number(RegExp.$1) >= 5.1;
						}
						else r = true;
                }
        }

        return r;
}

// call this in onload once menus have been created
TransMenu.initialize = function() {
        for (var i = 0, menu = null; menu = this.registry[i]; i++) {
                menu.initialize();
        }
}

// call this in document body to write out menu html
TransMenu.renderAll = function() {
        var aMenuHtml = [];
        for (var i = 0, menu = null; menu = this.registry[i]; i++) {
                aMenuHtml[i] = menu.toString();
        }
        document.write(aMenuHtml.join(""));
}

//==================================================================================================
// TransMenu constructor (only called internally)
//==================================================================================================
// oActuator            : The thing that causes the menu to be shown when it is mousedover. Either a
//                        reference to an HTML element, or a TransMenuItem from an existing menu.
// iDirection           : The direction to slide out. One of TransMenu.direction.
// iLeft                : Left pixel offset of menu from actuator
// iTop                 : Top pixel offset of menu from actuator
// iReferencePoint      : Corner of actuator to measure from. One of TransMenu.referencePoint.
// parentMenuSet        : Menuset this menu will be added to.
//==================================================================================================
function TransMenu(oActuator, iDirection, iLeft, iTop, iReferencePoint, parentMenuSet) {
        // public methods
        this.addItem = addItem;
        this.addMenu = addMenu;
        this.toString = toString;
        this.initialize = initialize;
        this.isOpen = false;
        this.show = show;
        this.hide = hide;
        this.items = [];

        // events
        this.onactivate = new Function();       // when the menu starts to slide open
        this.ondeactivate = new Function();     // when the menu finishes sliding closed
        this.onmouseover = new Function();      // when the menu has been moused over
        this.onqueue = new Function();          // hack .. when the menu sets a timer to be closed a little while in the future
		this.ondequeue = new Function();

        // initialization
        this.index = TransMenu.registry.length;
        TransMenu.registry[this.index] = this;

        var id = "TransMenu" + this.index;
        var contentHeight = null;
        var contentWidth = null;
        var childMenuSet = null;
        var animating = false;
        var childMenus = [];
        var slideAccel = -1;
        var elmCache = null;
        var ready = false;
        var _this = this;
        var a = null;

        var pos = iDirection == TransMenu.direction.down ? "top" : "left";
        var dim = null;

        // private and public method implimentations
        function addItem(sText, sUrl, browserNav, active) {
                var item = new TransMenuItem(sText, sUrl, this, browserNav, active);
                item._index = this.items.length;
                this.items[item._index] = item;
        }

        function addMenu(oMenuItem) {
                if (!oMenuItem.parentMenu == this) throw new Error("Cannot add a menu here");

                if (childMenuSet == null) childMenuSet = new TransMenuSet(TransMenu.direction.right, TransMenu.subpad_x, TransMenu.subpad_y, TransMenu.reference.topRight);

                var m = childMenuSet.addMenu(oMenuItem);

                childMenus[oMenuItem._index] = m;
                m.onmouseover = child_mouseover;
                m.ondeactivate = child_deactivate;
                m.onqueue = child_queue;
				m.ondequeue = child_dequeue;

                return m;
        }

        function initialize() {
                initCache();
                initEvents();
                initSize();
                ready = true;
        }

        function show() {
                //dbg_dump("show");
                if (ready) {
                        _this.isOpen = true;
                        animating = true;
                        setContainerPos();
                        elmCache["clip"].style.visibility = "visible";
                        elmCache["clip"].style.zIndex = TransMenu._maxZ++;
                        //dbg_dump("maxZ: " + TransMenu._maxZ);
                        slideStart();
                        _this.onactivate();
                }
        }

        function hide() {
                if (ready) {
                        _this.isOpen = false;
                        animating = true;

                        for (var i = 0, item = null; item = elmCache.item[i]; i++) 
                                dehighlight(item);

                        if (childMenuSet) childMenuSet.hide();

                        slideStart();
                        _this.ondeactivate();
                        
                        if (!oActuator.parentMenu) {
                        	oActuator.className = oActuator.className.replace(/ jahover-active/, '');
                        	oActuator.className = oActuator.className.replace(/ jahover/, '');
                        }
                }
        }

        function setContainerPos() {
                var sub = oActuator.constructor == TransMenuItem; 
                var act = sub ? oActuator.parentMenu.elmCache["item"][oActuator._index] : oActuator; 
                var el = act;
                
                var x = 0;
                var y = 0;

                
                var minX = 0;
                var maxX = (window.innerWidth ? window.innerWidth : document.body.clientWidth) - parseInt(elmCache["clip"].style.width);
                var minY = 0;
                var maxY = (window.innerHeight ? window.innerHeight : document.body.clientHeight) - parseInt(elmCache["clip"].style.height);
				maxX = 10000;
				maxY = 10000;

                // add up all offsets... subtract any scroll offset
                while (sub ? el.parentNode.className.indexOf("transMenu") == -1 : el.offsetParent) {
                        x += el.offsetLeft;
                        y += el.offsetTop;

                        if (el.scrollLeft) x -= el.scrollLeft;
                        if (el.scrollTop) y -= el.scrollTop;
                        
                        el = el.offsetParent;
                }

                if (oActuator.constructor == TransMenuItem) {
                        x += parseInt(el.parentNode.style.left);
                        y += parseInt(el.parentNode.style.top);
                }

                switch (iReferencePoint) {
                        case TransMenu.reference.topLeft:
                                break;
                        case TransMenu.reference.topRight:
                                x += act.offsetWidth;
                                break;
                        case TransMenu.reference.bottomLeft:
                                y += act.offsetHeight;
                                break;
                        case TransMenu.reference.bottomRight:
                                x += act.offsetWidth;
                                y += act.offsetHeight;
                                break;
                }

                x += iLeft;
                y += iTop;

                x = Math.max(Math.min(x, maxX), minX);
                y = Math.max(Math.min(y, maxY), minY);

                elmCache["clip"].style.left = x + "px";
                elmCache["clip"].style.top = y + "px";
        }

        function slideStart() {
                var x0 = parseInt(elmCache["content"].style[pos]);
                var x1 = _this.isOpen ? 0 : -dim;

                if (a != null) a.stop();
                a = new Accelimation(x0, x1, TransMenu.slideTime, slideAccel);

                a.onframe = slideFrame;
                a.onend = slideEnd;

                a.start();
        }

        function slideFrame(x) {
                elmCache["content"].style[pos] = x + "px";
        }

        function slideEnd() {
                if (!_this.isOpen) elmCache["clip"].style.visibility = "hidden";
                animating = false;
        }

        function initSize() {
                // everything is based off the size of the items table...
                var ow = elmCache["items"].offsetWidth;
                var oh = elmCache["items"].offsetHeight;
                var ua = navigator.userAgent.toLowerCase();

                // clipping container should be ow/oh + the size of the shadow
                elmCache["clip"].style.width = ow + TransMenu.shadowSize +  2 + "px";
                elmCache["clip"].style.height = oh + TransMenu.shadowSize + 2 + "px";

                // same with content...
                elmCache["content"].style.width = ow + TransMenu.shadowSize + "px";
                elmCache["content"].style.height = oh + TransMenu.shadowSize + "px";

                contentHeight = oh + TransMenu.shadowSize;
                contentWidth = ow + TransMenu.shadowSize;
                
                dim = iDirection == TransMenu.direction.down ? contentHeight : contentWidth;

                // set initially closed
                elmCache["content"].style[pos] = -dim - TransMenu.shadowSize + "px";
                elmCache["clip"].style.visibility = "hidden";

                // if *not* mac/ie 5
                if (ua.indexOf("mac") == -1 || ua.indexOf("gecko") > -1) {
                        // set background div to offset size
                        elmCache["background"].style.width = ow + "px";
                        elmCache["background"].style.height = oh + "px";
                        elmCache["background"].style.backgroundColor = TransMenu.backgroundColor;

                        // shadow left starts at offset left and is offsetHeight pixels high
                        elmCache["shadowRight"].style.left = ow + "px";
                        elmCache["shadowRight"].style.height = oh - (TransMenu.shadowOffset - TransMenu.shadowSize) + "px";
                        elmCache["shadowRight"].style.backgroundColor = TransMenu.shadowColor;

                        // shadow bottom starts at offset height and is offsetWidth - shadowOffset 
                        // pixels wide (we don't want the bottom and right shadows to overlap or we 
                        // get an extra bright bottom-right corner)
                        elmCache["shadowBottom"].style.top = oh + "px";
                        elmCache["shadowBottom"].style.width = ow - TransMenu.shadowOffset + "px";
                        elmCache["shadowBottom"].style.backgroundColor = TransMenu.shadowColor;
                }
                // mac ie is a little different because we use a PNG for the transparency
                else {
                        // set background div to offset size
                        elmCache["background"].firstChild.src = TransMenu.backgroundPng;
                        elmCache["background"].firstChild.width = ow;
                        elmCache["background"].firstChild.height = oh;

                        // shadow left starts at offset left and is offsetHeight pixels high
                        elmCache["shadowRight"].firstChild.src = TransMenu.shadowPng;
                        elmCache["shadowRight"].style.left = ow + "px";
                        elmCache["shadowRight"].firstChild.width = TransMenu.shadowSize;
                        elmCache["shadowRight"].firstChild.height = oh - (TransMenu.shadowOffset - TransMenu.shadowSize);

                        // shadow bottom starts at offset height and is offsetWidth - shadowOffset 
                        // pixels wide (we don't want the bottom and right shadows to overlap or we 
                        // get an extra bright bottom-right corner)
                        elmCache["shadowBottom"].firstChild.src = TransMenu.shadowPng;
                        elmCache["shadowBottom"].style.top = oh + "px";
                        elmCache["shadowBottom"].firstChild.height = TransMenu.shadowSize;
                        elmCache["shadowBottom"].firstChild.width = ow - TransMenu.shadowOffset;
                }
        }
        
        function initCache() {
                var menu = document.getElementById(id);
                var all = menu.all ? menu.all : menu.getElementsByTagName("*"); // IE/win doesn't support * syntax, but does have the document.all thing

                elmCache = {};
                elmCache["clip"] = menu;
                elmCache["item"] = [];
                
                for (var i = 0, elm = null; elm = all[i]; i++) {
                        switch (elm.className) {
                                case "items":
                                case "content":
                                case "background":
                                case "shadowRight":
                                case "shadowBottom":
                                        elmCache[elm.className] = elm;
                                        break;
                                case "item":
                                        elm._index = elmCache["item"].length;
                                        elmCache["item"][elm._index] = elm;
                                        break;
                        }
                }

                // hack!
                _this.elmCache = elmCache;
        }

        function initEvents() {
                // hook item mouseover
                for (var i = 0, item = null; item = elmCache.item[i]; i++) {
                        item.onmouseover = item_mouseover;
                        item.onmouseout = item_mouseout;
                        item.onclick = item_click;
                }

                // hook actuation
                if (typeof oActuator.tagName != "undefined") {
                        oActuator.onmouseover = actuator_mouseover;
                        oActuator.onmouseout = actuator_mouseout;
                }

                // hook menu mouseover
                elmCache["content"].onmouseover = content_mouseover;
                elmCache["content"].onmouseout = content_mouseout;
        }

        function highlight(oRow) {
                oRow.className = "item hover";
                if (childMenus[oRow._index]) 
                        oRow.lastChild.firstChild.src = TransMenu.dingbatOn;
        }

        function dehighlight(oRow) {
                oRow.className = "item";
                if (childMenus[oRow._index]) 
                        oRow.lastChild.firstChild.src = TransMenu.dingbatOff;
        }

        function item_mouseover() {
                if (!animating) {
                        highlight(this);

                        if (childMenus[this._index]) 
                                childMenuSet.showMenu(childMenus[this._index]);
                        else if (childMenuSet) childMenuSet.hide();
                }
        }

        function item_mouseout() {
                if (!animating) {
                        if (childMenus[this._index])
                                childMenuSet.hideMenu(childMenus[this._index]);
                        else    // otherwise child_deactivate will do this
                                dehighlight(this);
                }
        }

        function item_click() {
                if (!animating) {
                        if (_this.items[this._index].url) {
							switch (_this.items[this._index].browserNav) {
								// cases are slightly different
								case 1:
								// open in a new window
								window.open(_this.items[this._index].url, '', '');;
									
								break;

								case 2:
								// open in a popup window
								window.open(_this.items[this._index].url, '', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=550');;
								break;

								case 3:
								// don't link it
								break;

								default:	// formerly case 2
								// open in parent window
								location.href = _this.items[this._index].url;
								break;
							}
						}
                }
        }

        function actuator_mouseover() {
                parentMenuSet.showMenu(_this);
                if (!oActuator.parentMenu) {
                	if (oActuator.className.indexOf(' jahover') < 0){
                		if (oActuator.className.indexOf('-active') < 0)
                			oActuator.className += ' jahover';
                		else
                			oActuator.className += ' jahover-active';              			
                	}
                }
        }

        function actuator_mouseout() {
                parentMenuSet.hideMenu(_this);
        }

        function content_mouseover() {
                if (!animating) {
                        parentMenuSet.showMenu(_this);
                        _this.onmouseover();
                }
        }

        function content_mouseout() {
                if (!animating) {
                        parentMenuSet.hideMenu(_this);
                }
        }

        function child_mouseover() {
                if (!animating) {
                        parentMenuSet.showMenu(_this);
                }
        }

        function child_deactivate() {
                for (var i = 0; i < childMenus.length; i++) {
                        if (childMenus[i] == this) {
                                dehighlight(elmCache["item"][i]);
                                break;
                        }
                }
        }

        function child_queue() {
                parentMenuSet.hideMenu(_this);
        }

		function child_dequeue() {
				parentMenuSet.showMenu(_this);
		}

        function toString() {
                var aHtml = [];
                var sClassName = "transMenu" + (oActuator.constructor != TransMenuItem ? " top" : "");

                for (var i = 0, item = null; item = this.items[i]; i++) {
                        aHtml[i] = item.toString(childMenus[i]);
                }
				aHtml[i] = '<tr><td colspan="2" align="left" valign="top"><table cellpadding="0" cellspacing="0" border="0" style="width:100%;"><tr><td style="height:5px; width:5px;" align="left" valign="top"><img src="../img/bg-almenu-left.png" alt="Agria Park | Menu left spacer image" style="height:5px; width:5px;"/></td><td style="background-color:#ef8c00; height:5px;"><img src="../img/spacer.gif" alt="Agria Park | Menu spacer image" /></td><td valign="top" align="right" style="width:5px; height:5px;"><img src="../img/bg-almenu-right.png" alt="Agria Park | Menu right spacer image" style="height:5px; width:5px;"/></td></tr></table></td></tr>';

                return '<div id="' + id + '" class="' + sClassName + '" style="margin-left:-1px;">' + 
                        '<div class="content"><table class="items" cellpadding="0" cellspacing="0" border="0"><tr><td colspan="2" align="left" valign="top" style="height:3px;background-color:#ef8c00;"><img src="../img/spacer.gif" alt="Agria Park | Menu spacer image" /></td></tr>' + 
                        aHtml.join('') + 
                        '</table>' + 
                        '<div class="shadowBottom"></div>' + 
                        '<div class="shadowRight"></div>' + 
		        '<div class="background" style="background-color:none;"></div>' + 
	                '</div></div>';
        }
}


//==================================================================================================
// TransMenuSet
//==================================================================================================
// iDirection           : The direction to slide out. One of TransMenu.direction.
// iLeft                : Left pixel offset of menus from actuator
// iTop                 : Top pixel offset of menus from actuator
// iReferencePoint      : Corner of actuator to measure from. One of TransMenu.referencePoint.
//==================================================================================================
TransMenuSet.registry = [];

function TransMenuSet(iDirection, iLeft, iTop, iReferencePoint) {
        // public methods
        this.addMenu = addMenu;
        this.showMenu = showMenu;
        this.hideMenu = hideMenu;
        this.hide = hide;
        this.hideCurrent = hideCurrent;

        // initialization
        var menus = [];
        var _this = this;
        var current = null;

        this.index = TransMenuSet.registry.length;
        TransMenuSet.registry[this.index] = this;

        // method implimentations...
        function addMenu(oActuator) {
                var m = new TransMenu(oActuator, iDirection, iLeft, iTop, iReferencePoint, this);
                menus[menus.length] = m;
                return m;
        }

        function showMenu(oMenu) {
                if (oMenu != current) {
                        // close currently open menu
                        if (current != null) hide(current);        

                        // set current menu to this one
                        current = oMenu;

                        // if this menu is closed, open it
                        oMenu.show();
                }
                else {
                        // hide pending calls to close this menu
                        cancelHide(oMenu);
                }
        }

        function hideMenu(oMenu) {
                //dbg_dump("hideMenu a " + oMenu.index);
                if (current == oMenu && oMenu.isOpen) {
                        //dbg_dump("hideMenu b " + oMenu.index);
                        if (!oMenu.hideTimer) scheduleHide(oMenu);
                }
        }

        function scheduleHide(oMenu) {
                //dbg_dump("scheduleHide " + oMenu.index);
                oMenu.onqueue();
                oMenu.hideTimer = window.setTimeout("TransMenuSet.registry[" + _this.index + "].hide(TransMenu.registry[" + oMenu.index + "])", TransMenu.hideDelay);
        }

        function cancelHide(oMenu) {
                //dbg_dump("cancelHide " + oMenu.index);
                if (oMenu.hideTimer) {
						oMenu.ondequeue();
                        window.clearTimeout(oMenu.hideTimer);
                        oMenu.hideTimer = null;
                }
        }

        function hide(oMenu) {   
                if (!oMenu && current) oMenu = current;

                if (oMenu && current == oMenu && oMenu.isOpen) {
                        hideCurrent();
                }
        }

        function hideCurrent() {
				if (null != current) {
					cancelHide(current);
					current.hideTimer = null;
					current.hide();
					current = null;
				}
        }
}

//==================================================================================================
// TransMenuItem (internal)
// represents an item in a dropdown
//==================================================================================================
// sText        : The item display text
// sUrl         : URL to load when the item is clicked
// oParent      : Menu this item is a part of
//==================================================================================================
function TransMenuItem(sText, sUrl, oParent, browserNav, active) {
        this.toString = toString;
        this.text = sText;
        this.url = sUrl;
		this.browserNav = browserNav;
        this.parentMenu = oParent;
		this.active = active;

        function toString(bDingbat) {
                var sDingbat = bDingbat ? TransMenu.dingbatOff : TransMenu.spacerGif;
                var iEdgePadding = TransMenu.itemPadding + TransMenu.menuPadding;
                var sPaddingLeft = "padding:" + TransMenu.itemPadding + "px; padding-left:" + iEdgePadding + "px;"
                var sPaddingRight = "padding:" + TransMenu.itemPadding + "px; padding-right:" + iEdgePadding + "px;"
				var id = active?' id="active" ':'';
					/*return '<tr class="item"'+id+'><td nowrap style="' + sPaddingLeft + sPaddingRight + '"><div style="background: url(' + sDingbat + ') right no-repeat;">' + 
                        sText + '</div></td></tr>';*/
                return '<tr class="item"'+id+'><td nowrap style="padding:1px 30px;"  align="left" valign="top">' + 
                        sText + '</td><td style="width:10px;" align="left" valign="top">' + 
                        '</td></tr>';
        }
}

//=====================================================================
// Accel[erated] [an]imation object
// change a property of an object over time in an accelerated fashion
//=====================================================================
// obj  : reference to the object whose property you'd like to animate
// prop : property you would like to change eg: "left"
// to   : final value of prop
// time : time the animation should take to run
// zip	: optional. specify the zippiness of the acceleration. pick a 
//		  number between -1 and 1 where -1 is full decelerated, 1 is 
//		  full accelerated, and 0 is linear (no acceleration). default
//		  is 0.
// unit	: optional. specify the units for use with prop. default is 
//		  "px".
//=====================================================================
// bezier functions lifted from the lib_animation.js file in the 
// 13th Parallel API. www.13thparallel.org
//=====================================================================

function Accelimation(from, to, time, zip) {
	if (typeof zip  == "undefined") zip  = 0;
	if (typeof unit == "undefined") unit = "px";

        this.x0         = from;
        this.x1		= to;
	this.dt		= time;
	this.zip	= -zip;
	this.unit	= unit;
	this.timer	= null;
	this.onend	= new Function();
        this.onframe    = new Function();
}



//=====================================================================
// public methods
//=====================================================================

// after you create an accelimation, you call this to start it-a runnin'
Accelimation.prototype.start = function() {
	this.t0 = new Date().getTime();
	this.t1 = this.t0 + this.dt;
	var dx	= this.x1 - this.x0;
	this.c1 = this.x0 + ((1 + this.zip) * dx / 3);
	this.c2 = this.x0 + ((2 + this.zip) * dx / 3);
	Accelimation._add(this);
}

// and if you need to stop it early for some reason...
Accelimation.prototype.stop = function() {
	Accelimation._remove(this);
}



//=====================================================================
// private methods
//=====================================================================

// paints one frame. gets called by Accelimation._paintAll.
Accelimation.prototype._paint = function(time) {
	if (time < this.t1) {
		var elapsed = time - this.t0;
	        this.onframe(Accelimation._getBezier(elapsed/this.dt,this.x0,this.x1,this.c1,this.c2));
        }
	else this._end();
}

// ends the animation
Accelimation.prototype._end = function() {
	Accelimation._remove(this);
        this.onframe(this.x1);
	this.onend();
}




//=====================================================================
// static methods (all private)
//=====================================================================

// add a function to the list of ones to call periodically
Accelimation._add = function(o) {
	var index = this.instances.length;
	this.instances[index] = o;
	// if this is the first one, start the engine
	if (this.instances.length == 1) {
		this.timerID = window.setInterval("Accelimation._paintAll()", this.targetRes);
	}
}

// remove a function from the list
Accelimation._remove = function(o) {
	for (var i = 0; i < this.instances.length; i++) {
		if (o == this.instances[i]) {
			this.instances = this.instances.slice(0,i).concat( this.instances.slice(i+1) );
			break;
		}
	}
	// if that was the last one, stop the engine
	if (this.instances.length == 0) {
		window.clearInterval(this.timerID);
		this.timerID = null;
	}
}

// "engine" - call each function in the list every so often
Accelimation._paintAll = function() {
	var now = new Date().getTime();
	for (var i = 0; i < this.instances.length; i++) {
		this.instances[i]._paint(now);
	}
}


// Bezier functions:
Accelimation._B1 = function(t) { return t*t*t }
Accelimation._B2 = function(t) { return 3*t*t*(1-t) }
Accelimation._B3 = function(t) { return 3*t*(1-t)*(1-t) }
Accelimation._B4 = function(t) { return (1-t)*(1-t)*(1-t) }


//Finds the coordinates of a point at a certain stage through a bezier curve
Accelimation._getBezier = function(percent,startPos,endPos,control1,control2) {
	return endPos * this._B1(percent) + control2 * this._B2(percent) + control1 * this._B3(percent) + startPos * this._B4(percent);
}


//=====================================================================
// static properties
//=====================================================================

Accelimation.instances = [];
Accelimation.targetRes = 10;
Accelimation.timerID = null;


//=====================================================================
// IE win memory cleanup
//=====================================================================

if (window.attachEvent) {
	var cearElementProps = [
		'data',
		'onmouseover',
		'onmouseout',
		'onmousedown',
		'onmouseup',
		'ondblclick',
		'onclick',
		'onselectstart',
		'oncontextmenu'
	];

	window.attachEvent("onunload", function() {
        var el;
        for(var d = document.all.length;d--;){
            el = document.all[d];
            for(var c = cearElementProps.length;c--;){
                el[cearElementProps[c]] = null;
            }
        }
	});
}
	
	
var NS4 = (document.layers)? 1 : 0;
var IE4 = (document.all)? 1 : 0;
var W3C = (document.getElementById)? 1 : 0;
var aGalery = new Array();

function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}

function fClickCsoport2(csid, color){
	h = 0;
	while(fGetObject('csopuzletek_'+String(++h))){
		fGetObject('csopuzletek_'+String(h)).style.display = "none";
		fGetObject('csop_'+String(h)).style.color = "#818084";
	}
	fGetObject('csopuzletek_'+String(csid)).style.display = "block";
	fGetObject('csop_'+String(csid)).style.color = "#"+String(color);	
}

function fClickCsoport(csid, color){
	h = 0;
	while(fGetObject('csopuzletek_'+String(++h))){
		fGetObject('csopuzletek_'+String(h)).style.display = "none";
		fGetObject('csop_'+String(h)).style.color = "#818084";
	}
	fGetObject('csopuzletek_'+String(csid)).style.display = "block";
	fGetObject('csop_'+String(csid)).style.color = "#"+String(color);
	fCallFlash('uzletkereso','newCsoport',csid);
}

function fCallFlash(pFlashId, pfunction, param) {
	obj = thisMovie(pFlashId);
	if(pfunction == "newCsoport")
	    obj.newCsoport(param);
	else if(pfunction == "clickUzlet")
		obj.clickUzlet(param);
}

function fCheckBox(obj){
	var allapot = new String(obj.value);
	if(allapot == '0' )
		obj.value = '1';
	if(allapot == '1' )
		obj.value = '0';	
}
function fSikKon1(){
	alert('Üzenet küldése sikeres, kollégánk hamarosan válaszolni fog!');
}
function fNSikKon1(){
	alert('Üzenet küldése sikertelen, hiányzó e-mail cím!');
}
function fBadFel1(){
	alert('Hiányzó adatok, feliratkozás sikertelen!');
}

function fBadFel2(){
	alert('Feliratkozás sikertelen, ezzel az e-mail címmel már regisztráltak!');
}

function fFel1(){
	alert('Ön sikeresen regisztrált az Agria Park hírlevelére!');
}

function fUzletKer(cid){
	for(i = 1; i < 4; i++){
		if(fGetObject('szint_'+String(i))) { fGetObject('szint_'+String(i)).style.display = "none"; }
		if(fGetObject('uzlet_'+String(i))) { fGetObject('uzlet_'+String(i)).style.display = "none"; }
	}
	for(i = 1; i < 4; i++){
		if(i == cid){
			if(fGetObject('szint_'+String(i))) { fGetObject('szint_'+String(i)).style.display = "block"; }
			if(fGetObject('uzlet_'+String(i))) { fGetObject('uzlet_'+String(i)).style.display = "block"; }
		}
	}	
}

function fMutat(cid, mutat){
	if(mutat == 1){
		fGetObject(String(cid)+'_reszlet').style.display = "none";
		fGetObject(String(cid)+'_tartalom').style.display = "block";
	}else if(mutat == 0){
		fGetObject(String(cid)+'_reszlet').style.display = "block";
		fGetObject(String(cid)+'_tartalom').style.display = "none";
	}
}

function fCheckHirlevel(){
	if(fGetObject('snev').value == ''){
		alert('Kérem adja meg a nevét!');
		fGetObject('snev').focus();
		return  false;
	}
	if(fGetObject('semail').value == ''){
		alert('Kérem adja meg e-mail címét!');
		fGetObject('semail').focus();
		return  false;
	}
	var strtmp = new String(fGetObject('semail').value);
	if(strtmp.indexOf("@") == -1 || strtmp.indexOf(".") == -1){
		alert('Az e-mail cím formailag nem megfelelő!');
		fGetObject('semail').focus();
		return false;
	}
	return true;
}

function fCheckKontakt(){
	if(fGetObject('snev').value == ''){
		alert('Kérem adja meg a nevét!');
		fGetObject('snev').focus();
		return  false;
	}
	if(fGetObject('semail').value == ''){
		alert('Kérem adja meg e-mail címét!');
		fGetObject('semail').focus();
		return  false;
	}
	var strtmp = new String(fGetObject('semail').value);
	if(strtmp.indexOf("@") == -1 || strtmp.indexOf(".") == -1){
		alert('Az e-mail cím formailag nem megfelelő!');
		fGetObject('semail').focus();
		return false;
	}
	if(fGetObject('stargy').value == ''){
		alert('Kérem adja meg az üzenet tárgyát!');
		fGetObject('stargy').focus();
		return  false;
	}
	if(fGetObject('sszoveg').value == ''){
		alert('Kérem adja meg az üzenet szövegét!');
		fGetObject('sszoveg').focus();
		return  false;
	}
	return true;
}

function betolt(){
//==========================================================================================
// if supported, initialize TransMenus
//==========================================================================================
// Check isSupported() so that menus aren't accidentally sent to non-supporting browsers.
// This is better than server-side checking because it will also catch browsers which would
// normally support the menus but have javascript disabled.
//
// If supported, call initialize() and then hook whatever image rollover code you need to do
// to the .onactivate and .ondeactivate events for each menu.
//==========================================================================================
	if (TransMenu.isSupported()) {
		TransMenu.initialize();
		
		// hook all the highlight swapping of the main toolbar to menu activation/deactivation
		// instead of simple rollover to get the effect where the button stays hightlit until
		// the menu is closed.
		tmenu1.onactivate = function() { document.getElementById("menu1").style.background = "url(../img/bg-menu-informacio-over.jpg)"; };
		tmenu1.ondeactivate = function() { 
		if(menu == 'menu1')	document.getElementById("menu1").style.background = "url(../img/bg-menu-informacio-selected.jpg)"; 
		else document.getElementById("menu1").style.background = "url(../img/bg-menu-informacio.jpg)";
		};
		
		tmenu2.onactivate = function() { document.getElementById("menu2").style.background = "url(../img/bg-menu-uzletkereso-over.jpg)"; };
		tmenu2.ondeactivate = function() {
		if(menu == 'menu2')	document.getElementById("menu2").style.background = "url(../img/bg-menu-uzletkereso-over.jpg)"; 
		else document.getElementById("menu2").style.background = "url(../img/bg-menu-uzletkereso.jpg)";
		};
		
		tmenu3.onactivate = function() { document.getElementById("menu3").style.background = "url(../img/bg-menu-programok-over.jpg)"; };
		tmenu3.ondeactivate = function() { 
		if(menu == 'menu3')	document.getElementById("menu3").style.background = "url(../img/bg-menu-programok-over.jpg)"; 
		else document.getElementById("menu3").style.background = "url(../img/bg-menu-programok.jpg)";
		};
		
		tmenu4.onactivate = function() { document.getElementById("menu4").style.background = "url(../img/bg-menu-akciok-over.jpg)"; };
		tmenu4.ondeactivate = function() { 
		if(menu == 'menu4')	document.getElementById("menu4").style.background = "url(../img/bg-menu-akciok-over.jpg)"; 
		else document.getElementById("menu4").style.background = "url(../img/bg-menu-akciok.jpg)";		
		};
		
		tmenu5.onactivate = function() { document.getElementById("menu5").style.background = "url(../img/bg-menu-ujdonsagok-over.jpg)"; };
		tmenu5.ondeactivate = function() { 
		if(menu == 'menu5')	document.getElementById("menu5").style.background = "url(../img/bg-menu-ujdonsagok-over.jpg)";
		else document.getElementById("menu5").style.background = "url(../img/bg-menu-ujdonsagok.jpg)"; 		
		};
		
		tmenu6.onactivate = function() { document.getElementById("menu6").style.background = "url(../img/bg-menu-rolunk-over.jpg)"; };
		tmenu6.ondeactivate = function() { 
		if(menu == 'menu6') document.getElementById("menu6").style.background = "url(../img/bg-menu-rolunk-over.jpg)"; 
		else  document.getElementById("menu6").style.background = "url(../img/bg-menu-rolunk.jpg)"; 
		};
		
	}
}

function fMoveGalery(){
	for(k=0; k<aGalery.length; k++){
		obj = fGetObject(aGalery[k][0]);
		sleft = String(obj.style.left);
		pleft = Number(sleft.substr(0, sleft.length-2));
		if(pleft != aGalery[k][1]){
			if(aGalery[k][1]-pleft < 8 && aGalery[k][1]-pleft > -8)
				obj.style.left = String(aGalery[k][1])+"px";
			else
				obj.style.left = String(pleft + (aGalery[k][1]-pleft)/6)+"px";
		}		
	}
	setTimeout("fMoveGalery()", 100);
}

function fGalPlaceMod(objname, kapcs, nyil){
	sleft = String(fGetObject(objname).style.left);
	nleft = Number(sleft.substr(0, sleft.length-2));
	
	swidth = String(fGetObject(objname).style.width);
	nwidth = Number(swidth.substr(0, swidth.length-2));
	
	for(k=0; k<aGalery.length; k++){
		if(aGalery[k][0] == objname){
			currentrow = k;
			break;
		}
	}
	
	aGalery[currentrow][1] += kapcs*113;
	//nyilacska
	if(aGalery[currentrow][1] == -(nwidth-339)){
		fGetObject(nyil+'_1_on').style.display = "none";
		fGetObject(nyil+'_1_off').style.display = "block";
	}else{
		fGetObject(nyil+'_1_on').style.display = "block";
		fGetObject(nyil+'_1_off').style.display = "none";
	}
	
	if(aGalery[currentrow][1]  == 0){
		fGetObject(nyil+'_2_on').style.display = "none";
		fGetObject(nyil+'_2_off').style.display = "block";
	}else{
		fGetObject(nyil+'_2_on').style.display = "block";
		fGetObject(nyil+'_2_off').style.display = "none";
	}
	
}

function fFileBrowse(obj, ext){
	var tmp = new String(obj.value);
	tmp = tmp.substr(tmp.length-4, 4);
	if(tmp.toLowerCase() != ext){
		obj.value = "";
		dialogManager.add(new Dialog('Csak '+ext+' file-t lehet feltölteni!', 'alert'));
	}
}

function fGetObject(obj_name){
	if(W3C)
		return document.getElementById(obj_name);
	else if(NS4)
		return document.layers[obj_name];
	else
		return window.opener.document.all[obj_name];
}

function fIsNum(tmp){
	var szam = new String(tmp);
	var jok = new String("0123456789");
	for(k=0; k<szam.length; k++){
		if(jok.indexOf(szam.charAt(k)) == -1)
			return false;
	}
	return true;
}

function fIsNum2(tmp){
	var szam = new String(tmp);
	var jok = new String("0123456789.");
	var ispoint = false;
	for(k=0; k<szam.length; k++){
		if(szam.charAt(k) == "." && ispoint)
			return false;
		else if(szam.charAt(k) == ".")
			ispoint = true;
			
		if(jok.indexOf(szam.charAt(k)) == -1)
			return false;
	}
	return true;
}

function fIsNum3(obj){
	var szam = new String(obj.value);
	while(szam.indexOf(",") != -1)
		szam = szam.replace(",", ".");
		
	while(szam.indexOf(" ") != -1)
		szam = szam.replace(" ", "");
	obj.value = szam;
	
	var jok = new String("0123456789.");
	var ispoint = false;
	for(k=0; k<szam.length; k++){
		if(szam.charAt(k) == "." && ispoint){
			obj.value = "";
			return false;			
		}else if(szam.charAt(k) == ".")
			ispoint = true;
			
		if(jok.indexOf(szam.charAt(k)) == -1){
			obj.value = "";
			return false;
		}
	}
	return true;
}

function fIsNum4(obj){
	var szam = new String(obj.value);
	while(szam.indexOf(",") != -1)
		szam = szam.replace(",", ".");
		
	while(szam.indexOf(" ") != -1)
		szam = szam.replace(" ", "");
	obj.value = szam;
	
	var jok = new String("0123456789");
	for(k=0; k<szam.length; k++){			
		if(jok.indexOf(szam.charAt(k)) == -1){
			obj.value = 0;
			return false;
		}
	}
	return true;
}

function fIsTime(obj){
	var time = new String(obj.value);	
	while(time.indexOf(",") != -1)
		time = time.replace(",", ":");
		
	while(time.indexOf(".") != -1)
		time = time.replace(".", ":");
		
	while(time.indexOf(" ") != -1)
		time = time.replace(" ", ":");
		
	tmp = time.indexOf(":");
	if(tmp == 1){
		time = "0" + time;
	}	
	
	obj.value = time;
		
	if(time.length != 5){
		alert("Az idő formátuma nem megfelelő, helyesen: 16:30");
		return false;
	}	
	
	
	var hour = new String(time.substr(0,2));
	var minute = new String(time.substr(3,2));

	if(!fIsNum(hour)){
		alert("Az óra csak szám lehet!");
		return false;
	}
	
	if(!fIsNum(minute)){
		alert("A perc csak szám lehet!");
		return false;
	}
	
	if(hour<0 || hour>23){
		alert("Az óra 01-23 lehet!");
		return false;
	}
	
	if(!fIsNum(minute)){
		alert("A perc csak szám lehet");
		return false;
	}
	
	if(minute<0 || minute>59){
		alert("A perc 00-59 lehet!");
		return false;
	}
	
	return true;
}

function fIsDate(obj){
	var date = new String(obj.value);	
	while(date.indexOf(",") != -1)
		date = date.replace(",", "-");
		
	while(date.indexOf(".") != -1)
		date = date.replace(".", "-");
		
	while(date.indexOf(" ") != -1)
		date = date.replace(" ", "-");
		
	obj.value = date;
		
	if(date.length != 10){
		alert("A dátum formátuma nem megfelelő: 1999-09-09");
		return false;
	}	
	
	var year = new String(date.substr(0,4));
	var month = new String(date.substr(5,2));
	var day = new String(date.substr(8,2));

	if(!fIsNum(year)){
		alert("Az év csak szám lehet");
		return false;
	}
	
	if(!fIsNum(month)){
		alert("A hónap csak szám lehet");
		return false;
	}
	
	if(month<1 || month>12){
		alert("A hónap 01-12 lehet!");
		return false;
	}
	
	if(!fIsNum(day)){
		alert("A nap csak szám lehet");
		return false;
	}
	
	if(day<1 || day>31){
		alert("A nap 01-31 lehet!");
		return false;
	}
	
	return true;
}

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

String.prototype.replaceAll = function (str1, str2) {
	str = this;
	pos = str.indexOf(str1);
    while(pos != -1){
		str = str.replace(str1, str2);
		pos = str.indexOf(str1,pos+str2.length-str1.length);
	}
	return str;
}

Number.prototype.valuta = function () {
	var str = new String(this);
	
    str = str.replaceAll(".", ",");
	
	if(str.indexOf(".")>-1)
		tmp = false;
	else
		tmp = true;
	w=0;
	for(q=str.length-1; q>=0; q--){
		if(tmp)
			w++;
		
		if(str.charAt(q) == ",")
			tmp = true;
			
		if(w%3==0 && w>0)
			str = str.substr(0,q)+"&nbsp;"+str.substr(q);
	}
	return str;
}

function fShowDiv(gyid) {
	
	var divnev = "v_"+gyid;
	var anev = "a_"+gyid;

	if(fGetObject(divnev).value == 1){
		fGetObject(divnev).style.display = "none";	
		fGetObject(divnev).value = 0;
	}else{
		fGetObject(divnev).style.display = "block";	
		fGetObject(divnev).value = 1;
	}
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}	
	

