/**
 * EasyKat Framework
 * 
 * ported from Zend Framework 0.1.4 
 * Copyright (c) 2006 Zend Technologies USA Inc. (http://www.zend.com)
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.plansoft.de/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to info@plansoft.de so we can send you a copy immediately.
 *
 * @category   EasyKat
 * @package    EasyKat.Transformer
 * @copyright  Copyright (c) 2007 Plan Software GmbH (http://www.plansoft.de)
 * @license    http://www.plansoft.de/license/new-bsd     New BSD License
 */
EasyKat.Transformer.EasyGUI = function() {
	this.components = {};
	this.attributes = {};
	
	EasyKat.Transformer.EasyGUI.superclass.constructor.call(this);
	
	var CATALOG				= Object.fromStorage("ROOT.CATALOG");

	this.m_uiSystem			= CATALOG.UI.BASE.toLowerCase();
	
	this.m_ResultType 		= 'HTML';
	this.m_bInternalTransform = true;
	this.m_bAutoStyle 		= true;
	this.m_guiPath 			= CATALOG.UI.BASE_PATH.toLowerCase() + "/" + this.m_uiSystem;
	this.m_guiDebug			= false; // CATALOG.UI.DEBUG.toLowerCase() == "true";
	this.m_TempDir			= CATALOG.HTMLTEMP.trimRight(dirsep()) + dirsep();
	this.m_bCdMode			= CATALOG.INTERNETSERVERINCDMODE.toLowerCase() == "true";
	this.m_bCdSocketMode	= CATALOG.CDSOCKETMODE.toLowerCase() == "true";
	this.m_bReloadMaps		= false; // CATALOG.RELOADMAPS.toLowerCase() == "true";
	
	this.m_ProgDir			= getstddirectory("PROGRAM_SHORT");
	
	var sessId 				= getstring("sessionid","");
	var statId 				= getstring("stateid","");
		
	if(this.m_ProgDir == "") {	
		// Falls die Parameter "PROGRAM_SHORT" und "PROGRAM_UTF8" noch nicht funktionieren.
		// "PROGRAM_SHORT" sollte zu "PROGRAM" werden falls das '~' Zeichen keinen Ärger macht.
		this.m_ProgDir = getstddirectory("PROGRAM");
	}
	
	this.m_hostPort			= CATALOG.PORT;
	this.m_hostUrl			= this.m_bCdMode ? "http://localhost:" +this.m_hostPort + "/" : "";
	this.m_pathMapFiles		= this.m_guiPath + "/maps/";
	this.m_pathCustomMap	= CATALOG.UI.CUSTOM_MAP_PATH.toLowerCase();
	this.m_storageRootPath	= "EASYGUI";
	this.m_storagePath		= "EASYGUITRANSFORM";

	this.m_reqURL			= getdlgvar("REQUEST_URL");	// Im Servermode als Ziel für Action
			
							// @@@@@ MW
	this.m_pathInFile		= this.m_ProgDir + getstring("INFILE",this.m_storagePath);	// Parameter für EasyGuiTransform
	this.m_DialogId			= getstring("AKTUELLE_MASKE","");	// Parameter für EasyGuiTransform
	
	
	if(typeof CATALOG.ENCODING.SCREEN == "undefined" )
		CATALOG.ENCODING.SCREEN = "utf-8";

	this.m_bUtf8 			= CATALOG.ENCODING.SCREEN.toLowerCase() == "utf-8";
	
	if(typeof CATALOG.UI.INTERNALTRANSFORM == "undefined")
		CATALOG.UI.INTERNALTRANSFORM = false;
		
	//if( this.m_ResultType=="HTML" /*&& this.m_bInternalTransform==true*/ ) {
		this.m_pathOutFile = gettempfile(this.m_TempDir,"htm");	// HTML erzeugen
	//}
	
	if(!checkexist(this.m_storageRootPath,"ROOT")) {
		this.importMaps();
		this.prepareAliasReplace("RELATIVE");		
		this.initSpecialComponents();
	}
	
	if(typeof CATALOG.UI.FORMATOUTPUT == "undefined" ) {	
		CATALOG.UI.FORMATOUTPUT = true;
	}

	// Wie sollen die Aliase im Html ersetzt werden?
	this.m_aliasMethod = checkexist("ALIAS_METHOD",this.m_storagePath) ? getstring("ALIAS_METHOD",this.m_storagePath) : "";
	delete("ALIAS_METHOD",this.m_storagePath); // "Einwegparameter"
	
	if( this.m_aliasMethod != "FILE" && this.m_aliasMethod != "RELATIVE" )
	{	// automatisch wählen
		this.m_aliasMethod= !this.m_bCdMode || (this.m_bCdMode && this.m_bCdSocketMode) ? "RELATIVE" : "FILE";
	}

	this.setDefaultValue("sessionid", sessId );
	this.setDefaultValue("stateid", statId );
	
	// und setzen
	setalias("ROOT"~this.m_storageRootPath~"REPLACE_TABLE", this.m_aliasMethod~"REPLACE_TABLE");
	CATALOG.toStorage( "ROOT" );
}

