/*requires prototype.js*/
var speedWarningCount = 0;
var normalRequestCount = 0;
var featureList = [ 'pivot' ];

var History = {
	lastHash: null,
	MakeHistory: function( paramstr/*, title*/ )
	{
		this.lastHash = paramstr;
		
		if( navigator.userAgent.indexOf('MSIE') != -1 )
		{
			frames["backDummy"].document.open();
			frames["backDummy"].document.write("<script>parent.document.location.hash = '" + paramstr + "';</script>");
			frames["backDummy"].document.close();
		}
		else
		{
			//document.title = paramstr;
			document.location.hash = paramstr;
		}
	},
	
	getHistoryChange: function()
	{	
		if ( document.location.hash != replaceAll( document.location.hash, "%7C", "|" ) ) {
			document.location.hash = replaceAll( document.location.hash, "%7C", "|" );		
		}
		if( this.lastHash == document.location.hash.substring(1) )
			return null;
		else
		{
			this.lastHash = document.location.hash.substring(1);
			return this.deserialize(document.location.hash.substring(1));
		}
	},
	
	//hash: module:"modulnev"|portfolioid:"123"/ {deszerializalt objektum mezonevei:deszerializalt objektum adattagjai}*
	serialize: function( moduleName, obj )
	{
		var str = new String("");
		if ( portfolioselector ) {
			str += "module:" + /*Modules.activeModule.*/moduleName + "|portfolioid:" + portfolioselector.getselectedid() + "/";
		}
		
		var n = 0;
		for( var prop in obj )
		{		
			str += (n==0? "":"|") + prop + ":" + obj[prop];
			n++;
		}
		return str;	
	},
	
	deserialize: function( param )
	{
		var obj = new Object();
		//var mainparams = null, objparams = null;
		if(param.indexOf("/") == -1 ) return null;
		var params = param.split("/");

		//fo parameterek kinyerese
		var mainparams = params[0].split("|");
		for(var i = 0; i < mainparams.length; i++ )
		{
			var parameter = mainparams[i].split(":");
			obj[parameter[0]] = parameter[1]; 
		}

		//tarolt objektum deserializacioja
		obj.moduleState = new Object();
		var objstring = params[1].split("|");
		for(var i = 0; i < objstring.length; i++ )
		{
			var parameter = objstring[i].split(":");
			obj.moduleState[parameter[0]] = parameter[1];
		}
		
		return obj;
	}
	
	
}

var State = {
	portfolio_id: null,
	todate: null
};

