// ÷ 2010-01-25 11:05:36

///////////////////////////////////////////////////////////////////////////////////
//a console függvényt tünteti el olyan környezetben ahol nem működik
if (!window.console || !console.firebug) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}

//párhuzamos ajax futások száma
if (!ajaxRunCount) {
	var ajaxRunCount = 0;
}
///////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////
//WP függvények:
//

function pause(seconde) {
	  milliseconde = seconde * 1000;
	  var now = new Date();
      var exitTime = now.getTime() + milliseconde;
      while(true) {
		  now = new Date();
		  if (now.getTime() > exitTime) return;
      }
}

function selectText(id) {
    document.getElementById(id).focus();
    document.getElementById(id).select();
}

function addToOnload(object,func) {  
	var oldonload = object.onload;
	if (typeof object.onload != 'function') {
		object.onload = func;
	} else {
		object.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}


/*	///////////////////////////////////////////	*/
/*	Utility: add function to an eventListener	*/
/*	///////////////////////////////////////////	*/
/// eventType examples, keyboard: "keydown", "keypress", "keyup", mouse: "click", "mousedown", "mouseup", "mouseover", "mouseout", "mousemove"
/// capturingOrBubblingPhase: true(capturing), false (bubbling), IE always use bubbling! So..., see more: http://www.quirksmode.org/js/events_advanced.html (Javascript - Advanced event registration models)
/// using example: wpAddEvent(document, "keydown", keyEventChangesMade, false);
function wpAddEvent(object, eventType, functionToCall, capturingOrBubblingPhase) {
	if (object.addEventListener) { object.addEventListener(eventType, functionToCall, capturingOrBubblingPhase); return true; }
	else if (object.attachEvent) { return object.attachEvent("on"+eventType, functionToCall); }
	else { object["on"+eventType] = eventType; } //OLD version: return false;
}
function keyEvent_changesMade(e) {
	if (!e) e = event;	///	IE nem adja át az eseményt...
	try{
		setChangesMadeDIV();
	}catch(er){
		console.debug(er);
	}
	//alert(e + '\n keyCode=' + e.keyCode + '\n which=' + keyval(e.which) + '\n charCode=' + keyval(e.charCode));
	/*	alert('          keyIdentifier='+ e.keyIdentifier
		  + ' keyLocation='+e.keyLocation);
	alert('          shiftKey='+e.shiftKey
	      + ' ctrlKey='+e.ctrlKey
	      + ' altKey='+e.altKey
	      + ' metaKey='+e.metaKey);*/
}
function mouseEvent_changesMade(e) {
	if (!e) e = event;	///	IE nem adja át az eseményt...
	try{
		setChangesMadeDIV();
	}catch(er){
		console.debug(er);
	}
}
function setChangesMadeDIV() {
	var trgt = document.getElementById('hasChangesAfterSaved');
//	trgt.innerHTML = "*";
	trgt.style.backgroundImage = "url("+httpBase+"images/header/hasChanges.png)";
	trgt.style.display = "block";
}

function keyval(n) {
	if (n == null) return 'undefined';
	var s = "" + n;
	if (n >= 32 && n < 127) s += ' (' + String.fromCharCode(n) + ')';
	while (s.length < 9) s += ' ';
	return s;
}

/*	///////////////////////////////////////	*/

function validEmail(email, nincsUzenet, hibasUzenet) {
	if (email == "" || email == null) {
		if (!nincsUzenet ) nincsUzenet='Az email cím nincs megadva!';
		alert(nincsUzenet);
		return false;
	} else {
		var emailReg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
		var emailReg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,6}|[0-9]{1,3})(\]?)$/; // valid
		if (!(!emailReg1.test(email) && emailReg2.test(email))) { // if syntax is valid
			if (!hibasUzenet ) hibasUzenet='Az email cím formailag hibás!';
			alert(hibasUzenet);
			return false;
		}
		return true;
	}
}

function validDatum(strValue) {
		// nullát nem ellenőrzi
	if (strValue == "0000-00-00" || strValue == "" ) return true;

		// év ellenőrzése
	var intYear = strValue.substring(0,4);
	if (!isNumeric(intYear) || strValue.length == 0) {
		alert("Hibás év, kérjük az 'éééé-hh-nn' dátum formát használja ");
		return false;
	}

		// hónap ellenőrzése
	var intMonth = strValue.substring(5,7);
	if (!isNumeric(intMonth) || parseInt(intMonth, 10 ) > 12) {
		alert("Hibás hónap, kérjük az 'éééé-hh-nn' dátum formát használja ");
		return false;
	}

		// nap ellenőrzése
	var intDay = strValue.substring(8,10);
	if (!isNumeric(intDay) || parseInt(intDay, 10 ) > 31) {
		alert("Hibás nap, kérjük az 'éééé-hh-nn' dátum formát használja ");
		return false;
	}

   		//create a lookup for months not equal to Feb.
    var honapNap = {'01' : 31,
					'03' : 31,
                    '04' : 30,
					'05' : 31,
                    '06' : 30,
					'07' : 31,
                    '08' : 31,
					'09' : 30,
                    '10' : 31,
					'11' : 30,
					'12' : 31};

	var intNap = parseInt(intDay,10);
	var intHo = parseInt(intMonth,10);
	var intEv = parseInt(intYear,10);

    	//check if month value and day value agree
    if (honapNap[intMonth] != null) {
      	if (intNap <= honapNap[intMonth] && intNap != 0) {
	  		return true; //found in lookup table, good date
		}
    }

    if (intHo == 2) {
       if (intNap > 0 && intNap < 29) {
           return true;
	   } else if (intNap == 29) {
	   			// year div by 4 and ((not div by 100) or div by 400) ->ok
			if ((intEv % 4 == 0) && (intEv % 100 != 0) ||
				 (intEv % 400 == 0)) {
				 return true;
			}
       }
    }
	alert("A dátum nem helyes" + strValue);
	return false;
}

function checkTimeKeyPressed(e, id) {
    if (e.keyCode) keycode=e.keyCode;
    else keycode=e.which;
    ch=String.fromCharCode(keycode);

    var textfield = document.getElementById(id);
    var txt = textfield.value;

    if (txt == '00:00' ) txt = '';
    if (txt.length == 2 ) txt = txt + ':';
    if (txt.length > 5 ) txt = txt.substr(0, 5);

    var doIt = true;
    while (txt.length > 0 && doIt) {
        doIt = false;
        switch(txt.length) {
            case 1:
                if (!txt.match(/^[0-2]$/) ) doIt = true;
                break;
            case 2:
                if (!txt.match(/^[0-2][0-9]$/) ) doIt = true;
                if (txt > '23' ) doIt = true;
                break;
            case 3:
                if (!txt.match(/^[0-2][0-9]:$/) ) doIt = true;
                if (txt > '23:' ) doIt = true;
                break;
            case 4:
                if (!txt.match(/^[0-2][0-9]:[0-5]$/) ) doIt = true;
                if (txt > '23:5' ) doIt = true;
                break;
            case 5:
                if (!txt.match(/^[0-2][0-9]:[0-5][0-9]$/) ) doIt = true;
                if (txt > '23:59' ) doIt = true;
                break;
        }
        if (doIt ) txt = txt.substr(0, txt.length-1);
    }

        // ha közben törölni kellett rossz adat miatt
    if (txt.length == 2 ) txt = txt + ':';
    textfield.value = txt;
}