EasyKat.extend( EasyKat.Transformer.EasyGUI, EasyKat.Transformer.Abstract,
{	
	/**
	 *
	 */
	transform : function() {
		// Altes Temp File löschen 
		var bDeleteOldFiles = 0;
		if( bDeleteOldFiles && this.m_bCdMode && !this.m_bCdSocketMode )
			var r = filecommand("unlink", getstring("EKHTMLTEMPFILE",""));
			
		setstring("EKHTMLTEMPFILE","",this.m_pathOutFile);
				
		// Das Parser-Duo CXMLSAXBuilder & EKEasyGuiTransform starten...
		// In: m_pathInFile (Template) / m_DialogId
		// Out: m_pathOutFile (Erzeugte Html oder XML Datei)
		easyguixmlparser();
		delete( this.m_storagePath, "" );
		return this.m_pathOutFile;
	},
	
	/**
	 *
	 */
	importMaps : function() 
	{
		this.importScriptMap("components.map","COMPONENTS");
        this.importMap("attributes.map","ATTRIBUTES");
        this.importMap("events.map","EVENTS");
        this.importMap("styles.map","STYLES");
        this.importMap("defaults.map","STANDARDS");
        
		var EK_PATH=replace(this.m_guiPath, "\\", "/");
		
		this.setDefaultValue("EK_PATH", EK_PATH );
		this.setDefaultValue("EK_ENCODING", strCharset=="" ? "utf-8" : getstring("CATALOG.ENCODING.SCREEN","ROOT") );
		this.setDefaultValue("EK_SUBMIT_TARGET", "easygui.php" );
		this.setDefaultValue("port", getstring("CATALOG.PORT","ROOT") );
	},
	
	importMap : function(filename,storageSubPath) 
	{
		var storageMapPath = this.m_storageRootPath~"MAP_" + storageSubPath;
		
		var CONTENT = readfile(this.m_pathMapFiles+filename);
		var rows = stringtoarray(CONTENT,m_storagePath~"FILE","\n");
		
		for(i=0; i < rows ; i++)
		{
			var IT = arraypath(this.m_storagePath~"FILE",i);
			var CONTENT = trimright(getstring("VALUE",IT),"\r");
			CONTENT = trimright(CONTENT,"|");
			var POS;
			
			if( (POS=find(CONTENT,"|"))>0 )
			{
				var KEY=mid(CONTENT,1,POS-1);
				var VAL=right(CONTENT,strlen(CONTENT)-POS);

				if( this.m_easyguiMode )
				{	// easygui aliase
					var strPrefix= this.m_bCdMode ? this.m_ProgDir : "";
					VAL=replace(VAL,"css/",strPrefix+this.m_guiPath+"/css/");
					VAL=replace(VAL,"js/", strPrefix+this.m_guiPath+"/js/");
					VAL=replace(VAL,"gfx/",strPrefix+this.m_guiPath+"/gfx/");
				}
				VAL=replace(VAL,"%c%",KEY);
				
				setstring(storageMapPath~KEY,"ROOT",VAL);
			}
		}
        delete(this.m_storagePath~"FILE","");
	},
	
	importScriptMap : function(filename,storageSubPath) 
	{
		var storageMapPath=this.m_storageRootPath~"MAP_"+storageSubPath;
		
		if ( !EasyKat.isReadable(this.m_pathMapFiles+filename) )
			filename = "components.map.b";
			
		var CONTENT=readfile(this.m_pathMapFiles+filename);
		CONTENT=CONTENT.replace("\r\n","\n");
		
		eval( CONTENT );
		
		if(typeof($components) != 'object')
			return false;
			
		this.addUserComponents($components);

		for( var KEY in $components)
		{
			var VAL = $components[KEY];
			VAL = VAL.replace("%c%",KEY);
			VAL = VAL.replace("(label|text)", "%label%%text%");
			
			setstring(storageMapPath~KEY,"ROOT",VAL);
		}
		
		
		CUSTOM = readfile(this.m_pathCustomMap+'/custom.map')
		CUSTOM = CUSTOM.replace("\r\n","\n");
		
		eval(CUSTOM);
		
		if ( typeof ($custom) == 'object') {
			for( KEY in $custom ) {
				VAL = $custom[KEY];
				VAL = VAL.replace("(label|text)","%label%%text%");
				
				setstring(storageMapPath~KEY,"ROOT",VAL);
			}
		}
		return true;
	},
	
	/**
	 *
	 */
	prepareAliasReplace : function( aliasMethod ) 
	{
		// -pf- Alle möglichen Alias Ersetzungen vorbereiten.
		setalias("ROOT"~this.m_storageRootPath~"REPLACE_TABLE", aliasMethod~"REPLACE_TABLE");
		
		var storageAliasTablePath=this.m_storageRootPath~"REPLACE_TABLE";
		if(getsize(storageAliasTablePath,"ROOT")>0)
			return true;
		
		var progDir=replace(this.m_ProgDir, "\\", "/");
		var n=0;
		var nAlias=getsize("CATALOG.ALIAS","ROOT");
		for(var i=0;i<nAlias;i++)
		{
			var itIN=arraypath("CATALOG.ALIAS",i);
			
			var NAME=getstring(itIN~"NAME","ROOT");
			var PATH=replace(getstring(itIN~"PATH","ROOT"), "\\", "/")+"/";
			
			if(aliasMethod=="RELATIVE")
			{	// Den Alias nicht ersetzen wenn Pfad ausserhalb
				// vom Programmverzeichnis ( z.B. temp Verzeichnis )
				PATH= find(PATH,progDir)>0 ? replace(PATH, progDir, "") : "/"+NAME+"/";
			}
			
			var itOUT=arraypath(storageAliasTablePath,n++);
			setstring(itOUT~"SEARCH","ROOT", "/"+NAME+"/" );
			setstring(itOUT~"REPLACE","ROOT", PATH);
			
			// same pattern with backslash ...
			itOUT=arraypath(storageAliasTablePath,n++);
			setstring(itOUT~"SEARCH","ROOT", "/"+NAME+"\\" );
			setstring(itOUT~"REPLACE","ROOT", PATH);
		}
		
		
		if(this.m_bCdMode)
		{	// Im CD-Modus das Target ändern
			var strPort=getstring("CATALOG.PORT","ROOT");
			
			// easygui target replace
			this.addAlias("action=\"index.php\"", 	"action=\"http://localhost:"+strPort+"/easygui.plso\"");
			this.addAlias("action=\"easygui.php\"", 	"action=\"http://localhost:"+strPort+"/easygui.plso\"");
			// isycat target replace
			this.addAlias("/isycat/isycat.php", 		"http://localhost:"+strPort+"/isycat.plso");
		}
		else
		{	
			this.addAlias("action=\"index.php\"", 	"action=\""+this.m_reqURL+"\"");
			this.addAlias("action=\"easygui.php\"","action=\""+this.m_reqURL+"\"");
			
			this.addAlias("/isycat/isycat.php", 		"index.php");
		}
	},
	
	/**
	 * override function
	 */
	initSpecialComponents : function() 
	{
	
	},
	
	setDefaultValue : function(key, value)
	{
		setstring(this.m_storageRootPath~"MAP_STANDARDS"~key, "ROOT", value);
	},

	getDefaultValue : function(key)
	{
		return getstring(this.m_storageRootPath~"MAP_STANDARDS"~key, "ROOT");
	},
	
	addAlias : function(alias,repl)
	{
		var tabPath=this.m_storageRootPath~"REPLACE_TABLE";
		var pathNewAlias=arraypath(tabPath, getsize(tabPath,"ROOT"));
		setstring(pathNewAlias~"SEARCH", "ROOT", 	alias);
		setstring(pathNewAlias~"REPLACE", "ROOT", 	repl);
	},

	addHandler : function(COMPONENT_TAGNAME,HANDLERFUNCTION)
    {
        setstring(this.m_storageRootPath~"SPECIAL_COMPONENTS"~COMPONENT_TAGNAME,"ROOT",HANDLERFUNCTION);
    },
	
	handleEdit : function()
	{
		if(ATTR=="multiline" && VALUE=="true")
		{
			COMPONENT=replace(COMPONENT,"<input","<textarea");
			COMPONENT=replace(COMPONENT,"/>","></textarea>");
			COMPONENT=replace(COMPONENT,"value=","text=");
			COMPONENT=replace(COMPONENT,"styles:!height","styles");
		}
	},
	
	handleButton : function()
	{
		if ( ATTR=="type" && VALUE != "button" ) {
			
			COMPONENT=replace(COMPONENT, 'type="button"', 'type="' + VALUE + '"');
			var comp = COMPONENT;
		}
		/*
		if(ATTR=="top")
		{
			COMPONENT=replace(COMPONENT,'style="', 'style="position: absolute;');
		}
		*/
	},
	

	handleCombobox : function()
	{
		if(ATTR=="top")
		{
			COMPONENT=replace(COMPONENT,'style="', 'style="position: absolute;');
		}
/*
		else if(ATTR=="items")
		{
			OPTIONS="";
			ITEMS=VALUE+"|END";
			
			while(ITEMS!="" && split(ITEMS,ID,ITEMS,"=") && split(ITEMS,TXT,ITEMS,"|") )
			{
				OPTIONS+=<<|<option value="$ID$">$TXT$</option>|;
			}
			
			VALUE="";
			COMPONENT=replace(COMPONENT,"<option>&nbsp;</option>",OPTIONS);
		}
		else if(ATTR=="selected")
		{
			COMPONENT=replace(COMPONENT,<<|<option value="$VALUE$">|,<<|<option value="$VALUE$" SELECTED>|);
		}
*/
	},
	


	handleImage : function()
	{
		if(ATTR=="top")
		{
			COMPONENT=replace(COMPONENT,'style="', 'style="position: absolute;');
		}
	},
	
	
	handleText : function()
	{
		if(ATTR=="top")
		{
			COMPONENT=replace(COMPONENT,'style="', 'style="position: absolute;');
		}
	},


	labelLeft : function (COMPONENT)
	{
		
		return <<ENDHTML
		<table cellspacing="0" cellpadding="0" border="0" style="%styles%">
			<tr style="">
				<td>
					<table cellspacing="0" cellpadding="" border="0">
						<tr >
							<td class="%labelstyle%">
								<label id="%id%_LABEL" for="%id%"  accesskey="%accesskey%" style="white-space:nowrap;">%text%</label>
							</td>
							<td>
								$COMPONENT$
							</td>
						</tr>
					</table>
				</td>
			</tr>
		</table>
		ENDHTML;
	},

	labelRight : function(COMPONENT)
	{
		var label = <<!<label id="%id%_LABEL" for="%id%" accesskey="%accesskey%" style="white-space:nowrap;">%text%</label>!;
		
		if (EasyKat.isIE) {
			var label = <<!<div style="padding-top: 2px"><label id="%id%_LABEL" for="%id%" accesskey="%accesskey%" style="white-space:nowrap;">%text%</label></div>!;
		}
		
		return <<ENDHTML
		<table cellspacing="0" cellpadding="0" border="0" style="%styles%">
			<tr style="">
				<td>
					<table cellspacing="0" cellpadding="0" border="0">
						<tr >
							<td >
								$COMPONENT$
							</td>
							<td class="%labelstyle%" >
								$label$
							</td>
						</tr>
					</table>
				</td>
			</tr>
		</table>
		ENDHTML;
	},
	

	handleCheckbox : function()
	{
		if(ATTR=="textposition")
		{
			COMPONENT=replace(COMPONENT,"{styles:","{styles:!position;");

			if ( EasyKat.isIE ) {
				COMPONENT=replace(COMPONENT,"{styles:","{styles:!position;");
			} else {
				COMPONENT=replace(COMPONENT,"{styles:","margin: 2pt;{styles:!position;");
			}
			
			if (VALUE=="left")
				COMPONENT=this.labelLeft(COMPONENT);
			else
				COMPONENT=this.labelRight(COMPONENT);
		}
	},
	
	handleRadiobutton : function()
	{
		if(ATTR=="name") {
			if(!checkexist("GROUP", "EASYGUITRANSFORM"~VALUE )) {
				setstring("GROUP", "EASYGUITRANSFORM"~VALUE, "true");
				COMPONENT=replace(COMPONENT, "<input", "<span id=\"" + VALUE + "_GROUP\" selected=\"" + eval(VALUE) + "\"></span><input");
			}
		
			if ( EasyKat.isIE ) {
				COMPONENT=replace(COMPONENT,"{styles:","{styles:!position;");
			} else {
				COMPONENT=replace(COMPONENT,"{styles:","margin: 2pt;{styles:!position;");
			}
			
			if (VALUE=="left")
				COMPONENT=this.labelLeft(COMPONENT);
			else
				COMPONENT=this.labelRight(COMPONENT);
		}
	},
	
	
	handleIFrame : function()
	{
		if(ATTR=="top")
		{
			COMPONENT=replace(COMPONENT,'style="', 'style="position: absolute;');
		}
	},
	
	handleTable : function()
	{
		if (ATTR=="fixedlinescount")
		{
			ATTR = "fixedlines";
		}
	},
	
	handleStylesheet : function()
	{
		var stylesheets = this.getDefaultValue("STYLESHEETS");
		stylesheets += "\r\n" + COMPONENT;
		
		this.setDefaultvalue("STYLESHEETS", stylesheets);
	},
	

	initSpecialComponents : function() {
		// Handler für Spezialkomponenten anmelden:
		// addHandler(COMPONENT_TAGNAME,HANDLERFUNCTION);
		//
		// COMPONENT_TAGNAME: Name der Komponente wie ind easygui/map/components.map
		// HANDLERFUNCTION: Funktionsname einer Memberfunktion ohne Parameter (als String!!!)
		// Wird COMPONENT_TAGNAME gefunden wird bei jedem Attribut HANDLERFUNCTION 
		// aufgerufen. Dabei werden diese Variablen gesetzt und wieder übernommen:
		// ATTR (Attributname), VALUE (Attributwert), COMPONENT (gesamte Komponente)
		
		// Submitfunktion ersetzen ohne in Gaetan's Scripten rumzupfuschen
		if(this.m_easyguiMode && getstring("CATALOG.NAME","ROOT")=="Danfoss Motion Controls")
		{
			// addAlias(alias,repl); // alias wird durch repl ersetzt
			this.addAlias("ekSubmit(","mySubmit("); // keine Limits also Vorsicht!!
		}
		
		// In "easygui/map/components.map" gibt es viele %name% Variablen die normalerweise
		// durch die entsprechenden Attribute ersetzt werden. Sind diese Attribute nicht
		// vorhanden so wird der Default verwendet oder %name% gelöscht.
		// setDefaultValue(key, value);
		// setDefaultValue("width", "100"); // Im Zweifel 100 Pixel breit

		// Hawe easyguixp
		//addAlias("<", "\n<");
		/*
		addHandler("edit","handleEdit");
		addHandler("password","handleEdit");
		addHandler("textarea","handleEdit");
		
		addHandler("combobox","handleCombobox");
		addHandler("listbox","handleCombobox");
		addHandler("image","handleImage");
		addHandler("text","handleText");
		addHandler("iframe", "handleIFrame");
		*/
		this.addHandler("edit","handleEdit");
		this.addHandler("checkbox","handleCheckbox");
		this.addHandler("radiobutton","handleRadiobutton");
		//this.addHandler("tablecolumn","handleTableColumn");
		this.addHandler("table", "handleTable");
		this.addHandler("button","handleButton");
		this.addHandler("stylesheet","handleStylesheet");
		
		//this.addHandler("tabctrl","handleTabCtrl");
		//this.addHandler("text","handleText");
		//this.addHandler("dialog","handleDialog");
		
	},
	
	handleTabCtrl: function() {
		COMPONENT = COMPONENT.replace(/#([^#]+)#/, "#$1," + ATTR + ":'" + VALUE + "'#");
	},
	
	handleText: function() {
		COMPONENT = COMPONENT.replace(/#([^#]+)#/, "#$1," + ATTR + ":'" + VALUE + "'#");
	},
	
	addUserComponents : function(components) {
		
	}
});