var Modules = {
	//modulok
	Summary:null,
	Portfolio:null,
	PortfolioTree:null,
	PL:null,
	Risk:null,
	Transactions:null,
	PriceWatch:null,
	Settings:null,

	moduleNames: new Array( "Summary","Portfolio","PortfolioTree","PL","Risk","Transactions","PriceWatch","Settings" ),
	moduleURLs: new Array( "Summary","Portfolio","PortfolioTree","PL","Risk","Transactions","PriceWatch","Settings" ),
	activeModule: null,
	applicationTitle : "",
	
	addModuleList: function( moduleList ) {
		if ( moduleList ) {
			for ( var i = 0; i < moduleList.length; i++ ) {
				this.addModule( moduleList[ i ].moduleURL, moduleList[ i ].moduleURL, moduleList[ i ].displayName );
			}	
		}
	},
	
	addModule: function( moduleName, url, displayName ) {
		var splitted = moduleName.split( "/" );

		var shortModuleName = splitted[ splitted.length - 1  ];

		this.moduleNames.push( shortModuleName );
		this.moduleURLs.push( url );
		
		var container = document.createElement( "div" );
		container.id = shortModuleName + "Container";
		container.className = "modulecontainer";
		container.style.display = "none";	
		
		$( "ModulesContainer" ).appendChild( container );
				
		var innerMenuSpan = document.createElement( "span" );
		innerMenuSpan.className = "inner";
		innerMenuSpan.innerHTML = displayName;
		
		var menuList =  $( "top-col-2" ).select( '.lastmenuitem' );
		for ( var i = 0; i < menuList.length; i++ ) {
			Element.removeClassName( menuList[ i ], "lastmenuitem" );
		}	
		
		var outerMenuSpan = document.createElement( "span" );
		outerMenuSpan.id = "mainmenu" + shortModuleName.toLowerCase();
		Element.addClassName( outerMenuSpan, "menuitem" );
		Element.addClassName( outerMenuSpan, "lastmenuitem" );
		
		outerMenuSpan.appendChild( innerMenuSpan );		
		$( 'top-col-2' ).appendChild( outerMenuSpan );		
		outerMenuSpan.onmouseover = MainMenu.OnEnterItem.bind( $( outerMenuSpan.id ), $( outerMenuSpan.id ) );
		outerMenuSpan.onmouseout = MainMenu.OnLeaveItem.bind( $( outerMenuSpan.id ), $( outerMenuSpan.id ) );
		outerMenuSpan.onclick = Modules.activateModule.bind( Modules, shortModuleName );
	},
	
	loadModule: function( moduleName,/*innentol opcionalis*/ url, params, callback ) {
		if( !url ) {
			url = this.moduleURLs[ this.moduleNames.indexOf( moduleName ) ];
			if ( !url ) {
				url = moduleName.toLowerCase() + ".jsp"; 
			} else {
				url = url.toLowerCase() + ".jsp";
			}
		}
		this.getContainerOf(moduleName).show();
		new PageLoader( url, params, this.getContainerOf(moduleName), globalthis, false, callback);
	},
		
	activateModule: function( moduleName, moduleState, url ) {
		//ha nincs ilyen probaljuk meg betolteni
		//document.title = "Pozitron:" + moduleName;		
		
		if( !this.getModule( moduleName ) ) {
			this.loadModule(moduleName, url, null, this._doActivation.bind(this, moduleName, moduleState, true) );
		} else {
			this._doActivation( moduleName, moduleState, false );	
		}
	},
	
	//sendToActive: ha true, akkor az aktiv modulnak is elkuldi, kulonben nem
	notifyModules: function( eventObject, sendToActive ) {
		//megnezzuk, hogy van-e benne olyan valtozo, ami a globalis state-et is erinti
		if ( eventObject[ "MODULE_STATE" ] ) {
			if ( eventObject[ "MODULE_STATE" ][ "todate" ] ) {
				State.todate = eventObject[ "MODULE_STATE" ][ "todate" ];
			}
			if ( eventObject[ "MODULE_STATE" ][ "portfolio_id" ] ) {
				State.portfolio_id = eventObject[ "MODULE_STATE" ][ "portfolio_id" ];
			}		
		}
	
		for ( var i = 0; i < this.moduleNames.length; i++ ) {
			var mod = this.getModule( this.moduleNames[ i ] );
			if ( mod != null && !mod.noPermission && ( sendToActive == true || ( sendToActive != true  && mod != this.activeModule ) ) ) {
				mod.receiveEvent.call( mod, eventObject );
			}
		}	
	},
	
	notifyModule: function( moduleName, eventObject ) {
		var mod = this.getModule( moduleName );
		if ( mod != null && !mod.noPermission ) {
			mod.receiveEvent.call( mod, eventObject );		
		}	
	},
	
	
	//egy nem aktiv modul aktivalasa -> resume
	//initial: ha true, akkor ez a kezdeti aktivalas, ha mas, akkor nem az
	_doActivation: function(moduleName, moduleState, initial)
	{
		try{
			if( this.getModule(moduleName )	)
			{
				if(this.activeModule){
					this.activeModule.moduleContainer.hide();	
					if ( !this.activeModule.noPermission ) {
						this.activeModule.suspend();
					}
				}
				this.activeModule = this.getModule( moduleName );
				//kezdetinel nem kell resume!
				//TODO: a show atkerult ide, hogy a mereteket le lehessen kerdezni mar a resume-ben
				this.activeModule.moduleContainer.show();
				if ( !initial ) {
					this.activeModule.receiveEvent( { "MODULE_STATE": moduleState || {} } );
					if ( !this.activeModule.noPermission ) {
						this.activeModule.resume();
					}
				} else {
					//Modules.setNotApplicable( Modules.activeModule, false );				
					this.activeModule.OnCreate( moduleState );
				}
				//this.activeModule.moduleContainer.show();
				MainMenu.selectItem( "mainmenu"+moduleName.toLowerCase() );
				this.activeModule.OnResize();
			}

			var title = this.applicationTitle + ": ";
			if ( this.activeModule && this.activeModule.translatedModuleName ) {
				title += this.activeModule.translatedModuleName;
			} else {
				title += this.activeModule.moduleName;
			}
			document.title = title;			
		}
		catch (e) {alert(Str.pozitron.doActErr + e + "\n(" + e.message + ")");}
	},
	
	getContainerOf: function( moduleName ) {
		return $(moduleName + "Container" );
	},
	
	getModule: function( moduleName ) {	
		var mod = null;
		try { eval( "mod = Modules." + moduleName ); }
		catch( e ){ return null;}
	
		return mod;
	},
	/*	
	setNotApplicable: function( module, on_or_off, errorMessage ) {
		if ( module ) {
			if ( on_or_off ) {
				module.inNotApplicableState = true;
				if ( errorMessage ) {			
					$( "ErrorMessageContainer" ).innerHTML = errorMessage;
				} else {
					$( "ErrorMessageContainer" ).innerHTML = "Válasszon ki egy ügyfélportfóliót!";				
				}
				module.moduleContainer.style.display = "none";
				$( "ErrorMessageContainer" ).style.display = "";
			} else {
				module.inNotApplicableState = false;			
				module.moduleContainer.style.display = "";
				$( "ErrorMessageContainer" ).style.display = "none";
			}
		}	
	},
	*/
	observeHistoryTimer : null,
	//history valtozasat figyelo fv
	observeHistoryChange: function( param )
	{
		if( param == "stop")
		{
			window.clearTimeout( this.observeHistoryTimer );
			this.observeHistoryTimer = null;
			return;
		}
		else if( param == "start" )
		{
			this.observeHistoryTimer = window.setTimeout(this.observeHistoryChange.bind(this), 200 );
			return;
		}
		
		var params = null;
		if( params = History.getHistoryChange() )
		{
			//alert( "a hash valtozott erre: " + params );
			//hash: module:"modulnev"|portfolioid:"123"/ {deszerializalt objektum mezonevei:deszerializalt objektum adattagjai}*
			//Modules.activateModule( nev, {MODULE_STATE: {deszerializalt objektum adattagjai}});

			if ( portfolioselector ) {			
				if ( portfolioselector.getselectedid() != params.moduleState.portfolio_id ) {
					//var conn = new Connector("DispatcherServlet","req=getportfoliotree&action=standard&printroot=true&numberoflevels=1&root_id=" + params.moduleState.portfolio_id, function( resp) { var pList = eval ( resp ); portfolioselector.portfolio_data = pList[ 0 ]; $("portfolios").innerHTML = pList[ 0 ].portfolioname;}, false);
					portfolioselector.refresh( params.moduleState.portfolio_id );
				}
			}
			
			params.moduleState._fromHistory = true;
			Modules.activateModule( params.module, params.moduleState );			
			//alert( {MODULE_STATE: params.moduleState}.toSource() );
		}
		this.observeHistoryTimer = window.setTimeout(this.observeHistoryChange.bind(this), 200 );
	}
	
	
};

function ModuleTemplate(){};
ModuleTemplate.prototype = {
	modulename: "",
	moduleContainer: null,
	moduleState: {},
	moduleTabs: null,
	noPermission: false,	
	suspend: function(){},
	resume: function(){},
	OnCreate: function(ModuleState){},
	OnResize: function(ModuleState){},
	receiveEvent: function( eventObject ){},
	applyModuleState: function( moduleState ) {}
	//OnPortfolioChange(portfolio),
};

var RenewSession = {
	loginDialogObj : null, // loginDialogObj: logindialog.js-ben
	loginInProgress: false,
	loginDialog: null,
	requestList: null,
	initReLogin: function(){
		this.loginInProgress = true;
		this.requestList = new Array();
		var param = {};
		param.code = this.loginDialogObj;
		param.width = 300;
		param.modal = true;
		param.modalParent = $( "master" );
		param.createParams = {};
		param.position = "center";
		param.noclose = true;
		RenewSession.reLoginDialog = new Dialog( param );
	},
	finishReLogin: function(){
		var cl = RenewSession.requestList;
		if ( cl != null ) {
			for( var i=0; i<cl.length; i++ )
			{
				if( cl[i].type == "connector" ) {
					new Connector( cl[i].request.req_service, cl[i].request.req_params, cl[i].request.readyFunc );
				} else if( cl[i].type = "pageloader" ) {
					//page, params, target, globalref, unloadeventlisteners, callback, caching
					new PageLoader( cl[i].request.page,
									cl[i].request.params,
									cl[i].request.target,
									cl[i].request.globalref,
									null,
									cl[i].request.callback,
									null
					);
				}									
				cl[i] = null;
			}
		}
		cl = null;
		RenewSession.connectorList = null;
		RenewSession.loginInProgress = false;
	},
	isLoginInProgress: function(){
		return this.loginInProgress;
	},	
	addConnectorToList: function( connector ) {
		//alert( "Connector added: \n" + connector.req_params );
		var item = new Object();
		item.request = connector;
		item.type = "connector";
		this.requestList.push( item );
	},	
	addPageLoaderToList: function( pageloader ) {
		var item = new Object();
		item.request = pageloader;
		item.type = "pageloader";
		this.requestList.push( item );
	}
};