function validTime(strValue) {
	var hibas = false;
		// számok átkonvertálása
	if (isNumeric(strValue )) {
		if (strValue.length == 1 ) strValue = "0" + strValue + ":00";
		if (strValue.length == 2 && strValue < 25 ) strValue = strValue + ":00";
		if (strValue.length == 3 ) strValue = "0" + strValue.substring(0,1) + ':' + strValue.substring(1,3);
		if (strValue.length == 4 ) strValue = strValue.substring(0,2) + ':' + strValue.substring(2,4);
	}
		// érvénytelen hosszú stringeket visszadobja
	if (strValue.length > 5 || strValue.length < 3) {
		hibas = true;
	} else {
			// óra ellenőrzése
		var intHour = strValue.substring(0,2);
		if (!isNumeric(intHour) || parseInt(intHour, 10 ) > 24) {
			hibas = true;
		}
			// perc ellenőrzése
		var intMinute = strValue.substring(3,5);
		if (!isNumeric(intMinute) || parseInt(intMinute, 10 ) > 59) {
			hibas = true;
		}
	}
	if (hibas) {
		alert("Hibás idő, kérjük az 'óó:pp' formát használja ");
		strValue = '00:00';
	}
	return strValue;
}

var numbers="0123456789";
function isNumeric(x) {
    // is x a String or a character?
    if (x.length>1) {
      // remove negative sign
      x=Math.abs(x)+"";
      for(j=0;j<x.length;j++) {
        // call isNumeric recursively for each character
        number=isNumeric(x.substring(j,j+1));
        if (!number) return number;
      }
      return number;
    }
    else {
      // if x is number return true
      if (numbers.indexOf(x)>=0) return true;
      return false;
    }
}


function validInteger(strValue) {
	if (isNumeric(strValue ) ) return strValue;
	alert("Nem egész szám: " + strValue);
	return 0;
}

function validDouble(strValue) {
	strValue = replaceChars(",", ".", strValue );
	var numberParts = strValue.split(".", 1 );
	if (isNumeric(numberParts[0] ) && numberParts[1] == null ) return strValue;
	if (isNumeric(numberParts[0] ) && isNumeric(numberParts[1] ) ) return strValue;
	alert("Nem szám: " + strValue);
	return 0;
}

///////////////////////////////////
//keigészített
//indexOf pozició növelés, nem fagy be
//ha hozzáfűzésre van használva
function replaceChars(replaceThis, withThis, source) {
	temp = "" + source;
	var pos = 0;	
	while (temp.indexOf(replaceThis, pos  ) >-1) {
		pos= temp.indexOf(replaceThis );
		temp = "" + (temp.substring(0, pos) + withThis + temp.substring((pos + replaceThis.length), temp.length) );
		pos = pos+1;
	}
	return temp;
}

/*  ellenőrzi az oldal választás joghoz kötött submitolhatóságát */
function checkChangePage(oldalRight, userRight, requiredPageName) {
	if (oldalRight == 0 || userRight/oldalRight == Math.round(userRight/oldalRight )) {
		document.page.pageChooser.value = requiredPageName;
		//alert('New page requested: '+document.page.pageChooser.value);
		console.error('New page requested: '+document.page.pageChooser.value);
		document.page.submit();
	}
}

/* sbmitol egy control gomb formot */
function controlSubmitButton(submitValue, form, button) {
	button.value = submitValue;
	form.submit();
}

function writeIntoElement(id, text) {
	if (document.getElementById != null) {
		x = document.getElementById(id);
		if (x != null) {
			x.innerHTML = '';
			x.innerHTML = text;
		}
	} else if (document.all) {
		x = document.all[id];
		if (x != null) {
			x.innerHTML = text;
		}
	} else if (document.layers) {
		x = document.layers[id];
		if (x != null) {
			text2 = '<P CLASS="testclass">' + text + '</P>';
			x.document.open();
			x.document.write(text2);
			x.document.close();
		}
	} else {
		console.debug('nem sikerült a tartalmat beilleszteni a(z) '+id+' elembe');
		return false;
    }
	return true;
}

function printText(elem) {
    popup = window.open('','popup','toolbar=no,menubar=no,width=200,height=150');
    popup.document.open();
    popup.document.write("<html><head></head><body onload='print()'>");
    popup.document.write(elem);
    popup.document.write("</body></html>");
    popup.document.close();
} 

function getElementPosition(obj) {
    var topValue= 0,leftValue= 0;
    while(obj) {
        leftValue+= obj.offsetLeft;
        topValue+= obj.offsetTop;
        obj= obj.offsetParent;
    }
    return [leftValue, topValue];
}

function createDiv(id, html, width, height, left, top, background, border, zIndex) {
	var newdiv = document.createElement('div');

	newdiv.setAttribute('id', id);
	newdiv.style.position = 'absolute';
	newdiv.style.width = width;
	newdiv.style.height = height;
	newdiv.style.left = left;
	newdiv.style.top = top;
	newdiv.style.background = background;
	newdiv.style.border = border;
	changeOpacity(newdiv, 100);
	newdiv.style.zIndex = (zIndex) ? zIndex : 1;
	newdiv.innerHTML = (html) ? html : "nothing";
	
	document.body.appendChild(newdiv);
	return newdiv;	
}

function removeElement(elementID) {
	var el = document.getElementById(elementID);
	el.parentNode.removeChild(el);
}

function changeOpacity(obj, opacity) {
    if (typeof obj.style.opacity == "string") {
        obj.style.opacity = opacity/100;
    } else {
        obj.filters.alpha.opacity = opacity;
    }
}

/*
 *  animált mozgással és átméretezéssel átrak egy element-et
 *  obj: az element
 *  var animPropsDiv = {
    left: {start: 5, end: 100},
    top: {start: 55, end: 20},
    height: {start: 100, end: 400},
    width: {start: 300, end: 800}
};
    anim: true, false - kell-e animálni
 */

function moveElement(obj, animProps, anim) {    
    if (!anim) {
            // Az eredeti funkció futtatása
        obj.style.top = animProps.left.end + "px";
        obj.style.left = animProps.top.end + "px";
    } else {
        //Az animáció futtatása
        var moveArgs = {
            node: obj,
            easing: dojo.fx.easing.linear,
            duration: 60,
            properties:{}
        };

        //Az egyes mozgások beállítása
        if (animProps.left!=null) {
            moveArgs.properties.left = {start: animProps.left.start, end: animProps.left.end, unit: "px"};
        }

        if (animProps.top!=null) {
            moveArgs.properties.top = {start: animProps.top.start, end: animProps.top.end, unit: "px"};
        }

        if (animProps.width!=null) {
            moveArgs.properties.width = {start: animProps.width.start, end: animProps.width.end, unit: "px"};
        }

        if (animProps.height!=null) {
            moveArgs.properties.height = {start: animProps.height.start, end: animProps.height.end, unit: "px"};
        }

        dojo.fx.chain([dojo.animateProperty(moveArgs)]).play();
    }
}

function resizeElement(obj, width, height) {
    obj.style.width = width + "px";
    obj.style.height = height + "px";
}

function setInProgressAndJumpToPage(oldal, aloldal, inProgressIdName, inProgressID, extraParameters) {
	var url = oldal + '/control.php?aloldal=' + aloldal + '&' + inProgressIdName + '=' + inProgressID;
	if (extraParameters.length > 0 ) url = url + '&' + extraParameters;

	window.location = url;
}

function openWindow(windowWidth, windowHeight, url, windowName, passedParameters) {
	var OpenSubX = (screen.width/2)-(windowWidth/2);
	var OpenSubY = (screen.height/2)-(windowHeight/2);
	var pos = ', left='+OpenSubX+', top='+OpenSubY;
	var features = 'toolbar=no, menubar=yes, resizable=no, scrollbars=yes, status=no, location=no, width=' + windowWidth + ', height=' + windowHeight + pos;

	window.open(url + passedParameters, windowName, features);
}

function printWindow(nyomtatGombNeve) {
	document.getElementById(nyomtatGombNeve ).style.visibility = 'hidden';

	window.print();
	window.onAfterPrint();
}