var Reconnect = {
	requestList: new Array(),
	reconnectInProgress: false,
	startReconnect: function(){
		this.reconnectInProgress = true;
		this.testConnection();
	},
	testConnection: function(){
		var tester = "connectionTest.jsp";
		var num = new Date().getTime();
		var param = { chk: num };
		this.testConn = new Ajax.Request( tester, { method: 'get', parameters: param, onSuccess: this.testConnSuccess.bind( this, num ), onFailure: this.testConnFail.bind( this ) } );
		this.testConnTimer = window.setTimeout( this.testConnFail.bind(this), 20000 );
	},
	testConnSuccess:function(chk, result){
		window.clearInterval( this.testConnTimer );
		var respObj = null;
		try {
			respObj = eval( "(" + result.responseText + ")" );
		} catch ( e ) {
		}
		if( respObj && respObj.result_code == "notloggedin" ){
			if( !RenewSession.isLoginInProgress() ){
				RenewSession.initReLogin();
			}	
		}
		if( result.responseText != "OK" ){
			//alert( "result.responseText{"+ result.responseText + "} != chk{" + chk + "}");
			this.testConnFail(result);
			return;
		}
		//alert( "testConnSuccess" );
		var cl = this.requestList;
		for( var i=0; i<cl.length; i++ )
		{
			//alert( cl[i].toSource() );
			if( cl[i].type == "connector" )
				new Connector( cl[i].request.req_service, cl[i].request.req_params, cl[i].request.readyFunc );
			else if( cl[i].type = "pageloader" )
				//page, params, target, globalref, unloadeventlisteners, callback, caching
				new PageLoader( cl[i].request.page,
								cl[i].request.params,
								cl[i].request.target,
								cl[i].request.globalref,
								null,
								cl[i].request.callback,
								null
				);
								
			cl[i] = null;
		}
		this.requestList = cl.compact();
		cl = null;
		//alert( this.requestList.toSource() );
		this.reConnectInProgress = false;
	},
	testConnFail: function(result){
		//alert( "testConnFail" );
		this.testConn.transport.abort();
		window.setTimeout( this.testConnection.bind(this), 20000);
		window.clearInterval( this.testConnTimer );
	},
	addConnectorToList: function( connector ) {
		//alert( "Connector added: \n" + connector.req_params );
		var item = new Object();
		item.request = connector;
		item.type = "connector";
		this.requestList.push( item );
		if( !this.reconnectInProgress )
			this.startReconnect();
	},
	addPageLoaderToList: function( pageloader ) {
		var item = new Object();
		item.request = pageloader;
		item.type = "pageloader";
		this.requestList.push( item );
		if( !this.reconnectInProgress )
			this.startReconnect();
	}
};

var Help = {
	helpWindow: null,
	showHelp: function()
	{
		var am = Modules.activeModule;
		var parameters;
		/*
		if( am.moduleTabs ) {
			parameters =  "{ languageId: '" + userInfo.languageId.toLowerCase() + "' , moduleName: '" + am.moduleName.toLowerCase() + "', moduleTab: '" + am.moduleTabs.tabData[ am.moduleTabs.activetab ].div.toLowerCase().replace(".", "/") + "' }";
		}else{
			parameters =  "{ languageId: '" + userInfo.languageId.toLowerCase() + "' , moduleName: '" + am.moduleName.toLowerCase() + "' }";
		}
		*/

		parameters =  "{ languageId: '" + userInfo.languageId.toLowerCase() + "' , moduleName: 'attekintes' }";			
		
		
		if( this.helpWindow == null || this.helpWindow.closed ){
			this.helpWindow = window.open( "./help/" + userInfo.languageId.toLowerCase() + "/" + "help.jsp?parameters=" + escape(parameters), "helpWindow", "toolbar=no,height=600,width=900");		
			//this.helpWindow.resizeTo(900, 600);
		} else {
			this.helpWindow.focus();
			this.helpWindow.location = "./help/" + userInfo.languageId.toLowerCase() + "/" + "help.jsp?parameters=" + escape(parameters), "helpWindow", "toolbar=no";
		}
		var url = "./help/" + userInfo.languageId.toLowerCase() + "/" + "help.jsp";
	},
	
	loadHelpPage: function( pageName, targetDivName ) {
		var pageLoader = new PageLoader("./help/" + userInfo.languageId.toLowerCase() + "/" + pageName,'', targetDivName, globalthis, false );
	}
};

var StatusCheckerService = {
	timer: null,
	timerFunc: null,
	gotDataFunc: null,
	connection: null,
	interval: 30000,
	
	start: function(){
		this.timerFunc = this.onTimer.bind(this);
		this.gotDataFunc = this.gotData.bind(this);
		this.timer = window.setTimeout( this.timerFunc, this.interval );
	},
	
	stop: function(){
		window.clearTimeout(timer);
		this.timerFunc = null;
	},
	
	onTimer: function(){
		this.connection = null;
		this.connection = new Connector( "DispatcherServlet", "req=checkstatus", this.gotDataFunc );
		this.timer = window.setTimeout( this.timerFunc, this.interval );		
	},
	
	gotData: function( data ){
		var commandObj = null;
		try{
			commandObj = eval( data );
		} catch (e) {
			return;
		}
		if( commandObj.command == "refresh" ) {
			Modules.notifyModules.call( Modules, {"TRANSACTIONS_CHANGED":true}, true );
		}
	}
	
};

var MainMenu = {
	selectedMenu: null,
	
	OnLeaveItem: function( menuitem ) {	
		//var inner = menuitem.select( '.inner' )[ 0 ];
		var inner = menuitem.getElementsByTagName("span")[0];
		inner.style.textDecoration = "none";				
		if ( MainMenu.selectedMenu != menuitem ) {
			inner.style.color = Skin.skinMainMenuInactiveColor;
		}
	},
	
	OnEnterItem: function( menuitem ) {
		//var inner = menuitem.select( '.inner' )[ 0 ];
		
		var inner = menuitem.getElementsByTagName("span")[0];
		inner.style.textDecoration = "underline";
		inner.style.color = Skin.skinMainMenuActiveColor;
	},
	
	selectItem: function( menuname ) {
		MainMenu.selectedMenu = $( menuname );
		//var menuList =  Element.select( $( "top-col-2" ), '.menuitem' );
		var menuList =  $( "top-col-2" ).childElements();
		for ( var i = 0; i < menuList.length; i++ ) {
			//var inner =  Element.select( menuList[ i ], '.inner' )[ 0 ];
			var inner =  menuList[ i ].getElementsByTagName("span")[0];
			inner.style.color = Skin.skinMainMenuInactiveColor;
		}
		
		if( $( menuname ) ) {
			
			var item = null;
			for ( var i = 0; i < menuList.length; i++ ) {
				if ( menuList[i].id == menuname ) {
					item = menuList[i];
				}
			}
		
			//var inner =  Element.select( item, '.inner' )[ 0 ];	
			var inner = item.getElementsByTagName("span")[0];
			inner.style.color = Skin.skinMainMenuActiveColor;
		}
	}
}

///----------------------------------------------Segédfüggvények innentől------------------------------------------

function hideSelectElements( element, except ) {
	var hiddenSelects = new Array();
	var elmSels = element.getElementsByTagName( "select" );
	var exceptSels = except.getElementsByTagName( "select" );
	
	for( var i=0; i< elmSels.length; i++ ) {
		var except = false;
		for( var j=0; j < exceptSels.length; j++ )
			if( elmSels[i] == exceptSels[j] || elmSels[i].style.visibility == "hidden"  )
				except = true;
		if( !except )
			hiddenSelects.push( elmSels[i] );
	}
	
	for( var i=0; i<hiddenSelects.length; i++ )
		hiddenSelects[i].style.visibility = "hidden";
	

	return hiddenSelects;
}

function unhideSelectElements( elements ) {
	for( var i = 0; i < elements.length; i++ )
		elements[i].style.visibility = "";

}


function loadPage( page, target, globalref, unloadeventlisteners ) {
	//alert("loadPage: " + page);
	var conn = new PageLoader( page, null, target, globalref, unloadeventlisteners );
}

/*
function extractScripts ( html, ScriptFragment ) {
  var matchAll = new RegExp ( ScriptFragment, 'img' );
  var matchOne = new RegExp ( ScriptFragment, 'im' );
 
  var scripts = ( html.match ( matchAll ) || [] );
  var script  = new Array ();
  for ( i = 0; i < scripts.length; i++ ) {
    script.push (( scripts[ i ].match ( matchOne ) || [ '', '' ] )[ 1 ] );
  }
  return script;
}
*/

function extractScripts ( html ) {
	var scripts = new Array();
	
	var pos = 0;
	var beginIndex = 0;
	var endIndex = 0;
	
	while ( pos < html.length ) {
		beginIndex = html.indexOf( "<script", pos );
		if ( beginIndex == -1 ) break;		
		beginIndex = html.indexOf( ">", beginIndex );
		if ( beginIndex == -1 ) break;
		endIndex = html.indexOf( "</script>", beginIndex );
		
		scripts.push( html.substring( beginIndex + 1, endIndex ) );		
		pos = endIndex + 1;
	}
	
	return scripts;		
}

function evalScriptSource( sourceArray, callBackFunc ) {
	for ( var i = 0; i < sourceArray.length; i++) {
		new Connector( sourceArray[i], undefined, globalEval, false );	
	}
	callBackFunc();
}

function applyInnerHTML ( div, html, globalref ) {
  //html = replaceAll( html, "\n", "" );
  //html = replaceAll( html, "\t", "" );  
	
  var ScriptFragment = '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)';
  //div.innerHTML = html.replace ( new RegExp ( ScriptFragment, 'img' ), '' );
  div.innerHTML = html;
  var scripts = extractScripts ( html, ScriptFragment );
  //alert( "scripts length: " + scripts.length );
  try {
    for ( i = 0; i < scripts.length; i++ ) {
    	globalEval( scripts[i] );
    }
  }
  catch ( e ) {
    window.alert('Error while EVAL()ing: ' + e.message);
  }
}

function globalEval(src) {
    if (window.execScript) {
        window.execScript(src);
        return;
    }
    var fn = function() {
        window.eval.call(window,src);
    };
    fn();
};

function replaceAll( str, from, to ) {
	if ( from == ' ' && to == '' ) {
		return removeSpaces( str );
	}

    var idx = str.indexOf( from );

    while ( idx > -1 ) {
        str = str.replace( from, to );
        idx = str.indexOf( from );
    }

    return str;
}

function removeSpaces( str ) {
	
	if ( str ) {
		var splitted = (String(str)).split( ' ' );
		if ( splitted ) {
			return splitted.join( '' );
		}	
	}
		
	return str;
}

function getURLFriendlyString( original ) {
	var retval = String(original).unescapeHTML();
	retval = removeAccents( retval );
	retval = replaceSpaces( retval, '_' );
	retval = replaceAll( retval, '&', '' );
	retval = replaceAll( retval, '.', '' );	
	retval = replaceAll( retval, '\'', '' );
	retval = replaceAll( retval, '/', '' );	
	retval = replaceAll( retval, '?', '' );
	retval = retval.toLowerCase();
	
	return retval;
}

function removeAccents( s ) {

	var withaccents = "öüóőúéáűíÖÜÓŐÚÉÁŰÍ";
	var withoutaccents = "ouooueauiOUOOUEAUI";

    var retval = String( s );

    for ( var i = 0; i < withaccents.length; i++ ) {
      retval = replaceAll( retval, withaccents[ i ], withoutaccents[ i ] );
    }

    return retval;
}

function replaceSpaces( str, newspace ) {
	
	if ( str ) {
		var splitted = (String(str)).split( ' ' );
		if ( splitted ) {
			return splitted.join( newspace );
		}	
	}
		
	return str;
}

//yyyy.mm.dd
function getDateFromString( dateString ) {
	var dates = replaceAll( dateString, " ", "" );
	var tmpDate = new Date();
	tmpDate.setFullYear( Number(dates.substring(0,4)), Number(dates.substring(5,7))-1, dates.substring(8, 10) );
	
	return tmpDate;
}