function showDolgozom(left, top) {
	if (document.getElementById('dolgozomPict')) {
		sizes = getImgSize(document.getElementById('dolgozomPict').src);
		document.getElementById('dolgozom_div').style.visibility = 'visible';
		document.getElementById('dolgozom_div').style.left =  Math.round(iWidth-sizes[0]-12)/2 + 'px';
		document.getElementById('dolgozom_div').style.top =  Math.round(iHeight-sizes[1]-12)/2 + 'px';
	} else {
		document.getElementById('dolgozom_div').style.visibility = 'visible';
		document.getElementById('dolgozom_div').style.left = left + 'px';
		document.getElementById('dolgozom_div').style.top = top + 'px';
	}
}

function hideDolgozom() {
	document.getElementById('dolgozom_div').style.visibility = 'hidden';
}

function setSelectedOption(select, selectedValue, sceId) {
    for (var i = 0; i < select.options.length; i++) {
        if (select.options[i].value == selectedValue) {
            select.options[i].selected = true;
			//ha tartozik hozzá sceId
			if (sceId > 0) {
				try{
					eval('setComboFakeTxt_'+sceId+'();');
				}catch(e){
					eval("setComboFakeTxt('"+select.id+"', 'comboVisiLbl_"+sceId+"'); ");
				}
			}
            //break;
			return true;
        }
    }
	select.options[0].selected = true;
	if (sceId > 0) {
		try{
			eval('setComboFakeTxt_'+sceId+'();');
		}catch(e){
			eval("setComboFakeTxt('"+select.id+"', 'comboVisiLbl_"+sceId+"'); ");
		}
	}
	return false;
}

function getAjaxObject() {
    var xmlhttp;
        // browser based object setting
    if (window.XMLHttpRequest) {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    } else if (window.ActiveXObject) {
      // code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    } else {
      alert("Your browser does not support XMLHTTP!");
    }

    return xmlhttp;
}

function setHtml(div, content, scriptID) { 
    var search = content; 
    var script; 
    
	if (scriptID == null) {
		scriptID = "ajaxViewSetHtmlJs";
	}
	
	if (div != "wpPopupSpecial") {
		document.getElementById(div).innerHTML=content;
	}

    //összes headScript megszerzése, hogy csak 1x legyenek be includeolva a js-ek
    var headScripts = document.getElementsByTagName('script');
	 
	/*
	//régi tag-ek leszedése headscriptből
	for (wpIndexRemoveJava = 0; wpIndexRemoveJava < headScripts.length; wpIndexRemoveJava++) {
		if (headScripts.item(wpIndexRemoveJava).id == scriptID) {
			headScripts.item(wpIndexRemoveJava).remove();
		}
	}
	*/

	if ( search != 'null' ){
		while(script = search.match(/(<script[^>]+javascript[^>]+>\s*(<!--)?)/i)) { 
		  search = search.substr(search.indexOf(RegExp.$1) + RegExp.$1.length); 
		   
		  if (!(endscript = search.match(/((-->)?\s*<\/script>)/))) break; 
		   
		  block = search.substr(0, search.indexOf(RegExp.$1)); 
		  search = search.substring(block.length + RegExp.$1.length); 

		  eval(block);

		  var setHtmlJavaInclude = true;

		  for (wpIndexSetHtml = 0; wpIndexSetHtml < headScripts.length; wpIndexSetHtml++) {
			  if (headScripts.item(wpIndexSetHtml ).text == block) {
				  setHtmlJavaInclude = false;
			  }
		  }

		  if (setHtmlJavaInclude == true) {
			  var oScript = document.createElement('script');
			  oScript.text = block;
			  oScript.id = scriptID;
			  oScript.title = div;
			  document.getElementsByTagName("head").item(0).appendChild(oScript);
		  }
		} 
	}
}

function addHtmlJsFunction(functionContent, idName) {
	console.debug(functionContent);	
}