//yyyy.mm.dd hh:mm
function getTimestampFromString( dateString ) {
	if ( dateString.length < 16 ) {
		return getDateFromString( dateString );
	}
	var tmpDate = new Date( Number(dateString.substring(0,4)), Number(dateString.substring(5,7))-1, dateString.substring(8, 10), dateString.substring(11, 13), dateString.substring(14, 16) );
	
	return tmpDate;
}


//a mai naptol szamitva numberofdays nappal korabbi (-) / kesobbi (+) datum
//ha a givendate meg van adva, akkor attol a datumtol szamolja az elt?r?st
function getDateString( numberofdays, givendate, includetime, includesecond ) {
	var tmpDate = new Date();
	if (givendate != null ) {
		tmpDate = givendate;
	}
	
	tmpDate.setDate( tmpDate.getDate() + numberofdays );			
	
	var month = tmpDate.getMonth() + 1;
	var day = tmpDate.getDate();
						
	if ( month.toString().length == 1) month = '0'+ month;
	if ( day.toString().length == 1) day = '0'+ day;
	
	var time = "";
	
	if ( includetime ) {
		var hours = tmpDate.getHours();
		var minutes = tmpDate.getMinutes();
		if ( hours.toString().length == 1) hours = '0'+ hours;
		if ( minutes.toString().length == 1) minutes = '0'+ minutes;					
		
		time = " " + hours + ":" + minutes;
		
		if ( includesecond ) {
	  		var seconds = tmpDate.getSeconds();		
	  		if ( seconds.toString().length == 1) seconds = '0'+ seconds;
			time = time + ":" + seconds;		
		}
	}						
			
	return tmpDate.getFullYear() + "." + month + "." + day + time;
}

/*TESZT:*/
function showlog()
{
	$("log").style.display = "";
}

function hidelog()
{
	$("log").style.display = "none";
}

var keszletertekeles_modszer = [
{id: "FIFO", description: Str.pozitron.keszletErt_FIFO}];

var allamkotveny_ertekeles_modszer = [
{id: "DISZKONTALT_CF", description: Str.portfolioEditor.s11007},
{id: "UTOLSO_AR", description: Str.portfolioEditor.s11009}];

var vallalati_kotveny_ertekeles_modszer = [
{id: "DISZKONTALT_CF", description: Str.portfolioEditor.s11007},
{id: "UTOLSO_AR", description: Str.portfolioEditor.s11009}];

var hitel_betet_ertekeles_modszer = [
{id: "DISZKONTALT_CF", description: Str.portfolioEditor.s11007},
{id: "FELHALMOZOTT_KAMAT", description: Str.portfolioEditor.s11008}];

function getNameByID( id, buffer, idcolname, namecolname, namecolnameindex ) {
	for ( var i = 0; i < buffer.length; i++ ) {
		if ( buffer[ i ][ idcolname ] == id ) {			
			if ( namecolnameindex ) {
				return buffer[ i ][ namecolname ][ namecolnameindex ];
			} else {
				return buffer[ i ][ namecolname ];
			}
		}	
	}
	return null;
}

function getCurrencyNameByID( id ) {
	for ( var i = 0; i < currencies.length; i++ ) {
		if ( currencies[ i ].id == id ) {
			return currencies[ i ].name;
		}	
	}
	return null;
}

function getBenchmarkJSONString( benchmarkobj ) {
	var retval = "[";
	if(benchmarkobj[0].properties){
		for ( var i = 0; i < benchmarkobj.length; i++){
			if ( i > 0 ) retval += ","
			retval += "{validfrom:\"" + benchmarkobj[ i ].validfrom +"\",validto:\"" + benchmarkobj[ i ].validto+"\",properties:[";
			for ( var j = 0; j < benchmarkobj[i].properties.length; j++){		
				if ( j > 0 ) retval += ",";
				retval += "{p:" + benchmarkobj[ i ].properties[j].p +",w:" + benchmarkobj[ i ].properties[j].w;
				if ( benchmarkobj[ i ].properties[j].o ) {
					retval += ",o:" + benchmarkobj[ i ].properties[j].o;
				}
				retval += "}";
			}
			retval += "]}";
		}		
	} else {
		// regebbi szerkezet
		for ( var i = 0; i < benchmarkobj.length; i++ ) {
			if ( i > 0 ) retval += ",";
			retval += "{p:" + benchmarkobj[ i ].p +",w:" + benchmarkobj[ i ].w;
			if ( benchmarkobj[ i ].o ) {
				retval += ",o:" + benchmarkobj[ i ].o;
			}
			retval += "}";	
		}	
	}
	retval += "]";
	
	return retval;
}

function getBenchmarkString( benchmark ) {
	
	var retval = "";
	
	for ( var i = 0; i < benchmark.length; i++ ) {
		if ( i > 0 ) retval += "<br/>";
		if(benchmark.length > 1) retval += benchmark[ i ].validfrom + "-" + benchmark[i].validto + ": ";
		if ( benchmark[i].properties.length == 1) {
			var str = getNameByID( benchmark[ i ].properties[0].p, indexes, "id", "data", "0" );
			
			if ( !str ) {
				str = getNameByID( benchmark[ i ].properties[0].p, currencies, "id", "name", null );
			}
			
			if ( benchmark[ i ].properties[0].o ) {
				str += "+" + ( benchmark[ i ].properties[0].o ) + "%";
			}
			
			retval += str;
		} else {
			for( var j = 0; j < benchmark[i].properties.length; j++) {
				if ( j > 0 ) retval += " + ";
				retval += benchmark[ i ].properties[j].w + " % ";
				
				var str = getNameByID( benchmark[ i ].properties[j].p, indexes, "id", "data", "0" );
				
				if ( !str ) {
					str = getNameByID( benchmark[ i ].properties[j].p, currencies, "id", "name", null );
				}
				
				if ( benchmark[ i ].properties[j].o ) {
					str += "+" + ( benchmark[ i ].properties[j].o ) + "%";
				}
				retval += str;
			}
		}
	}
	
	return retval;
}

function fillCurrencies( target, noDelete ) {
	
	if ( noDelete == null || noDelete == false ) {
		while ( target.firstChild ) {
			target.removeChild( target.firstChild );
		}
	}
	
	for (var i=0; i<currencies.length; i++) {
		var opt = document.createElement("option");
		opt.innerHTML = currencies[i].name;
		opt.value = currencies[i].id;	
		target.appendChild( opt );
	}
}

function setSelectedValue( select, id ) {
	for ( var i = 0; i < select.options.length; i++ ) {
		if ( select.options[ i ].value == id ) {
			select.options[ i ].selected = true;
		} else {
			select.options[ i ].selected = false;		
		}
	}
}

//melyik selectet toltse fel, melyik tombbol, mi az id oszlop neve, mi a megjelenitendo oszlop neve
function fillOptions( select, optarray, idname, displayname ) {
	while ( select.firstChild ) {
		select.removeChild( select.firstChild );
	}

	for( var i = 0; i < optarray.length; i++ ) {		
			var opt = document.createElement( "option" );
			opt.value = optarray[i][idname];
			opt.innerHTML = optarray[i][displayname];

			select.appendChild( opt );
	}
}

function fillSelectWithIntegerList( select, from, to, step, leadingZerosLength ) {

	if ( !step ) {
		step = 1;
	}
	
	var intList = new Array();
	
	for ( var i = from; i <= to; i+=step ) {
		var act = new Object();
		
		var val = i;
		
		if ( leadingZerosLength ) {
			val = new String( i );			
			var actLen = val.length;
			for ( var j = actLen; j < leadingZerosLength; j++ ) {
				val = '0' + val;							
			}		
		}
		act.id = val;
		act.value = val;	
		intList.push( act );
	}
	
	fillOptions( select, intList, "id", "value" );
}

function fillProducts( target, product_type_id, dataarray, delete_content ) {
	if ( dataarray == null ) {
		dataarray = products;
	}
	if ( delete_content ) {
		while ( target.firstChild ) {
			target.removeChild( target.firstChild );
		}
	}
	
	for (var i=0; i<dataarray.length; i++) {
		if ( product_type_id == null || dataarray[ i ].data[1] == product_type_id ) {		
			var opt = document.createElement("option");
			opt.innerHTML = dataarray[ i ].data[ 0 ];
			opt.value = dataarray[ i ].id;	
			target.appendChild( opt );
		}
	}
}

//visszaadja a kivalasztott portfolio id-jet
//ha m?g nincs kivalasztva semmi, akkor a user default portfoliojanak id-jet
function getSelectedPortfolioID() {
	var id = -1;
	if ( portfolioselector ) {
		id = portfolioselector.getselectedid();
	}
	if ( /*id == null || id == ""*/ !id || id == -1 ) {
		id = default_portfolio_id;
	}	
	return id;
}

function liveFormatNumber (e,id) {
	if ($( this.id).value!="") {
		$( this.id).value = $( this.id).value.replace(/[^0-9]+/g,'');
		var value = formatNumber(normalizeNumber($( this.id).value)," ",0);
		//value=String.fromCharCode(e.charCode)+value;
		$( this.id).value=value;
		//alert(value);
	}
}

function formatNumber( num, separator, precision, min_digits, adjustToPoint ) {
	if ( num == null || num == 'undefined' ) return "";
	var nStr=Number(num);		
	if (precision>-1) nStr=nStr.toFixed(precision);
	nStr=nStr+''; //string legyen
	x = nStr.split('.');
	x1 = x[0];
	//hany jegy az egeszresz
	var x1len = x1.length;
	x2 = x.length > 1 ? x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + separator + '$2');
	}
	if( min_digits != null && min_digits != 'undefined' )
	{		
		var count = 0;
		var pos = x2.length-1;
		for( ; pos > min_digits-1; pos--)
		{
			if( x2.charAt(pos) == '0' ) 
			{
				x2 = x2.substr(0,x2.length-1);
				count++;
			}
			else 
				break;	 
		}

		/*
		if ( x2.length > 6 - x1len ) {
			x2 = x2.substr(0, 6 - x1len );
		}
		*/		
	}	
	
	if( adjustToPoint )
	{
		var invisiblestr="<span style='visibility: hidden;'>";
		for( var i=0; i<=precision - x2.length; i++)
			invisiblestr += "0";
		invisiblestr += "</span>";
		
		x2 += invisiblestr; //":" + count;
	}
	return x1 + ( x2.length > 0 ? '.' : '' ) + x2;
}

function formatNumberWithScale( value, multiLangBillion ){ 
      var retval = value; 
      var scale = ''; 
        if(retval >= 1000000 || retval <= -1000000){ 
          retval*=0.000001; 
          if(retval >= 1000 || retval <= -1000){ 
            retval*=0.001; 
            scale = ' ' + multiLangBillion;
          } else{ 
            scale = ' M'; 
          }
      } 
      // ha nem volt valtas, nem kell tizedesjegy
		retval = formatNumber(retval, ' ', 2, 0);
      return retval + scale;
}

function normalizeNumber( num ) {
	var temp = replaceAll( num+"", ",", "." );
	return replaceAll( temp, " ", "" );
}

function removeAllChildren( element ) {
	while ( element.firstChild ) {
		element.removeChild( element.firstChild );
	}
}

function recRemoveAllChildren( element ) {
	if ( element ) {
		while ( element.firstChild ) {
			recRemoveAllChildren2( element.firstChild );
		}
	}
}

function recRemoveAllChildren2( element ) {
	if ( element ) {
		if ( element.firstChild ) {
			while ( element.firstChild ) {	
				recRemoveAllChildren2( element.firstChild );	
			}
		} else {
			element.parentNode.removeChild( element );
		}
	}
}

function cleanUpAll( element ) {
	if (window.opera || !document.all) return;
	var objects = element.getElementsByTagName("OBJECT");
	for (var i=0; i < objects.length; i++) {
		objects[i].style.display = 'none';
		for (var x in objects[i]) {
			if (typeof objects[i][x] == 'function') {
				objects[i][x] = null;
			}
		}
	}
}

function PageWidth () {
  if ( window.innerWidth ) return window.innerWidth;
  else if (( document.body ) && ( document.body.offsetWidth )) return document.body.offsetWidth;
  return 0;
}

function PageHeight () {
   var iHeight = 0;

   if( typeof ( window.innerWidth ) == 'number' ) {
     iHeight = window.innerHeight;
   }
   else {
     if( document.documentElement && ( document.documentElement.clientWidth
	|| document.documentElement.clientHeight ) ) {
       iHeight = document.documentElement.clientHeight;
     }
     else {
       iHeight = document.body.clientHeight;
     }
   }
   return iHeight;

}

function getBrowserType () {
  var browser      = new Object ();
  browser.platform = navigator.platform.substr ( 0, 3 );
  browser.browser  = navigator.appName;
  browser.version  = navigator.appVersion.substr ( 0, 1 );
  return browser;
}