function ajaxControl(httpControl, variablesAll, onLoad) {
	ajaxRunCount += 1;
	var loading = document.getElementById("dolgozom_div");
	if (loading != null) {
		loading.style.visibility = "visible";			
		loading.style.left = (iWidth-132)/2 + "px";
		loading.style.top = (iHeight-168)/2 + "px";
	}
	// tömb elküldése és a válasz feldolgozás elindítása
	jQuery.noConflict();
	var req = jQuery.ajax({
		url : httpControl + "?ajaxControl=1",
		data : JSON.stringify(variablesAll),
		dataType : "text",
		type: "POST",

		timeout : 15000,

		success : function(response, ioArgs) {
				ajaxRunCount -= 1;
                try {
                  ajaxView(response );
                      if (document.getElementById("dolgozom_div") && ajaxRunCount === 0) {
                              var loading = document.getElementById("dolgozom_div");
                              if (loading != null) {
                                      if (loading.style.visibility == "visible") {
                                            loading.style.visibility = "hidden";
                                      }
                              }
                      }
                } catch (e) {
                  //alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
                      console.debug("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message);
                      var loading = document.getElementById("dolgozom_div");
                      if (loading != null && ajaxRunCount === 0) {
                              if (loading.style.visibility == "visible") {
                                    loading.style.visibility = "hidden";
                              }
                      }
                }
		},

		error : function(response, textStatus, errorThrown) {
				ajaxRunCount -= 1;
				  var loading = document.getElementById("dolgozom_div");
				  if (loading != null && ajaxRunCount === 0) {
						  if (loading.style.visibility == "visible") {
								loading.style.visibility = "hidden";
						  }
				  }
                console.debug("HTTP status code: ", textStatus);
				console.error("Error: ", errorThrown);
				alert('Valami hiba történt (próbáld újra):'+textStatus);
				return response; 
		}
	});
	return req;
}

function ajaxView(response) {
    //console.error(response);
    var responseArray = JSON.parse(response );
    //console.error(responseArray);

    for (wpIndex=0; wpIndex<responseArray.length; wpIndex++) {
        var sceID = responseArray[wpIndex]['sceID'];

        switch(responseArray[wpIndex]['type']) {
			case 'radio_buttons':
					/*
					*/
					if (responseArray[wpIndex]['checked'] != null) {
						var radioButton = document.getElementById('radioButton_'+sceID+'_'+responseArray[wpIndex]['checked']);
						if (radioButton != null) {
							radioButton.checked = true;
						} else {
							var radioButtonForm = document.forms[responseArray[wpIndex]['form']].elements['radioButton'];
							radioButtonForm[0].checked = true;
							radioButtonForm[0].checked = false;
						}
					} else {
						var radioButtonForm = document.forms[responseArray[wpIndex]['form']].elements['radioButton'];
						if (radioButtonForm != undefined) {
							if (radioButtonForm.length == undefined) {
								if (radioButtonForm.checked) {
									radioButtonForm.checked = false;
								} else {
									console.debug(sceID+' radioButton formban nincs elem');
								}
							} else {
								for (var radioButtonIndex = 0; radioButtonIndex < radioButtonForm.length; radioButtonIndex++) {
									if (radioButtonForm[radioButtonIndex].checked) {
										radioButtonForm[radioButtonIndex].checked = false;
										break;
									}
								}
							}
						}
					}
					break;
            case 'controlled_empty_div':
					try {
						tinyMCE.activeEditor.remove();
					} catch(errorTinyMCERemove) {
						console.debug("no tinyMCE");
					}
                    setHtml(responseArray[wpIndex]['sceDiv'], responseArray[wpIndex]['tartalom']);
                    if (responseArray[wpIndex]['mce'].length > 0) {
                            //jsInclude(httpBase + '/', 'tinymce/jscripts/tiny_mce/tiny_mce.js', true);
                            //jsInclude(httpBase + '/', 'tinymce/tinyMCE_init.js', true);
                            //tinyMCE.execCommand('mceAddControl', false, 'div_'+responseArray[wpIndex]['mce']+'_txa');
                            if (tinyMCE == undefined) {
                                location.reload();
                            } else {
                                try {
                                    tinyMCE.addMCEControl(document.getElementById('txa_' + responseArray[wpIndex]['mce']));
                                } catch (error) {
									try {
										tinyMCE.execCommand("mceAddControl", true, 'txa_' + responseArray[wpIndex]['mce']);
									} catch (errorNew) {
										location.reload();
										console.debug(print_r(error));
										console.debug(print_r(errorNew));
									}
                                }
                            }
                            //location.reload();
                    }
                    break;
            case 'checkboxes_dynamic' :
                    //dinamikus checkbox-ok
                    if (document.getElementById(responseArray[wpIndex]['sceDiv'] )) {
                            var wpCheckboxesDynamic = document.getElementById(responseArray[wpIndex]['sceDiv'] );
                            wpCheckboxesDynamic.innerHTML = responseArray[wpIndex]['tartalom'];
                    } else {
                            console.debug('nincs meg a dynamic_checkbox div');
                    }
                    break;
            case 'calendar_textfield' :
                    //textfield
                    if (document.getElementById("calendar_textfield_" + responseArray[wpIndex]['formName'] + "_form_txt" )) {
                            var wpCalendar = document.getElementById("calendar_textfield_" + responseArray[wpIndex]['formName'] + "_form_txt");
                            wpCalendar.value = responseArray[wpIndex]['tartalom'];
                    }
                    //felirat
                    if (document.getElementById("calendar_" + responseArray[wpIndex]['sceID'] + "_felirat")) {
                            var wpCalendarFelirat = document.getElementById("calendar_" + responseArray[wpIndex]['sceID'] + "_felirat");
                            wpCalendarFelirat.innerHTML = responseArray[wpIndex]['felirat'];
                    }
                    break;
            case 'connected_named_combo' :
                    if (document.getElementById(responseArray[wpIndex]['formName'])) {
                            var wpCombo = document.getElementById(responseArray[wpIndex]['formName']);
                            wpCombo.innerHTML = responseArray[wpIndex]['tartalom'];
                    }
                    break;
            case 'mce_div':
                    //getContent nélkül nem updateli az mce-t
                    try {
						tinyMCE.getContent('mce_editor_txa_'+sceID);
						tinyMCE.execCommand('mceFocus', false, 'mce_editor_txa_'+sceID);
						tinyMCE.setContent(responseArray[wpIndex]["tartalom"]);
						tinyMCE.getContent('mce_editor_txa_'+sceID);
					} catch (tinyMceErrorCatched) {
						tinyMCE.activeEditor.getContent();
						tinyMCE.execCommand('mceFocus', false, 'txa_'+sceID);
						tinyMCE.activeEditor.setContent(responseArray[wpIndex]["tartalom"]);
						tinyMCE.activeEditor.getContent();
					}
                    break;
            case 'table':
                    var wpTable = document.getElementById('tableDiv_' + sceID);
                    if (wpTable != null) {
                            wpTable.innerHTML = responseArray[wpIndex]['tartalom'];
                    }
                    break;
            case 'tree_table':
                    if (jQuery.tree.focused(responseArray[wpIndex]['sceDiv']).refresh(jQuery("#" + responseArray[wpIndex]['nodeID'])) == false) {
						jQuery.tree.focused(responseArray[wpIndex]['sceDiv']).refresh();
                    }
            case 'button':
					var working = writeIntoElement('bttnLbl' + sceID, responseArray[wpIndex]['felirat'] ); //'wp_btn'+ volt a régi
                    if (!working) {
						writeIntoElement('btn_' + responseArray[wpIndex]['sceDiv'], responseArray[wpIndex]['felirat'] );
					}
                    break;
			case 'popup_button' :
					if (responseArray[wpIndex]['function'] != null) {
						//kódból régi függvény törlése
						try {
						document.getElementById('popupFgv_' + sceID).remove();
						} catch(popupFgvRemoveError) {
							console.debug("Hiba neve: " + popupFgvRemoveError.name + " message: " + popupFgvRemoveError.message);
						}
						//?????
						//addHtmlJsFunction(responseArray[wpIndex]['function'], 'popupFgv_' + sceID);
						//setHtml("wpPopupSpecial", responseArray[wpIndex]['function'], 'popupFgv_' + sceID);
					}
					if (responseArray[wpIndex]['localController'] == 'true') {
						eval(responseArray[wpIndex]['functionName']);
					}
					break;
            case 'label_inprogress' :
                    writeIntoElement('felirat_' + sceID, responseArray[wpIndex]['felirat'] + " " + responseArray[wpIndex]['tartalom'] );
                    break;
            case 'label':
					writeIntoElement('felirat_' + sceID, responseArray[wpIndex]['felirat'] );
					break;
            case 'named_textfield':
					writeIntoElement('felirat_' + sceID, responseArray[wpIndex]['felirat'] );
					document.getElementById('textfield_' + sceID ).value = responseArray[wpIndex]['tartalom'];
					break;
            case 'named_txa':
					document.getElementById('txa_' + sceID ).value = responseArray[wpIndex]['tartalom'];
					break;
            case 'named_checkbox':
					writeIntoElement('felirat_' + sceID, responseArray[wpIndex]['felirat'] );
					if (responseArray[wpIndex]['tartalom'] == '') {
						document.getElementById('checkBox_check_' + sceID ).checked = false;
					} else {
						document.getElementById('checkBox_check_' + sceID ).checked = true;
					}
					if (!refreshDsgnChckBoxView(sceID, "http://www.woodpecker.hu/WPGenerator/css/WPGenerator/named_checkbox/")){
						refreshDsgnChckBoxView_v2(sceID);
					}
					break;
            case 'named_combo':
					//régi, dizájn elötti
					if (document.getElementById('combo_' + responseArray[wpIndex]['formName'] )) {
						writeIntoElement('combo_' + responseArray[wpIndex]['formName'], responseArray[wpIndex]['tartalom'] );
					} else {
						//új, dizánjos
						if (document.getElementById(responseArray[wpIndex]['formName'] + '_select')) {
							var formEnd = "_select";
						}else{
							var formEnd = "_sel";
						}
						
						writeIntoElement(responseArray[wpIndex]['formName'] + formEnd, responseArray[wpIndex]['tartalom'] );
						//új, ez kell a kiválasztásnál
						try {
							eval('setComboFakeTxt_'+ sceID + '();');
						} catch (e) {
							console.debug('named_combo eval nem fut le ' + 'setComboFakeTxt_'+ sceID + '();');
						}
						try {
							var comboForm = responseArray[wpIndex]['formName'] + formEnd;
							var comboDiv = 'comboVisiLbl_'+sceID;
							eval("setComboFakeTxt('"+comboForm+"', '"+comboDiv+"'); ");
						} catch(f) {
							console.debug('named_combo eval nem fut le' + "setComboFakeTxt('"+comboForm+"', '"+comboDiv+"'); ");
						}					
					}
					break;
            case 'new_button_list':
					writeIntoElement('list_' + responseArray[wpIndex]['sce_wpadatName'] + 'All_sel', responseArray[wpIndex]['tartalom'] );
					break;
            case 'combo_local_controller':
					//régi, dizájn elötti
					//writeIntoElement('select_' + responseArray[wpIndex]['formName'], responseArray[wpIndex]['tartalom'] );
					//új, dizánjos
					if (document.getElementById(responseArray[wpIndex]['formName'] + '_select')) {
						var formEnd = "_select";
					}else{
						var formEnd = "_sel";
					}
					writeIntoElement(responseArray[wpIndex]['formName'] + formEnd, responseArray[wpIndex]['tartalom'] );
					//új, ez kell a kiválasztásnál
					try {
						eval('setComboFakeTxt_'+ sceID + '();');
					} catch(e) {
						console.debug('named_combo eval nem fut le ' + 'setComboFakeTxt_'+ sceID + '();');
					}
					try {
						var comboForm = responseArray[wpIndex]['formName'] + formEnd;
						var comboDiv = 'comboVisiLbl_'+sceID;
						eval("setComboFakeTxt('"+comboForm+"', '"+comboDiv+"'); ");					
					} catch(f) {
						console.debug('named_combo eval nem fut le' + "setComboFakeTxt('"+comboForm+"', '"+comboDiv+"'); ");
					}
					break;
			case 'pm_file_upload_list':
					//innerHTML kicserélése
					jQuery('#'+responseArray[wpIndex]['sceDiv']).children('table').replaceWith(responseArray[wpIndex]['tartalom']);
					break;
            case 'manualJsAfterAjax':
					if (responseArray[wpIndex]['tartalom']) {
						eval(responseArray[wpIndex]['tartalom']);
					}
					break;
            case 'messageForViewAlert':
					alert(responseArray[wpIndex]['tartalom'] );
        }


            // SCE-k elrejtése és megjelenítése
        if (document.getElementById(responseArray[wpIndex]['sceDiv'] )) {
            document.getElementById(responseArray[wpIndex]['sceDiv'] ).style.visibility = responseArray[wpIndex]['visibility'];
        }

        if (responseArray['manualJsAfterAjax'] != null) {
            eval(responseArray['manualJsAfterAjax']);
        }

		/*
        if (responseArray[wpIndex]['sceDiv']) {
            document.getElementById(responseArray[wpIndex]['sceDiv'] ).style.visibility = responseArray[wpIndex]['visibility'];
        }
		*/
    }
}

function refreshAfter_connection_popup() {
    return true;
}

var index;
var win;
var betoltes_count;

function connection_popup(httpConnectionPopup) {

	jsInclude(httpConnectionPopup,  '/js/prototype.js', true);
	jsInclude(httpConnectionPopup,  '/js/effects.js', true);
	jsInclude(httpConnectionPopup, '/js/window.js', true);
	cssInclude(httpConnectionPopup, '/css/popup/default.css', true);

    win = new Window(
    "connection_popup_" + index, {
      width: 400,
      height: 400,
      zIndex:150,
      opacity:1,
      resizable: false,
      closable: true,
      showEffect: Element.show,
      hideEffect: Element.hide,
      title: "Connection ablak",
      url: httpConnectionPopup + '/graphic_pages/wp_connection_popup/control.php'
    }
  );
    win.setCloseCallback(refreshAfter_connection_popup );
    win.showCenter(true);
    index++;
}

/*DOJO alapú dnd függvények**************************/

function makeDndSource(nodeID, param) {
	return dndSource = new dojo.dnd.Source(nodeID, param );
}

function getNode(param, where) {
	return dojo.query(param, where );
}

function getNodeById(id) {
	return dojo.byId(id );
}

function getNodeAttr(node, attr) {
	try {
		return dojo.attr(node, attr );
	} catch(e) {
		return console.debug('can\'t getNodeAttr');
	}
}

function jsonEncode(adat) {
	return dojo.toJson(adat );
}

///////////////////////////////
//ajaxos hívás post-al küldhető paraméterrelm és string-el visszatérésnél
function runAjax(phpURL, onLoad, onError) {
	//dolgozom kép bekapcsolása (dolgozom_div)
	ajaxRunCount += 1;
	var loading = document.getElementById("dolgozom_div");
	if (loading != null) {
		var time = setTimeout(function() {loading.style.visibility = "visible";},1000);
		loading.style.left = "450px";
		loading.style.top = "250px";
	}
	
	if ((typeof onError) == 'undefined') {
		dojo.xhrGet({
			// Ezt a php file-t hívja meg.
			url: phpURL,
			handleAs: "text",
			timeout: 10000, // Ennyi ideig vár a válaszra
			// a LOAD függvény lesz meghívva sikeres válasz esetén.
			//load: onLoad,
			load: function(respond, ioArgs) {
					ajaxRunCount -= 1;
					if (onLoad != null) {
						onLoad(respond, ioArgs);
					}
					clearTimeout(time);
					if (loading != null && ajaxRunCount === 0) {
						loading.style.visibility = "hidden";
					}
					return respond;
				  },

			// Hiba esetén az ERROR függvény lesz meghívva.
			error: function(response, ioArgs) {
				ajaxRunCount -= 1;
			  console.error("HTTP status code: ", ioArgs.xhr.status);
			  console.error("Error text: ", response);
			  return response;
			  }
		});
	} else {
		dojo.xhrGet({
			// Ezt a php file-t hívja meg.
			url: phpURL,
			handleAs: "text",
			timeout: 10000, // Ennyi ideig vár a válaszra
			// a LOAD függvény lesz meghívva sikeres válasz esetén.
			//load: onLoad,
			load: function(respond, ioArgs) {
					ajaxRunCount -= 1;
					if (onLoad != null) { 
						onLoad(respond, ioArgs);
					}
					clearTimeout(time);
					if (loading != null && ajaxRunCount === 0) {
						loading.style.visibility = "hidden";
					}
					return respond;
				  },

			// Hiba esetén az ERROR függvény lesz meghívva.
			error: onError
		});
	}
}


///////////////////////////////////////////////
//ajaxos hívás post-ban json kódolt adattal!!
function runAjaxJsonToJson(phpURL, post, onLoad, onError, showDolgozom) {
	//dolgozom kép bekapcsolása (dolgozom_div)
	ajaxRunCount += 1;
	if ((typeof showDolgozom ) == "undefined"  || showDolgozom == null) {
		showDolgozom = true;
	}
	
	if (showDolgozom) {
		var loading = document.getElementById("dolgozom_div");
		if (loading != null) {
			var time = setTimeout(function() {loading.style.visibility = "visible";},1000);
			loading.style.left = "450px";
			loading.style.top = "250px";
		}
	}
	
	if ((typeof onError) == 'undefined') {
		jQuery.noConflict();
		jQuery.ajax({
			url : phpURL,
			data : JSON.stringify(post),
			dataType : "text",
			type: "POST",

			timeout : 15000,

			success : function(respond, ioArgs) {
					ajaxRunCount -= 1;
					try{
						if (onLoad != null) {
							onLoad(respond, ioArgs);
						}
						if (ajaxRunCount === 0) {
							clearTimeout(time);
							hideDolgozom()
						}
						return respond;
					} catch (e) {
						  //alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
							  console.debug("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message);
							  var loading = document.getElementById("dolgozom_div");
							  if (loading != null && ajaxRunCount === 0) {
								hideDolgozom()
							  }
					}
				},

			error : function(response, ioArgs) {
						ajaxRunCount -= 1;
						console.error("HTTP status code: ", ioArgs.xhr.status);
						console.error("Error text: ", response);
						if (ajaxRunCount === 0) {
							clearTimeout(time);
							hideDolgozom()
						}
						return response;
					}
		});	
	} else {
		jQuery.noConflict();
		jQuery.ajax({
			url : phpURL,
			data : JSON.stringify(post),
			dataType : "text",
			type: "POST",

			timeout : 15000,

			success : function(respond, ioArgs) {
					ajaxRunCount -= 1;
					try{
						if (onLoad != null) {
							onLoad(respond, ioArgs);
						}
						if (ajaxRunCount === 0) {
							clearTimeout(time);
							hideDolgozom()
						}
						return respond;
					} catch (e) {
					  //alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
						  console.debug("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message);
						  var loading = document.getElementById("dolgozom_div");
						  if (loading != null && ajaxRunCount === 0) {
							hideDolgozom()						  
							}
					}
				},

			error : function( respond, ioArgs) {
						ajaxRunCount -= 1;
						if (ajaxRunCount === 0) {
							clearTimeout(time);
							hideDolgozom()
						}
						onError( respond, ioArgs );
					}
		});	
	}
}

///////////////////////////
//post-ban küldhet paramétert json kódolt adat jön vissza
function runAjaxJson(phpURL, onLoad, onError, showDolgozom) {
	ajaxRunCount += 1;
	//dolgozom kép bekapcsolása (dolgozom_div)
	if ((typeof showDolgozom ) == "undefined"  || showDolgozom == null) {
		showDolgozom = true;
	}

	if (showDolgozom) {
		var loading = document.getElementById("dolgozom_div");
		if (loading != null) {
			var time = setTimeout(function() {loading.style.visibility = "visible";}, 1000);
			loading.style.left = "450px";
			loading.style.top = "250px";
		}
	}

	if ((typeof onError) == 'undefined') {
		jQuery.noConflict();
		jQuery.ajax({
		url : phpURL,
		dataType : "json",

		timeout : 10000,

		success : function(respond) {
			ajaxRunCount -= 1;
			if (onLoad != null) {
				onLoad(respond );
			}
			if (showDolgozom && ajaxRunCount === 0) {
				clearTimeout(time);
				if (loading != null) {
					loading.style.visibility = "hidden";
				}       
			}
		},

		error : function(XMLHttpRequest, textStatus, errorThrown) {
				ajaxRunCount -= 1;
				if (onLoad != null) {
					onLoad(respond );
				}
				if (showDolgozom && ajaxRunCount === 0) {
					clearTimeout(time);
					if (loading != null) {
						loading.style.visibility = "hidden";
					}       
				}
				alert('Valami hiba történt (próbáld újra): '+errorThrown);
				console.error("errorThrown: ", errorThrown);
				console.error("textStatus: ", textStatus);
			}
		});

	} else {
		jQuery.noConflict();
		jQuery.ajax({
			url : phpURL,
			dataType : "json",
			timeout : 10000,
			success : function(respond) {
				ajaxRunCount -= 1;
				if (onLoad != null) {
					onLoad(respond );
				}
				if (showDolgozom && ajaxRunCount === 0) {
					clearTimeout(time);
					if (loading != null) {
						loading.style.visibility = "hidden";
					}       
				}
			},
			error : onError
		});
	}
}

function forEach(nodes, nodeFgv) {
	dojo.forEach(nodes, nodeFgv );
}

function connectToEvent(node, event, fgv) {
	try {
		dojo.connect(node, event, fgv);
	} catch(e) {
		console.debug('can\'t connectToEvent');
	}
}

/*
jsInclude funkció

Leírás:
Include funkciót hajt végre az ?url? argumentumban
megdott *.js fájlra. Azaz betölti az oldalra.

Argumentumok:
? url: a fájl elérési útja, amit be akarunk húzni,
? useOnce: true kell, hogy legyen, ha csak egyszer akarjuk, hogy megjelenjen
az aktuális script a weblapon belül.

Visszatérés:
? true, ha hozzáfűződött a javascript
*/
function jsInclude(host, url, useOnce) {

	if (httpBase == 'undefined' || host != httpBase + '/') {

		alert('Rossz hosztnév vagy nincs telepítve a config_js.js' );
		return false;
		
	} else {
		
		// a fejléc elem megkeresése
		var head = document.getElementsByTagName("head").item(0);
		//kiolvassuk az összes objektumot a fejlécből
		var jss = head.getElementsByTagName("script");
		// tag számláló
		var index = 0;

		//Csak egyszer használható?
		if (useOnce == true) {
			//Ha csak egyszer akarjuk használni, akkor kell keresni, hogy megvan-e
		
			//Végigfutunk, hogy van-e már ilyen script behúzva
			for(; (index < jss.length) && (jss.item(index).getAttribute("src") != host + url); index++);
		}
		//Megtaláltuk (azaz nem futott túl az ?index?) vagy többször is be akarjuk húzni?
		if (index == jss.length || useOnce == false) {
			//Nem létezik vagy többször is használható, ezért létrehozhatjuk
		
			//Egy új elem létrehozása és felparaméterezése
			var js = document.createElement("script");
			js.setAttribute("language", "javascript");
			js.setAttribute("type", "text/javascript");
			js.setAttribute("src", host + url);

			//A elem hozzáadása a fejléc elemhez
			head.appendChild(js);

			//Hozzáfűztük szóval true-t kell visszaadni
			return true;
		}

		//Nem adódott hozzá a megadott javascript
		return false;
	}

	//Nem adódott hozzá a megadott javascript
	return false;
}
/*
jsInclude funkció

Leírás:
Include funkciót hajt végre az ?url? argumentumban
megdott *.js fájlra. Azaz betölti az oldalra.

Argumentumok:
? url: a fájl elérési útja, amit be akarunk húzni,
? useOnce: true kell, hogy legyen, ha csak egyszer akarjuk, hogy megjelenjen
az aktuális script a weblapon belül.

Visszatérés:
? true, ha hozzáfűződött a javascript
*/
function cssInclude(host, url, useOnce) {
	if (httpBase == 'undefined' || host != httpBase + '/') {

		alert('Rossz hosztnév vagy nincs telepítve a config_js.js' );
		return false;
		
	} else {
		// a fejléc elem megkeresése
		var head = document.getElementsByTagName("head").item(0);
		//kiolvassuk az összes objektumot a fejlécből
		var css = head.getElementsByTagName("link");
		// tag számláló
		var index = 0;

		//Csak egyszer használható?
		if (useOnce == true) {
			//Ha csak egyszer akarjuk használni, akkor kell keresni, hogy megvan-e

			//Végigfutunk, hogy van-e már ilyen script behúzva
			for(; (index < css.length) && (css.item(index).getAttribute("src") != host + url); index++);
		}

		//Megtaláltuk (azaz nem futott túl az ?index?) vagy többször is be akarjuk húzni?
		if (index == css.length || useOnce == false) {

			//Nem létezik vagy többször is használható, ezért létrehozhatjuk

			//Egy új elem létrehozása és felparaméterezése
			var cssNode = document.createElement("link");
			cssNode.type = 'text/css';
			cssNode.rel = 'stylesheet';
			cssNode.media = 'screen';
			cssNode.href =  host + url;

			//A elem hozzáadása a fejléc elemhez
			head.appendChild(cssNode);

			//Hozzáfűztük szóval true-t kell visszaadni
			return true;
		}

		//Nem adódott hozzá a megadott javascript
		return false;
	}
    
	//Nem adódott hozzá a megadott javascript
    return false;
}


/* fejléc menü functions */

// menu init
var inMenu = 0;
var menuActive = '';
var timeOn = null;

// show menu
function wpShowMenu(menuName) {
    if (document.getElementById(menuName)) {
        if (timeOn != null) {
            clearTimeout(timeOn);
            wpHideMenu(menuActive);
        }
        document.getElementById(menuName).style.visibility = 'visible';
        menuActive = menuName;
    }
}

// hide menu
function wpHideMenu(menuName) {
    if (inMenu == 0) {
        document.getElementById(menuName).style.visibility = 'hidden';
    }
}

// mouse out timer
function wpMenuTimer(lastMenuName) {
    if (document.getElementById(lastMenuName)) {
        timeOn = setTimeout("wpMenuTimeout()", 150);
    }
}

// hide button on mouse out
function wpMenuTimeout() {
    if (inMenu == 0) {
        wpHideMenu(menuActive);
    }
}

// menu mouseover
function wpMenuOver(menuButton) {
    clearTimeout(timeOn);
    inMenu = 1;
    if (document.getElementById('menuButton_'+menuButton) && menuButton.length) {
        document.getElementById('menuButton_'+menuButton).className = 'header_page_name_menu_over';
    }
}

// menu mouse out
function wpMenuOut(menuButton, className) {
    inMenu = 0;
    timeOn = setTimeout("wpHideMenu(menuActive)", 50);
    if (document.getElementById('menuButton_'+menuButton) && menuButton.length) {
        document.getElementById('menuButton_'+menuButton).className = className;
    }
}

////////////////////////////////////////////////////////////////////////////////

function initSessionFrissit(url,refreshSec) {
  if ((typeof url != "undefined" ) && (url != null)) {
      sessionFrissitUrl=url;
      if ((typeof refreshSec != "undefined" ) && (refreshSec != null)) {
        sessionFrissitSecs=refreshSec;
      } else {
        refreshSec = 60;
        sessionFrissitSecs=refreshSec;
      }
      beginSessionFrissit(sessionFrissitSecs,sessionFrissitUrl,sessionFrissitSecs);
  }
}

function beginSessionFrissit(secsToRefesh,sessionUrl,sessionSecs) {
  if (secsToRefesh==1) {
    runAjaxJson(sessionUrl, null, null, false );
	ajaxRunCount -= 1;
    secsToRefesh=sessionSecs;
    setTimeout('beginSessionFrissit('+secsToRefesh+',\''+sessionUrl+'\','+sessionSecs+')',1000);
  } else {
    secsToRefesh-=1;
    setTimeout('beginSessionFrissit('+secsToRefesh+',\''+sessionUrl+'\','+sessionSecs+')',1000);
  }
}

function tableScrollJump(div_id, sor_id) {
	if (sor_id.length > 0) {
		var rows = document.getElementById(div_id).getElementsByTagName('tr');
		var i = 0;
		var magassag = 0;
		var tablamagassag = document.getElementById(div_id).clientWidth;
		while(i < rows.length && rows[i].id != sor_id) {
			if (rows[i].id.length > 0 ) magassag = magassag + rows[i].clientHeight + 0;
			++i;
		}
		//scrollHelyzet = magassag - (tablamagassag/2 );
		scrollHelyzet = magassag;
		document.getElementById(div_id).scrollTop = scrollHelyzet;
	}
	return true;
}

//benne van-e a class?
function hasClass(elem,clas) {
	return elem.className.match(new RegExp('(\\s|^)'+clas+'(\\s|$)'));
}

//class hozzáadása az elemhez
function addClass(elem,clas) {
	if (!this.hasClass(elem,clas)) elem.className += " "+clas;
}

//class leszedése
function removeClass(elem,clas) {
	if (hasClass(elem,clas)) {
		var reg = new RegExp('(\\s|^)'+clas+'(\\s|$)');
		elem.className=elem.className.replace(reg,' ');
	}
}

/**
 * Concatenates the values of a variable into an easily readable string
 * by Matt Hackett [scriptnode.com]
 * @param {Object} x The variable to debug
 * @param {Number} max The maximum number of recursions allowed (keep low, around 5 for HTML elements to prevent errors) [default: 5]
 * @param {String} sep The separator to use between [default: a single space ' ']
 * @param {Number} l The current level deep (amount of recursion). Do not use this parameter: it's for the function's own use
 */
function print_r(x, max, sep, l) {
	l = l || 0;
	max = max || 5;
	sep = sep || ' ';
	if (l > max) {
		return "[WARNING: Too much recursion]\n";
	}
	var
		i,
		r = '',
		t = typeof x,
		tab = '';
	if (x === null) {
		r += "(null)\n";
	} else if (t == 'object') {
		l++;
		for (i = 0; i < l; i++) {
			tab += sep;
		}
		if (x && x.length) {
			t = 'array';
		}
		r += '(' + t + ") :\n";
		for (i in x) {
			try {
				r += tab + '[' + i + '] : ' + print_r(x[i], max, sep, (l + 1));
			} catch(e) {
				return "[ERROR: " + e + "]\n";
			}
		}
	} else {
		if (t == 'string') {
			if (x == '') {
				x = '(empty)';
			}
		}
		r += '(' + t + ') ' + x + "\n";
	}
	return r;
}; 

var cursorKeys ='8;46;37;38;39;40;33;34;35;36;45;';
function searchInList(field, selectForm, select, property, event, prefix) {
	var found = false;
		// enterre submitolja a listát
	if (event.keyCode == 13) {
		selectForm.submit();
		return;
	}
		// lefelé nyílra eggyel lejjebb lép a listában
	if (event.keyCode == 40) {
		select.selectedIndex += 1;
		field.value = select.options[select.selectedIndex][property];
		return;
	}
		// felfelé nyílra eggyel lejjebb lép a listában
	if (event.keyCode == 38) {
		select.selectedIndex -= 1;
		field.value = select.options[select.selectedIndex][property];
		return;
	}
		// megnézi, hogy talál e ilyen szövegű option-t
	for (var i = 0; i < select.options.length; i++) {
		if (select.options[i][property].toUpperCase().indexOf((prefix + field.value.toUpperCase()) ) == 0) {
			found=true;
			break;
		}
	}
		// ha talált beállítja a listában kiválasztottként
	if (found) select.selectedIndex = i;
	else select.selectedIndex = -1;
}

function searchInTable(field, submitForm, selected, tableDivID, event, searchSubmits, prefix) {
	var found = false;
		// enterre submitolja a listát
	if (event.keyCode == 13) {
		submitForm.submit();
		return;
	}
		// lefelé nyílra eggyel lejjebb lép a listában
	if (event.keyCode == 40) {
		for (divID in searchSubmits) {
			if (found) {
				foundDivID = searchSubmits[divID];
				break;
			}
			if (foundDivID == searchSubmits[divID] ) found = true;
		}
		// felfelé nyílra eggyel vissza lép a listában
	} else if (event.keyCode == 38) {
		var elozoDivID = 0;
		for (divID in searchSubmits) {
			if (foundDivID == searchSubmits[divID] && elozoDivID != 0) {
				foundDivID = elozoDivID;
				break;
			} else {
				elozoDivID = searchSubmits[divID];
			}
		}
		// megnézi, hogy talál e ilyen szövegű table feliratot
	} else {
		for (divID in searchSubmits) {
            var containerDiv = document.getElementById(divID );
            var searchedText = containerDiv.innerHTML;
            searchedText = trim(searchedText );

			if (searchedText.toUpperCase().indexOf((prefix + field.value.toUpperCase()) ) == 0 && field.value.length > 0) {
				foundDivID = searchSubmits[divID];
				break;
			}
		}
	}
    var scrollTopValue = 0;
	for (divID in searchSubmits) {
		var divElement = document.getElementById(divID );
			// találat háttérszín beállítása
		if (foundDivID == searchSubmits[divID]) {
			selected.value = searchSubmits[divID];
			divElement.style.background='#336699';
			divElement.style.color='white';

                // scrollTop beállítása a keresett szöveghez
            var containerDiv = document.getElementById(divID );
            var positionTomb = getElementPosition(containerDiv);
            scrollTopValue = positionTomb[1] - 200;
            } else if ( divElement ) {
			divElement.style.background='transparent';
			divElement.style.color='black';
		}
	}
        // scroll beállítása
    var tableDiv = document.getElementById(tableDivID );
    tableDiv.style.overflow = 'scroll';
    tableDiv.scrollTop = scrollTopValue;
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}


/*	///////////////////////////////////////	*/
/*	SCE DESIGN	*/
/*	///////////////////////////////////////	*/

/*	Az oldal control elemeinek vizuális kiválasztása	*/
function setSelectedControlElements () {
	var pageContent = jQuery('body').html();
	var pageIDsStr = (pageContent.match(/<!--pageid.*?-->/g));
	if (!pageIDsStr) return;
	for (i = 0; i < pageIDsStr.length; i++) {
		var lastColon = pageIDsStr[i].lastIndexOf(":");
		actPageID = pageIDsStr[i].substring(11, lastColon);
		var controllButtonRowTypeA = document.getElementById('cs_'+actPageID);
		var controllButtonRowTypeB = document.getElementById('tab_'+actPageID);
		///
		if (controllButtonRowTypeA) {
			controllButtonRowTypeA.setAttribute('class', 'wp_Bttn_bttnCtrlBttnSelected');
			var controllButtonRowR = document.getElementById('cs_'+actPageID+'R');
			controllButtonRowR.setAttribute('class', 'wp_Bttn_bttnCtrlBttnSelectedR');
		}
		if (controllButtonRowTypeB) {
			controllButtonRowTypeB.setAttribute('class', 'wp_tabBttnSelected');
			var controllButtonRowR = document.getElementById('tab_'+actPageID+'R');
			controllButtonRowR.setAttribute('class', 'wp_tabBttnSelectedR');
			var controllButtonRowLbl = document.getElementById('tab_'+actPageID+'_lbl');
			controllButtonRowLbl.setAttribute('class', 'wp_tabBttnSelectedLbl');
		}
	}
}

/*	design checkbox vizuális frissítése	*/
function refreshDsgnChckBoxView (sceID, imgsPath) {
	sceID += "";	/// force to create a string
	if (sceID.substring(0, 15) == "checkBox_check_") {
		sceID = sceID.substring(15);
	} else {
		sceID = sceID;
	}
	var chkElement = document.getElementById('checkBox_check_'+sceID);
	if (chkElement != null) {
		var chkImg = document.getElementById('checkBox_img_'+sceID);
		if (chkImg != null) {
			if (chkElement.checked) {
				chkImg.src = imgsPath+"wp_named_checkbox_checked.png";	
			} else {
				chkImg.src = imgsPath+"wp_named_checkbox_normal.png";
			}
		}else{
			refreshDsgnChckBoxView_v2(sceID);
			//return false;
		}
	}
	return true;
}
/*	design checkbox vizuális frissítése V2	*/
function refreshDsgnChckBoxView_v2 (sceID) {
	var chkElement = document.getElementById('checkBox_check_'+sceID);
	var chkDesign = document.getElementById('wp_checkBoxDIV_'+sceID);
	if (chkElement != null) {
		if (chkElement.checked) { chkDesign.style.backgroundPosition = "0 -15px";
		} else { chkDesign.style.backgroundPosition = "0 0"; }
	}
}
/*	Set the combo's visible label	*/
function setComboFakeTxt(trgt, lbl_ID) {
	var actList = document.getElementById(trgt);
	if (actList.selectedIndex >= 0) document.getElementById(lbl_ID).innerHTML = actList.options[actList.selectedIndex].text;
}

//megszerzi az adatból a bejelölt rádio gomb értékét
function getSelectedRadioButton(adat) {
	console.debug(adat);
	for (var i=0; i < adat.length; i++) {
		if (adat[i].checked) {
			return adat[i].value;
		}
	}
}
/*	+/- képlistához thumbnail preview-kat mutat	*/
function showImgPreview (dir, imgName, left, top) {
	var shiftX = 24;
	var prevDIV = document.getElementById("imgPreviewDIV");
	if (!prevDIV) prevDIV = createDiv("imgPreviewDIV", "<img alt=\"\" id=\"imgPreview\" src=\"\" />", "100px", "100px", left+shiftX+"px", top+"px", "#666666", "1px solid #ffffff", 9999);
	pictURL = dir + getFileName_w_postfix(imgName);
	document.getElementById("imgPreview").src = pictURL;
	prevDIV.style.overflow = "hidden";
	ImgSizes = getImgSize(pictURL);
	prevDIV.style.width = ImgSizes[0]+"px";
	prevDIV.style.height = ImgSizes[1]+"px";
	prevDIV.style.left = left+shiftX+"px";
	prevDIV.style.top = top+"px";
	prevDIV.style.padding = "1px 1px 1px 1px";
}
/*	+/- képlistához egérmutató helyzetének elkapása	*/
function catchMouseXY4ImgPreview(e) {
	if (IE4XY) { // grab the x-y pos.s if browser is IE
		tempX = event.clientX + document.body.scrollLeft; tempY = event.clientY + document.body.scrollTop;
	} else {  // grab the x-y pos.s if browser is NS
		tempX = e.pageX; tempY = e.pageY
	}
	// catch possible negative values in NS4
	if (tempX < 0) {tempX = 0}; if (tempY < 0) {tempY = 0};
	///
	prevImgName = null;
	if (this.text) {	/// Képlistához (select)
		prevImgName = this.text
	} else if (this.value) {	/// Egy kép feltöltohöz (input mezo)
		prevImgName = this.value
	} else {
		console.debug("*************** Error!: catchMouseXY4ImgPreview(e) *************** \n No image name defined!");
	}
	if (prevImgName) showImgPreview (uplDir4ImgPreview, prevImgName, tempX, tempY);
}
/*	MSG 4 VIEW ALERT DESIGN	*/
function showMsgForViewDsgnDIV(str) {
	prevDIV = createDiv("msgForViewDsgnDIV", str, "", "", "", "", "", "", 99999);
	prevDIV.onmouseup = function () { removeElement('msgForViewDsgnDIV'); }
	prevDIV.data_opacity = 100;
	setTimeout('fadeOutMsgForViewDsgnDIV()', 3400);
}
function fadeOutMsgForViewDsgnDIV() {
	trgtDIV = document.getElementById("msgForViewDsgnDIV");
	if (trgtDIV) {
		trgtDIV.data_opacity = Math.round(trgtDIV.data_opacity-(trgtDIV.data_opacity/14))-2;
		if (trgtDIV.data_opacity <= 0) {
			removeElement('msgForViewDsgnDIV');
		} else {
			changeOpacity(trgtDIV, trgtDIV.data_opacity);
			setTimeout('fadeOutMsgForViewDsgnDIV()', 34);
		}
	}
}

/*	///////////////////////////////////////	*/
/*	COLOR PICKER							*/
/*	///////////////////////////////////////	*/
function setColorsByPicker (RGB, callObj) {
	var prntSceID = callObj.parentNode.parentNode.parentNode.parentNode.title;
	document.getElementById("colorPickerDIV_"+prntSceID).style.visibility = "hidden";
	document.getElementById("textfield_"+prntSceID).value = "#"+RGB;
}
function showHideColorPicker (pickerID) {
	pickerDIV = document.getElementById(pickerID);
	if (pickerDIV.style.visibility == "hidden") {
		pickerDIV.innerHTML = colorPickerInnerHTML;
		pickerDIV.style.visibility = "visible";
	} else { pickerDIV.style.visibility = "hidden"; }
}



/*	///////////////////////////////////////	*/
/*	IMG-hez (képekhez kapcsolódó müveletek)	*/
/*	///////////////////////////////////////	*/

/*	képméret lekérése	*/
function getImgSize(imgSrc) {
	var newImg = new Image();
	newImg.src = imgSrc;
	var width = newImg.width;
	var height = newImg.height;
	var ImgSizes = new Array(width, height);
	return ImgSizes;
}
/// Visszaadja a feltöltött (eredeti) fájlnévbol a thumb és a preview fájlok neveit,
/// a postfix változóban kell megadni ("th", vagy "pre"), hogy melyiket akarjuk (alapból "th")
/// Pl.: kép01.jpg ==> kép01_th.jpg és kép01_pre.jpg
function getFileName_w_postfix (fileName, postfix) {
	postfix = (postfix) ? postfix : "th";
	fName = fileName.substring(0, fileName.lastIndexOf("."));
	fExt = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length);
	return fName+"_"+postfix+"."+fExt;
}