function iframeUploadData( formId, iframeParentId, formCallback ) {
  var form         = $( formId );
  var iframeParent = $( iframeParentId );

  var iframe               = document.createElement ( 'iframe' );
  iframe.id                = 'iFrame' + formId;
  iframe.name              = 'iFrame' + formId
  iframe.style.width       = '0px';
  iframe.style.height      = '0px';
  iframe.style.borderWidth = '0px'

  iframeParent.appendChild ( iframe );
  window.frames[ 'iFrame' + formId ].name = 'iFrame' + formId;

  form.target   = 'iFrame' + formId;
  //form.method   = 'post';
  form.enctype  = 'multipart/form-data';
  form.encoding = 'multipart/form-data';

  if ( getBrowserType().browser == 'Microsoft Internet Explorer' ) {
    var loadedFv = function () {
          if ( iframe.contentWindow.document.readyState == 'complete' ) {
            var resultStr = iframe.contentWindow.document.body.innerHTML;
            if ( formCallback != null ) formCallback ( resultStr );
            setTimeout ( function () { iframe.parentNode.removeChild ( iframe ); }, 100 );
          }
          else window.setTimeout ( loadedFv, 100 );
        };
    window.setTimeout ( loadedFv, 100 );
  }
  else {
    iframe.onload = function () {
      iframe.onload = null;
      var resultStr = iframe.contentWindow.document.body.innerHTML;
      if ( formCallback != null ) formCallback ( resultStr );
      setTimeout ( function () { iframe.parentNode.removeChild ( iframe ); }, 100 );
    };
  }
  form.submit ();
}

function createTableFromJSON() //arguments: jsonStruct (array of objects), column1, ... columnN 
{
	var jsonStruct = arguments[0];
	var colNames = new Array();
	if( arguments.length > 1 )
	{
		for( i=1; i < arguments.length; i++)
			colNames.push( arguments[i] );
	}
	else
	{
		for( x in jsonStruct[0]) 
			colNames.push( x );
	}
	var table = document.createElement("table");
	var tbody = document.createElement("tbody");
	table.appendChild(tbody);
	
	var rows = new Array();
	var cells = new Array();
	for( var i = 0; i < jsonStruct.length; i++ )
	{
		var _row = document.createElement( "tr" );
		var _cells = new Array();
		for( var j = 0; j < colNames.length; j++ )
		{
			var cell = document.createElement( "td" );
			cell.innerHTML = jsonStruct[i][ colNames[j] ];
			_row.appendChild( cell );
			_cells.push( cell );
		}
		tbody.appendChild( _row );
		rows.push( _row );
		cells.push( _cells );
	}
	var res = new Object();
	res.table = table; 
	res.rows = rows;
	res.cells = cells;
	return res;
}


//titleObj: a fieldset legend objektum maga
function zoomChart( chartobj, title, titleObj, showFunc, closeFunc ) {
	var id = "Zoom.chartzoom_" + (new Date()).getMilliseconds();
	var legendObj = null;
	var legendHTML = "";
	
	if ( titleObj ) {
		var divObj = getNextSibling( titleObj );
		if ( divObj ) {
			var legendObj = getNextSibling( divObj );
		}
	}

	if ( legendObj && legendObj.tagName && legendObj.tagName.toUpperCase() == "TABLE" ) {
		legendHTML = "<table style='padding-bottom:0px;font-size:13px;' align='center' class='chartlegendtable'>" + legendObj.innerHTML + "</table>";
	}	
	
	var obj = {	
			title: "Chart",
			newchart : null,
			getContent: function() {
				return "<div id='"+id+"' style='width:700px;height:480px;padding:10px 10px 10px 10px;'></div>" + legendHTML;
			},					
			onCreate: function() {
				this.setCaption(this.title);
				if ( chartobj.getAttribute('swf').indexOf('Pie') == -1 ) {
					this.newchart = new FusionCharts( chartobj.getAttribute('swf'), id, "100%","100%",false,false,'','exactFit');
				} else {
					this.newchart = new FusionCharts( chartobj.getAttribute('swf'), id, "640","450",false,false,'','');				
				}
				this.newchart.setDataXML( chartobj.getVariable( 'dataXML' ) );
				this.newchart.render( id );
			}					
	};
	if( title ) obj.title = title;
	obj.closeFunc = cleanUpAll;
	obj.closeFuncParam = id;
	if( showFunc ) showFunc();
	var dialog = new Dialog( { code: obj, width:"740", modal:false, borderColor: "black"} );			
}

function setCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {		
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function deleteCookie(name) {
	setCookie(name,"",-1);
}

function getNextSibling(startBrother){
  if ( !startBrother ) return null;
  endBrother=startBrother.nextSibling;
  if ( !endBrother ) return null;
  while(endBrother.nodeType!=1){
    endBrother = endBrother.nextSibling;
    if ( !endBrother ) return null;
  }
  return endBrother;
}

function changeLang( newLang, isTemp ) {
	if ( isTemp ) {
		setCookie( "temp_lang", newLang, 90 );	
	} else {
		setCookie( "lang", newLang, 90 );		
	}
	
	window.location.reload( true );
	//window.location.replace( unescape( window.location.pathname ) );
	/*
	var oldAddress = window.location;
	window.location.href = "";
	window.location.href = oldAddress;
	*/
}

function setCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {		
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function deleteCookie(name) {
	setCookie(name,"",-1);
} 	


function showUserMessages( initialData ) {
	var param = {};
	param.url = "messages.dialog";
	param.width = "500";
	param.modal = false;
	param.position = "center";			
	//param.modalParent = $( "SettingsPage.UserDetailsTab" );
	param.createParams = {};
	param.createParams.returnFunc = null;
	param.createParams.initialData = initialData;
			
	var dialog = new Dialog( param );       		
}

function fillControls( controlIDPrefix, dataObj, noNullsOnFields, selectFirstInSelectOnNull ) {
	for ( var act in dataObj ) {
		var elem = $( controlIDPrefix + act );
		if ( elem ) {
			if ( elem.type == "text" || elem.type == "hidden" || elem.type == "textarea")   {			
				if ( noNullsOnFields && ( dataObj[ act ] == null || "null" == dataObj[ act ] ) ) {
					elem.value = '';
				} else {
					elem.value = dataObj[ act ];
				}
			} else if ( elem.type == "select" || elem.type == "select-one" ) {
				if ( !selectFirstInSelectOnNull && ( dataObj[ act ] == null || "null" == dataObj[ act ] ) ) {
					elem.value = '';
				} else {
					if ( !( dataObj[ act ] == null || "null" == dataObj[ act ] ) ) {
						elem.value = dataObj[ act ];
					}
				}			
			} else if ( elem.type == "checkbox" ) {
				if ( dataObj[ act ] && dataObj[ act ] != "0" ) {
					elem.checked = true;
				} else {
					elem.checked = false;				
				}
			}
		}
	}	
}

function showSpeedWarning() {
	speedWarningCount++;
	normalRequestCount = 0;
	if ( speedWarningCount > 2 && $( "MainPage.showError" )) {
		$( "MainPage.showError" ).style.visibility = "";	
		speedWarningCount = 0;
	}
}

function hideSpeedWarning() {
	normalRequestCount++;
	if ( normalRequestCount > 10 && $("MainPage.showError"))  {
		$( "MainPage.showError" ).style.visibility = "hidden";
		normalRequestCount = 0;
	}
}

function KillAllHints() {
	//TODO IE-ben valami nem jo....
	try {
		var hints = document.body.getElementsByClassName("hint");
		if ( hints != null ) {
			for( var i=0; i < hints.length; i++) {
				try {
				while(hints[i].firstChild)
					hints[i].removeChild(hints[i].firstChild);
				hints[i].parentNode.removeChild(hints[i]);
				hints[i] = null;
				} catch(e) {
				}
			}
		}
	} catch( e ) {	
	}
}

function updateDOM(inputField) {
    // if the inputField ID string has been passed in, get the inputField object
    if (typeof inputField == "string") {
        inputField = document.getElementById(inputField);
    }

    if (inputField.type == "select-one") {
        for (var i=0; i<inputField.options.length; i++) {
            if (i == inputField.selectedIndex) {
                inputField.options[inputField.selectedIndex].setAttribute("selected","selected");
            }
        }
    } else if (inputField.type == "text") {
        inputField.setAttribute("value",inputField.value);
    } else if (inputField.type == "textarea") {
        inputField.setAttribute("value",inputField.value);
    } else if ((inputField.type == "checkbox") || (inputField.type == "radio")) {
        if (inputField.checked) {
            inputField.setAttribute("checked","checked");
        } else {
            inputField.removeAttribute("checked");
        }
    }
}

function updateDOMForFields(id) {
  elem=document.getElementById(id);
  i=elem.getElementsByTagName('input');
  s=elem.getElementsByTagName('select');
  t=elem.getElementsByTagName('textarea');
  field_sets=Array(i,s,t);
  for(x=0;x<field_sets.length;x++){
    set=field_sets[x];
    for(y=0;y<set.length;y++){
      updateDOM(field_sets[x][y]);
    }
  }
}

function include_dom(script_filename) {
   var html_doc = document.getElementsByTagName('head').item(0);
   var js = document.createElement('script');
   js.setAttribute('language', 'javascript');
   js.setAttribute('type', 'text/javascript');
   js.setAttribute('src', script_filename);
   html_doc.appendChild(js);
   return false;
}

 function getOffsetTopByElement ( e ) {
   var offsetTop = 0;
   do {
     offsetTop += ( e.offsetTop );
     e = e.offsetParent;
   } while ( e );
   return offsetTop;
 }
 
 function getOffsetLeftByElement  ( e ) {
   var offsetLeft = 0;
   do {
     offsetLeft += ( e.offsetLeft - e.scrollLeft );
     e = e.offsetParent;
   } while ( e );
   return offsetLeft;
 } 

 
 function ChangeFooterSize () {
    var divFooter     = $('bottom-section');
    var tableFooter   = $('bottom-section-table');
    if (divFooter && tableFooter) {
    	var iFooterTop    = getOffsetTopByElement ( divFooter );
    	var iPageHeight   = PageHeight ();
    	var iNewDivHeight = Math.max ( iPageHeight - iFooterTop - 20, 15 );
		divFooter.style.height   = iNewDivHeight + 'px';
		tableFooter.style.height = ( iNewDivHeight ) + 'px';
	}

    setTimeout ( ChangeFooterSize, 1000 );
  }
  
function getVarhatoEletHonap( kor, nem, tol ) {
		var korList = [ 30, 35, 40, 45, 50, 55 ];
		var honapList = [ 210, 204, 198, 192, 186, 180 ];
		if ( nem == "no" ) {
			honapList = [ 270, 264, 258, 252, 246, 240 ];
		}

		var retval = honapList[ 0 ];
		
		for ( var i = 0; i < korList.length; i++ ) {
			if ( kor > korList[ i ] ) {
				if ( i < korList.length - 2 ) {
					//interpolalunk					
					retval = honapList[ i ] + ( honapList[ i + 1 ] - honapList[ i ] ) * ( ( kor - korList[ i ] ) / ( korList[ i + 1 ] - korList[ i ] ) ) ;					
				} else {
					retval = honapList[ korList.length - 1 ]
				}
			}
		}
		
		return retval - ( tol - 62 ) * 12;
}

function promptValue( title, returnFunc, modalParent ) {
		var param = {};
		param.url = "prompt.dialog";
		param.width = "300";
		param.position = "center";
		param.createParams = {};
		param.createParams.title = title;
		param.createParams.returnFunc = returnFunc;
		param.modal = true;
		param.modalParent = modalParent;		

		var dialog = new Dialog( param );	
}
	
function checkDateFormat( dateString ) {
	if (
		dateString.length == 10 &&
		Object.isNumber(Number(dateString.substring(0,1))) &&
		Object.isNumber(Number(dateString.substring(1,2))) &&
		Object.isNumber(Number(dateString.substring(2,3))) &&
		Object.isNumber(Number(dateString.substring(3,4))) &&
		
		dateString.substring(4,5) == '.' &&
		
		Object.isNumber(Number(dateString.substring(5,6))) &&
		Object.isNumber(Number(dateString.substring(6,7))) &&
		
		dateString.substring(7,8) == '.' &&
		
		Object.isNumber(Number(dateString.substring(8,9))) &&
		Object.isNumber(Number(dateString.substring(9,10)))
		) return true;
	return false;		
}

function deepCopy(obj) {
	//alert(Object.prototype.toString.call(obj));
      if (Object.prototype.toString.call(obj) === '[object Array]') {
    	  //alert('isArray');
	      var out = [], i = 0, len = obj.length;
	      for ( ; i < len; i++ ) {
	      	out[i] = arguments.callee(obj[i]);
	      }
	      return out;
      }
      if (typeof( obj ) === 'object') {
    	  //alert('isObject');
	      var out = {}, i;
	      for ( i in obj ) {
	      	out[i] = arguments.callee(obj[i]);
	      }
	      return out;
      }
      return obj;
}
