/**
  * Cascade Layout
  * @todo encapsulate functionality in different classes.
  * by Gaetan Lauff
  * http://www.plansoft.de
  */

// reference local blank image
Ext.BLANK_IMAGE_URL = 'catalog/client/base/extjs/resources/images/default/s.gif';

// create namespace
Ext.namespace('Cascade');
Ext.namespace('Cascade.form');
Ext.namespace('Cascade.panel');

// create application
Cascade.app = function() {
    // private variables
	var viewport;
	// currently visible idx
	var idx = 0;
	var wndSystemmasse;
	var bHeartbeatActiv = false;
	var strSessionId    = '';
	
	// 2 Optionen-Dialoge
	var wndCADOptions;
	var form;
	var lb_2D;

	var centerPanel;
	var descriptionView;
	var topologyView;
	var rohrrichtungView;
	var historyTree;


    // private functions
	var updateDescription = function( id ) {
		// Reload Description Data
		descriptionView.store.reload({
			params: {
				dlg : id
			}
		});
	};

	var updateTopology = function( id , was ) {
		// Reload Topology Data
		topologyView.store.reload({
			params: {
				dlg : id,
				teil : was
			}
		});
	};

	// Das geht bestimmt auch besser :-)
	var updateToolbar = function( id ) {
		var nextBut = Ext.getCmp('move-next');
		var prevBut = Ext.getCmp('move-prev');
		var saveBut = Ext.getCmp('save');

        var sysmBut  = Ext.getCmp('IDC_SYSTEMMASSE');
        var drehButOL = Ext.getCmp('IDC_DREHEN_OL');
        var drehButOR = Ext.getCmp('IDC_DREHEN_OR');
        var drehButU  = Ext.getCmp('IDC_DREHEN_U');
        var cad2But   = Ext.getCmp('IDC_2DCAD');
        var cad3But   = Ext.getCmp('IDC_3DCAD');
        // var printBut  = Ext.getCmp('IDC_PRINT');
        // var copyBut   = Ext.getCmp('IDC_COPY');

		/*
		Ext.getCmp('east-panel').getTopToolbar().items.each( function( item ) {
			// Identify the Spacer
            // -mw- spacer jetzt schon nach dem ersten ;-)))
			if ( typeof item.td != "undefined" ) return false;
			(id == "uebersicht_lastkette") ? item.enable() : item.disable();
		});
        */

		// Perhaps there's a better solution but this one works for the Moment.
		// this.el.child('button:first').dom.style.backgroundImage = 'url(/images/icon.gif)';
		if (id == "uebersicht_lastkette") {
			nextBut.disable();
			saveBut.enable();
			saveBut.show();
            sysmBut.enable();
            drehButOL.enable();
            drehButOR.enable();
            drehButU.enable();
            cad2But.enable();
            $*.WEBVERSION_COMMENT$  cad3But.enable();		// WEBVERSION_COMMENT = // im Webmode, leer sonst ....
            // printBut.enable();
            // copyBut.enable();  erstmal nicht, geht noch nicht
		} else {
			nextBut.enable();
			saveBut.disable();
			// -Schu- 20181004
			saveBut.hide()
            sysmBut.disable();
            drehButOL.disable();
            drehButOR.disable();
            drehButU.disable();
            cad2But.disable();
            cad3But.disable();
            // printBut.disable();
            // copyBut.disable();
		}

		( (id == "systemcharakteristik") || (id == "systemcharakteristik2") ) ? prevBut.disable() : prevBut.enable();
		
		_setButton(id)
	};
	
	var _setButton = function(id){
		switch(id){			
			case 'lager.systemcharakteristik' 		:
					Ext.getCmp('move-prev').hide();					
					if(Ext.getCmp('move-next').hidden)
						Ext.getCmp('move-next').show();
					Cascade.panel.lager.systemcharakteristik.setActivInitial();											
			case 'lager.sollwerte_rohrumschliessendesteil' :
			case 'lager.sollwerte_halterungspunkt' 	:
					if(Ext.getCmp('move-next').hidden)
						Ext.getCmp('move-next').show();
				break;	
		}
		
		if(id.substring(0,6)==="lager."){
			var oSaveButton = Ext.getCmp('save');
			if(id == 'uebersicht_lastkette' && oSaveButton.hidden)		
				oSaveButton.show();
			else	
				oSaveButton.hide();
		}
	}
	
	/**
	 * Convenience Function to update the whole Viewport
	 *
	 * @param string id	The active panel id
	 * @access private
	 */
	var updateViewport = function( id ) {
		updateDescription( id );
		updateTopology( id );
		updateToolbar( id );

		//var nHeight = 350;
		var nHeight = 320;
		var nWidth  = 300;
		if( id == 'lager.auswahl_standard' || id == 'lager.auswahl_rollenlager' || id == 'lager.auswahl_sattel' ||
			id == 'lager.auswahl_rollenlager_direkt'){
			nHeight = 220;			
			nWidth  = 270;
		}
		else if ( id == 'lager_auswahl' ){ // kann später entfallen
			nHeight = 240;
		}
		else if ( id == 'klemmsystem_auswahl')
			nHeight = 270;
		//else if ( id == 'sollwerte_rohrumschliessendes_teil' )
		//	nHeight = 310;
		var panel = Ext.getCmp( 'east-panel' );
		panel.setHeight( nHeight );
		var wpanel = Ext.getCmp( 'west-panel' );
		wpanel.setWidth(nWidth);
		
		_setButton(id);
		
		viewport.doLayout( true );
	};

	// NAVIGATION PART
	// @@@ todo Encapsulate this in a distinct Handler

	var addEntryToHistory = function( entry ) {
		var rootNode = historyTree.root;

		rootNode.appendChild(
			new Ext.tree.TreeNode( {
				text: 		entry.title,
				panelId: 	entry.id,
				cls:		'album-node',
				allowDrag:	false
			} )
		);

		rootNode.lastChild.select();
		return rootNode.lastChild;
	};

	/**
	 * Removes the last entry from history
	 */
	var removeEntryFromHistory = function() {
		var rootNode = historyTree.root;
		rootNode.removeChild( rootNode.lastChild );
		
		if(rootNode.lastChild)
			rootNode.lastChild.select();		
		return rootNode.lastChild;
	};

	/**
	 * Navigation Handler.
	 *
	 * @param string dir	Direction (1=forward,-1=backward)
	 * @access	public
	 */
	var moveToPreviousPanel = function() {
		if ( openTransactions.getCount() > 0 ) {
			return;
		}
		
		var node = removeEntryFromHistory();
		_setButton(node.attributes.panelId);
		setPanelByNode(node);
	};

	var moveToNextPanel = function() {
		if ( openTransactions.getCount() > 0 ) {
			return;
		}
		var formPanel = centerPanel.layout.activeItem;
		formPanel.getForm().submit({url: formPanel.id + "/set-values"});
	};

	/**
	 * TreeClick Handler
	 * Also a kind of Navigation
	 *
	 */
	var onTreeClick = function(node, evt) {
		var root = node.getOwnerTree().root;

		while( root.lastChild.id != node.id ) {
			root.removeChild( root.lastChild );
		}

		setPanelByNode( node );
	};

	var setPanelByNode = function(node) {
		if(node){
			if(node.attributes.panelId.substring(0,6)==="lager."){
				var strNewLagerId = node.attributes.panelId.replace("lager.","");
				Cascade.panel.lager[strNewLagerId].init(centerPanel.items.indexOfKey( node.attributes.panelId ));
				centerPanel.layout.setActiveItem( centerPanel.items.indexOfKey( node.attributes.panelId ) );
				_setButton(node.attributes.panelId);						
			}
			else if(node){
				centerPanel.layout.setActiveItem( centerPanel.items.indexOfKey( node.attributes.panelId ) );
				updateViewport( centerPanel.layout.activeItem.id );
			}
		}
	}

	/**
	 * Cascade.app::getNextPanel calls this Handler
	 * to activate the next panel and fill the History
	 *
	 * @param	object	response
	 * @param	object	options
	 * @access	private
	 */
	var setNextPanel = function(response, options)
	{
		var np = Ext.decode( response.responseText );

		// If the panel doesn't exists create a DataView
		// with images.
		if(np){
			var bIsLager = false;
			var strNewLagerId;
			if(np.id.substring(0,6)==="lager."){
				bIsLager = true;
				Ext.getCmp('save').hide();
				strNewLagerId = np.id.replace("lager.","");
				if (!typeof Cascade.panel.lager[strNewLagerId]) {
					Ext.MessageBox.show({
				       title	: 'Error',
				       msg		: 'Dialog Panel not found ! Name: '+np.id,
				       maxWidth : 800,
				       minWidth : 400,
				       buttons	: Ext.MessageBox.OK,
				       icon	: 'ext-mb-error'
				    });
				}
			}
			else if ( typeof Cascade.panel[np.id] == "undefined" ) {
								
				createNewPanel( np );
			}
	
			var panel 		= Ext.getCmp('center-panel');
			var layout 		= panel.layout;
			var formPanel 	= layout.activeItem;			
			var idx 		= panel.items.indexOfKey( formPanel.id );			
			var nextIdx 	= panel.items.indexOfKey(  np.id  );			
			
			idx = ( nextIdx == -1 ) ? ((idx*1)+1) : nextIdx;
						
			if(!bIsLager)
				Cascade.panel[np.id].init(idx);
			else
				Cascade.panel.lager[strNewLagerId].init(idx);
					
			centerPanel.layout.setActiveItem( idx );
			
			addEntryToHistory( { id:  np.id , idx: idx, title: centerPanel.layout.activeItem.title } );	
			updateViewport(  np.id );
		}
	};

	var onSystemmasseClick = function() {
        Cascade.panel.uebersicht_lastkette.mySubmitForm();
		if( !wndSystemmasse )
		{
            wndSystemmasse = new Ext.Window({
				id: 'systemmasse-window',
                layout:'fit',
                width:500,
                height:300,
                closeAction: 'hide',
                plain: true,
                title: '$SYSTEMMASSE$',
				modal: true,

				plugins: [{
					init: function(cp) {
						cp.on('beforeshow', this.onBeforeShow, cp);
					},

					onBeforeShow: function(evt) {
						// Request form fields from server
						Ext.Ajax.request(
						{ 	url: 'systemmasse/get-form-fields',
							success: function(response, options) {
								// Destroy old items
								if ( this.form ) {
									this.form.items.each( function(item) {
										this.form.remove(item);
									}, this );
								}

								// Create new form
								if ( !this.form ) {
									this.form = this.add( {
										url: 'systemmasse/save',
										bodyStyle:'padding:5px 5px 5px 5px',
										xtype: 'form',
										labelWidth: 120,
										defaultType: 'numberfield',
										// Update the last panel with new information
										listeners: {
											'actioncomplete': function(form, action) {
                                                if (action.result.message && (action.result.message != ""))
                                                    alert(action.result.message);
                                                // alert('Daten wurden uebertragen!');
												//Cascade.panel.uebersicht_lastkette.init();
												var grid = Cascade.panel.uebersicht_lastkette.getGrid();
												grid.getStore().load();
                                                updateDescription( 'uebersicht_lastkette' );
                                                updateTopology( 'uebersicht_lastkette' );
											}
										}
									});
								}

								// Add fields to form.
								var fields = Ext.util.JSON.decode(response.responseText);

								for( var i=0; i < fields.length; i++ ) {
									var field = this.form.add( fields[i] );
									field.on('blur', function(fld) {
										var btn = Ext.getCmp('systemmasse-uebernehmen');

										if ( this.form.getForm().isValid() ) {
											btn.enable();
										} else {
											btn.disable();
										}

									}, this );
								}

								this.doLayout();
							},
							scope: this
						} );
					}
				}],

                buttons: [{
					// @todo only activate when form is validated.
					id: 'systemmasse-uebernehmen',
					// disabled: true,
                    text:'$UEBERNEHMEN$',
                    handler: function() {
						wndSystemmasse.form.getForm().submit();

						wndSystemmasse.hide();
					}
                },{
                    text: '$ABBRECHEN$',
                    handler: function(){
                        wndSystemmasse.hide();
                    }
                }]
            });
        }

        wndSystemmasse.show(this);
	};

    var updateTopologyUebersichtLastkette = function(was) {
        updateTopology('uebersicht_lastkette', was);
    };

	var onDrehenClick = function(was) {
		Ext.Ajax.request({ url: 'uebersicht_lastkette/dreh_dich',
                           params : { drehteil : was },
                           success: updateTopologyUebersichtLastkette(was)
        } );
	};

	var onDrehenOLClick = function() {
		onDrehenClick("OL");
	};

	var onDrehenORClick = function() {
		onDrehenClick("OR");
	};

	var onDrehenUClick = function() {
		onDrehenClick("U");
	};

	var on2DCadClick = function() {
		Cascade.panel.uebersicht_lastkette.mySubmitForm(); // damit ungesicherte Änderungen in der Tabelle übertragen werden
		askCadOptions('2d');
	};

	var on3DCadClick = function() {
		Cascade.panel.uebersicht_lastkette.mySubmitForm(); // damit ungesicherte Änderungen in der Tabelle übertragen werden
		askCadOptions('3d');
	};

	var askCadOptions = function(modus){
		// 2D oder 3D Optionen ?
		lb_2D = ( modus == '2d' );

		if( ! wndCADOptions )
		{
            wndCADOptions = new Ext.Window(
			{
				id: 'CADOptions-window',
				modal: true,
				width: 350,
                title: '',
                buttonAlign: 'right',
                closeAction: 'hide',

				items:
				[
                    form = new Ext.FormPanel(
                    {
                        id: 'CADOptions-formpanel',
						layout: 'form',
						url: 'three_d_cad_options/set-values',
						baseParams: { __STORE_PATH__ : 'DLGDATA.CA.FORMS.THREEDCADOPTIONS' },
						frame: true,
						autoScroll: true,
						layoutConfig: {
							labelSeparator: ''
						},

						// load default values from server
						//this.form.getForm().load({ url: 'three-d-cad-options/get-defaults' });
						// calculate new layout
						//this.doLayout();
						items:
						[/*{
							xtype: 'combo',
							id:  'KP_OUTQUAL',
							hiddenName:  'IDC_OUTQUAL',
							labelWidth: 170,
							listWidth: 200,
							width: 200,
							labelSeparator: '',
							fieldLabel: '$QUALSTUFE$',
							store: new Ext.data.SimpleStore({
								fields: ['value', 'text'],
								data : [
									$*.WEBVERSION_COMMENT$ [ 'HOCH', '$CAD_HIGH_QUAL$' ],
									[ 'SCHNELL', '$CAD_QUICK_GEN$' ]
								]
							}),
							displayField:'text',
							valueField:'value',
							typeAhead: true,
							mode: 'local',
							triggerAction: 'all',
							selectOnFocus: true,
							editable: false
						},*/{
							xtype: 'combo',
							id:  'KP_OUTFMT',
							hiddenName:  'IDC_OUTFMT',
							labelWidth: 170,
							listWidth: 50,
							width: 50,
							labelSeparator: '',
							fieldLabel: '$Format$',
							store: new Ext.data.SimpleStore({
								fields: ['value', 'text'],
								data : [
									[ 'DXF', 'DXF' ],
									[ 'PDF', 'PDF' ]
								]
							}),
							displayField:'text',
							valueField:'value',
							typeAhead: true,
							mode: 'local',
							triggerAction: 'all',
							selectOnFocus: true,
							editable: false
						},/*{
							xtype: 'combo',
							id:  'KP_DETAILS',
							hiddenName:  'IDC_DETAILS',
							labelWidth: 170,
							listWidth: 50,
							width: 50,
							labelSeparator: '',
							fieldLabel: '$DETAILSTUFE$',
							store: new Ext.data.SimpleStore({
								fields: ['value', 'text'],
								data : [
									[ 'EINS', '1' ],
									[ 'ZWEI', '2' ],
									[ 'DREI', '3' ]
								]
							}),
							displayField:'text',
							valueField:'value',
							typeAhead: true,
							mode: 'local',
							triggerAction: 'all',
							selectOnFocus: true,
							editable: false
						},*/{
							xtype: 'checkbox',
							id: 'IDC_STANGEN_GEKUERZT',
							inputValue: 'true',
							hideLabels: true,
							boxLabel:'$STANGEN_GEKUERZT$'
						},{
							xtype: 'checkbox',
							id:'IDC_ROHR',
							inputValue: 'true',
							hideLabels: true,
							boxLabel:'$IDC_ROHR_LABEL$'
						},{
							xtype: 'checkbox',
							id:'IDC_DAEMMUNG',
							inputValue: 'true',
							hideLabels: true,
							boxLabel:'$IDC_DAEMMUNG_LABEL$'
						},{
							xtype: 'checkbox',
							id:'IDC_TRAEGER',
							inputValue: 'true',
							hideLabels: true,
							boxLabel:'$IDC_TRAEGER_LABEL$'
						},{
							xtype: 'checkbox',
							id:'IDC_BEMASSUNG',
							inputValue: 'true',
							hideLabels: true,
							boxLabel:'$BEMASSUNG$'
						},{
							xtype: 'checkbox',
							id:'IDC_POSNR',
							inputValue: 'true',
							hideLabels: true,
							boxLabel:'$POSNR$'
						}]
					})
				],

				buttons:
				[{
					id: 'CADOptions-uebernehmen',
					disabled: false,
					text:'$CAD$',
					handler: function() {
                        if (lb_2D) {
                            // wndCADOptions.form.getForm().submit(
                            Ext.getCmp('CADOptions-formpanel').getForm().submit(
                            {
                                url: 'three_d_cad_options/cad_two_d',
                                success: function(response, options) {
                                    /* Generierung wird blocking gestartet ....
                                    */
                                    var retobj = Ext.util.JSON.decode( options.response.responseText );
									if (( typeof retobj.errMsg != "undefined" ) && (retobj.errMsg != ""))
									{
										wndCADOptions.hide();
										Ext.MessageBox.alert('Message', retobj.errMsg);
										// Wenn Fehler auftrat wird Anwender evtl. auf anderes Panel zurückgesetzt:
										if (retobj && retobj.strGoBackPanel && (retobj.strGoBackPanel != ""))
										{
											// History-Tree updaten
											var node = removeEntryFromHistory();
											while (node && (node.attributes.panelId != retobj.strGoBackPanel)) {
												node = removeEntryFromHistory();
											}
											// Panel umsetzen
											centerPanel.layout.setActiveItem( centerPanel.items.indexOfKey( retobj.strGoBackPanel ) );
											updateViewport( centerPanel.layout.activeItem.id );		
										}
									}
									else
									{
										if (( typeof retobj.url != "undefined" ) && (retobj.url != "") && 
											( typeof retobj.mode != "undefined" ) && (retobj.mode == "online"))
										{
											// im Web versuchen, die Datei zu oeffnen
											self.open(retobj.url, 'Flexperte', '');		// im 2ten Parameter (Window-Title) keine Umlaute benutzen!
										}
										if (( typeof retobj.url != "undefined" ) && (retobj.url != ""))
											EasyKat.util.downloadMessage(retobj);
									}
                                }
                            });
                            var f = Ext.getCmp('CADOptions-formpanel').getForm();
                            //if (f.findField('KP_OUTQUAL').getValue() == 'HOCH')
                            //    Ext.MessageBox.alert('Message', '$IDS_MSG_CAD_HIGH_QUALITY$');
                        }
                        else {
                            // wndCADOptions.form.getForm().submit(
                            Ext.getCmp('CADOptions-formpanel').getForm().submit(
                            {
                                url: 'three_d_cad_options/cad_three_d',
                                success: function(response, options) {
                                    // wndCADOptions.hide();
                                    var retobj = Ext.util.JSON.decode( options.response.responseText );
									if (( typeof retobj.errMsg != "undefined" ) && (retobj.errMsg != ""))
									{
										wndCADOptions.hide();
										Ext.MessageBox.alert('Message', retobj.errMsg);

										// Wenn Fehler auftrat wird Anwender evtl. auf anderes Panel zurückgesetzt:
										if (retobj && retobj.strGoBackPanel && (retobj.strGoBackPanel != ""))
										{
											// History-Tree updaten
											var node = removeEntryFromHistory();
											while (node && (node.attributes.panelId != retobj.strGoBackPanel)) {
												node = removeEntryFromHistory();
											}
											// Panel umsetzen
											centerPanel.layout.setActiveItem( centerPanel.items.indexOfKey( retobj.strGoBackPanel ) );
											updateViewport( centerPanel.layout.activeItem.id );		
										}
									}
                                }
                            });
                        }
                        // Das hide können wir immer machen, nicht nur im Success-Fall
                        wndCADOptions.hide();
						
					}
				},
				{
					text: '$ABBRECHEN$',
					handler: function(){
						wndCADOptions.hide();
					}
				}]
			})
		}
		// default Werte
		form.load({ url: 'three-d-cad-options/get-defaults' });

		// display dialog
		wndCADOptions.show();

		// dialog anpassen
		var f = Ext.getCmp('CADOptions-formpanel').getForm();
		if( lb_2D ) 
		{			
			wndCADOptions.setTitle('$2DCAD$');
			//Ext.getCmp('KP_OUTQUAL').show();
			Ext.getCmp('KP_OUTFMT').show();
			Ext.getCmp('IDC_BEMASSUNG').show();
			Ext.getCmp('IDC_POSNR').show();
			
			Ext.getCmp('IDC_TRAEGER').disable();
			
			//f.findField('KP_OUTQUAL').setLabel('$QUALSTUFE$');
			f.findField('KP_OUTFMT').setLabel('$Format$');
			f.findField('IDC_BEMASSUNG').showBoxLabel('$BEMASSUNG$');
			f.findField('IDC_POSNR').showBoxLabel('$POSNR$');
		}
		else 
		{
			wndCADOptions.setTitle('$3DCAD$');
			
			Ext.getCmp('IDC_TRAEGER').enable();
			
			//f.findField('KP_OUTQUAL').setLabel('');
			f.findField('KP_OUTFMT').setLabel('');
			f.findField('IDC_BEMASSUNG').hideBoxLabel('');
			f.findField('IDC_POSNR').hideBoxLabel('');
			
			//Ext.getCmp('KP_OUTQUAL').hide();
			Ext.getCmp('KP_OUTFMT').hide();
			Ext.getCmp('IDC_BEMASSUNG').hide();
			Ext.getCmp('IDC_POSNR').hide();
		}

	};

	var onPrintClick = function() {
	
		Cascade.panel.uebersicht_lastkette.mySubmitForm(); // damit ungesicherte Änderungen in der Tabelle übertragen werden
	
		Ext.Ajax.request({ url: 'three_d_cad_options/cad_preview',
                                success: function(response, options) {
                                    /* Generierung wird blocking gestartet ....
                                    */
                                    var retobj = Ext.util.JSON.decode( response.responseText );
                                    if (( typeof retobj.url != "undefined" ) && (retobj.url != "") && 
										( typeof retobj.mode != "undefined" ) && (retobj.mode == "online"))
									{
										// im Web versuchen, die Datei zu oeffnen
                                        self.open(retobj.url, 'Flexperte', '');		// im 2ten Parameter (Window-Title) keine Umlaute benutzen!
                                    }
                                    EasyKat.util.downloadMessage(retobj);
                                } } );
	};

	var onCopyClick = function() {
		alert( "noch nicht implementiert" );
	};

	var onCancelSelectionClick = function() {
		document.forms.cascade.EKSUBMITEVENT.value = 'IDC_CASCADE_ABORT';
		document.forms.cascade.submit();
	};

	var onSaveClick = function() {
		var rootNode = historyTree.root;
		var history = [];

		Cascade.panel.uebersicht_lastkette.mySubmitForm(); // damit ungesicherte Änderungen in der Tabelle übertragen werden

		for ( var i=0, len = rootNode.childNodes.length; i < len; ++i ) {
			var node = rootNode.childNodes[i];
			history.push( {
				id: node.attributes.panelId,
				title: encodeURIComponent(node.attributes.text)
			} )
		}

		history = Ext.util.JSON.encode( history );
        var values = Ext.getCmp('uebersicht_lastkette').getForm().getValues();
		values = Ext.util.JSON.encode(values);

		// Hier serialisieren wir einfach die Childnodes vom History Tree
		Ext.Ajax.request({
			url: 'index/complete-selection',
			params : {
				history: history,
                values: values
			},
			success: proceedToBasket
		});

	};

	var proceedToBasket = function(response, options) {
        // Schlusspruefung,  ob er darf ...
		var respObj = Ext.decode( response.responseText );
        if (respObj && respObj.strErrorMessage && (respObj.strErrorMessage != ""))
        {
            Ext.MessageBox.alert('Message', respObj.strErrorMessage);
        }
        else if (respObj && respObj.strWarningMessage && (respObj.strWarningMessage != ""))
        {
       		var ret = window.confirm(respObj.strWarningMessage);
            if (ret)
            {
                document.forms.cascade.EKSUBMITEVENT.value = 'IDC_BASKET';
                document.forms.cascade.submit();
            }
        }
        else
        {
            document.forms.cascade.EKSUBMITEVENT.value = 'IDC_BASKET';
            document.forms.cascade.submit();
        }
		// Wenn Fehler auftrat wird Anwender evtl. auf anderes Panel zurückgesetzt:
        if (respObj && respObj.strGoBackPanel && (respObj.strGoBackPanel != ""))
		{
			// History-Tree updaten
			var node = removeEntryFromHistory();
			while (node && (node.attributes.panelId != respObj.strGoBackPanel)) {
				//alert (node.id + " - " + respObj.strGoBackPanel);
				node = removeEntryFromHistory();
			}
			// Panel umsetzen
			centerPanel.layout.setActiveItem( centerPanel.items.indexOfKey( respObj.strGoBackPanel ) );
			updateViewport( centerPanel.layout.activeItem.id );		
		}
		
	};

	/**
	 * Creates a new panel
	 * @params  object np  contains id and title of new panel
	 *
	 */
	var createNewPanel = function(np) {
		Cascade.panel[np.id] = function() {
			var form;
			var store;
			var dataView;

			return {
				init: function(idx) {
					if ( !form ) {
						store = new Ext.data.JsonStore({
							url: np.id + '/get-images',
							root: 'images',
							fields: [
								'id', 'src', 'shortName', 'qtip'
							],
							listeners: {
								'load': this.defaultSelect
							}
						});

						var tpl = new Ext.XTemplate(
							'<tpl for=".">',
								'<div class="thumb-wrap" id="{id}">',
								'<div class="thumb"><img src="{src}" qtip="{qtip}"></div>',
								'<span>{shortName}</span></div>',
							'</tpl>',
							'<div class="x-clear"></div>'
						);

						dataView = new Ext.DataView({
							xtype: 'dataview',
							store: store,
							tpl: tpl,
							title: np.title,
							autoHeight:true,
							singleSelect: true,
							overClass:'x-view-over',
							itemSelector:'div.thumb-wrap',
							emptyText: 'No images to display',
							listeners: {
								'click': function(view,idx,node,evt) {
									Ext.getCmp('move-next').disable();
									form.getForm().findField('IDC_IMAGE_ID').setValue(node.id);
									moveToNextPanel();
								}
							}
						});

						form = new Ext.FormPanel({
							url: np.id + '/set-values',
							id: np.id,
							cls: 'images-view',
							title: decodeURIComponent(np.title),

							baseParams: {
								__STORE_PATH__: 'DLGDATA.CA.FORMS.' + np.id.toUpperCase()
							},

							listeners: {
								'actioncomplete': Cascade.app.getNextPanel
							},

							items: [{
								xtype: 'hidden',
								name: 'IDC_IMAGE_ID'
							}, dataView ]
						});
					}

					var cp = Ext.getCmp('center-panel');

					cp.insert(idx,form);
					cp.doLayout();

					store.load();
				},

				defaultSelect: function(store, records, options ) {
					if ( !dataView.getSelectionCount() ) {
						dataView.select(0);
					}
                    if (store.reader.jsonData.message && (store.reader.jsonData.message != ""))
                        alert(store.reader.jsonData.message);
					var selectedNodes = dataView.getSelectedNodes();
					if ( selectedNodes.length )
						form.getForm().findField('IDC_IMAGE_ID').setValue(selectedNodes[0].id);
				}
			}
		}();
	};


	var beforeRequest = function( conn, options ) {
		openTransactions.add(options.url);
	};
	
	var requestComplete = function(conn, response, options) {
		openTransactions.remove(options.url);
	};
	
	var requestException = function(conn, response, options ) {
		openTransactions.remove(options.url);
	};
	
	var openTransactions = new Ext.util.MixedCollection();

	
    // public space
    return {
    	/**
    	 *  Aktivierungsfunktion für Heartbeat
    	 */
    	activateHeartbeat: function(strSession){
    		if(!bHeartbeatActiv){
	    		strSessionId 	= strSession;
				var myTimer 	= setInterval("Cascade.app.activeHeartbeat()", 200000);
    		}
    	},
    	/**
		 * @deprecated Update ViewPort 
		 * @param [strDialogId] {String} Dialog FormID
		 */
    	setUpdateViewport : function(strDialogId){
    		updateViewport(strDialogId);
    	},
    	/**
		 * @deprecated Heart beat - damit die Session aufrecht erhalten bleibt -
		 * @version 18. Nov. 2011 ist notwendig geworden, nachdem wir Variablen an das SessionObject hängen
		 */
		activeHeartbeat : function(){ 
			bHeartbeatActiv = true;
			var oDate = new Date();
			var ms	  = oDate.getMilliseconds() * 1000;
			var requestId = strSessionId +  Math.round(Math.random()*ms+1 ) ;
			Ext.Ajax.request( 
		    { 
		        url		: 'index/Heartbeat',
				params  : {
					'requestId_' : requestId
				},
				success: function(response, options){
					var retObj = Ext.util.JSON.decode(response.responseText);
				}
			}); 
		},
		
        // public properties, e.g. strings to translate
		setRemoveEntryFromHistory : function(){
			removeEntryFromHistory();
		},
		setAddEntryToHistory : function(oRet){
			addEntryToHistory(oRet);
		},
        // public methods
        init: function() {
			Ext.QuickTips.init();
			Ext.form.Field.prototype.msgTarget = 'side';

			Ext.Ajax.on('beforerequest', beforeRequest, this);
			Ext.Ajax.on('requestcomplete', requestComplete, this);
			Ext.Ajax.on('requestexception', requestException, this);
			
			window.setInterval( function() {
				var nextBut = Ext.getCmp('move-next');
				var prevBut = Ext.getCmp('move-prev');
				var saveBut = Ext.getCmp('save');
			
				if ( openTransactions.getCount() > 0 ) {
					nextBut.disable();
					prevBut.disable();
					saveBut.disable();
				} else {
					var id = centerPanel.layout.activeItem.id;
						
					if (id !== "systemcharakteristik" && id !== "systemcharakteristik2") {
						prevBut.enable();
					}
					
					if ( id !== "uebersicht_lastkette" ) {
						nextBut.enable();
					}
					
					saveBut.enable();
				}
			}, 500 );
			
			
			viewport = new Ext.Viewport( {
				id: 'viewport',
				layout: 'border',

				items: [{
					layout: 'border',
					region: 'west',
					width: 300,
					minSize: 150,
					maxSize: 400,
					margins: '5 0 5 5',
					collapsible: true,
					split: true,
					id: 'west-panel',
					items: [
						new Ext.tree.TreePanel({
							id:'history-tree',
							title:'$HISTORY$',
							region: 'center',
							height: 250,
							//margins:'5 0 5 5',
							rootVisible:false,
							title: 'History',
							autoScroll: true,
							split: true,
							loader: new Ext.tree.TreeLoader(),

							root: new Ext.tree.AsyncTreeNode({
								expanded: true/*,
								children: [{
									text: 'Systemcharakteristik',
									leaf: true
								}]*/
							}),

							listeners: {
								'click' : {
									fn: onTreeClick,
									scope: this,
									delay: 100
								}
							}
						}),
						new Ext.Panel({
							id:'description-panel',

							//layout:'fit',
							width: 350,
							height: 500,
							region: 'south',
							title:'$DESCRIPTION$',
							autoScroll: true,
							items:
								new Ext.DataView({
									id: 'description-view',
									height: 350,
									// Hier muss noch die Info hin wo wir eigentlich sind
									store: new Ext.data.JsonStore({
										url: 'description/get-description',
										root: 'values',
										fields: ['title', 'rows']//,
										//autoLoad: true
									}),
									tpl: new Ext.XTemplate(
										'<table>',
											'<tpl for=".">',
												'<tr><td colspan="4"><h3>{title}</h3></td></tr>',
												'<tpl for="rows">',
													'<tr>',
														'<td>{0}</td>',
														'<td style="text-align: right">{1}</td>',
														'<td>{2}</td>',
														'<td>{3}</td>',
													'</tr>',
												'</tpl>',
											'</tpl>',
										'</table>'
									),
									autoHeight:true,
									//multiSelect: true,
									//overClass:'x-view-over',
									itemSelector:'div.thumb-wrap',
									emptyText: ''
								})
						})
					]
				},{
					region: 'center',
					id: 'center-main',
					layout: 'border',
					margins: '5 5 5 0',
					//autoScroll: true,
					items: [{
						region: 'center',
						id: 'center-panel',
						layout: 'card',

						//margins: '5 0 5 0',
						activeItem: 0,
						defaults: {
							border: false
						},
						//bodyStyle: 'padding: 5px',
						layoutConfig: {

						}

					},{
						region: 'south',
						id: 'east-panel',
						height: 350,
						minSize: 75,
						// maxSize: 325,
						collapsible: true,
						//margins: '5 5 5 0',

						split: true,
						layout: 'fit',
						tbar: [
							{
								id: 'IDC_SYSTEMMASSE',
								icon: 'catalog/client/custom/img/icons/layout_edit.png',
								cls: 'x-btn-text-icon',
								text: '$SYSTEMMASSE$',
								tooltip: '<b>$SYSTEMMASSE$</b>',
								disabled: true,
								handler: onSystemmasseClick.createDelegate(this)
							},'-',
							{
								id: 'IDC_DREHEN_OL',
								icon: 'catalog/client/custom/img/icons/arrow_rotate_anticlockwise.png',
								cls: 'x-btn-text-icon',
								text: '$DREHEN_LINKS$',
								tooltip: '<b>$DREHEN_LINKS_TOOLTIP$</b>',
								disabled: true,
								handler: onDrehenOLClick.createDelegate(this)
							},
							{
								id: 'IDC_DREHEN_OR',
								icon: 'catalog/client/custom/img/icons/arrow_rotate_anticlockwise.png',
								cls: 'x-btn-text-icon',
								text: '$DREHEN_RECHTS$',
								tooltip: '<b>$DREHEN_RECHTS_TOOLTIP$</b>',
								disabled: true,
								handler: onDrehenORClick.createDelegate(this)
							},
							{
								id: 'IDC_DREHEN_U',
								icon: 'catalog/client/custom/img/icons/arrow_rotate_anticlockwise.png',
								cls: 'x-btn-text-icon',
								text: '$DREHEN_SCHELLE$',
								tooltip: '<b>Drehen Schelle</b>',
								disabled: true,
								hidden: true,
								handler: onDrehenUClick.createDelegate(this)
							},'-',
							{
								id: 'IDC_2DCAD',
								icon: 'catalog/client/custom/img/icons/vector.png',
								text: 'CAD 2D',
								cls: 'x-btn-text-icon',
								tooltip: '<b>$2D_CAD$</b>',
								disabled: true,
								handler: on2DCadClick.createDelegate(this)
							},'-',
							{
								id: 'IDC_3DCAD',
								icon: 'catalog/client/custom/img/icons/vector.png',
								text: 'CAD 3D',
								cls: 'x-btn-text-icon',
								tooltip: '<b>$3D_CAD$</b>',
								disabled: true,
								handler: on3DCadClick.createDelegate(this)
							},/* '-',
							{
								id: 'IDC_PRINT',
								cls: 'x-btn-text-icon',
								text: '$DRUCKEN$',
								icon: 'catalog/client/custom/img/icons/printer.png',
								tooltip: '<b>$DRUCKEN$</b>',
								disabled: true,
								handler: onPrintClick.createDelegate(this)
							}, '-',
							{
								id: 'IDC_COPY',
								icon: 'catalog/client/custom/img/icons/page_copy.png',
								cls: 'x-btn-text-icon',
								text: '$KOPIEREN$',
								tooltip: '<b>$KOPIEREN$</b>',
								disabled: true,
								handler: onCopyClick.createDelegate(this)
							}, */
							'->',
							{
								id: 'cancel-selection',
								icon: 'catalog/client/custom/img/icons/house.png',
								cls: 'x-btn-text-icon',
                                text: '&nbsp;',
								tooltip: '<b>$CANCEL_SELECTION$</b>',
								handler: onCancelSelectionClick.createDelegate(this)
							},'-',
                            {
								id: 'save',
								icon: 'catalog/client/custom/img/icons/cart_add.png',
								cls: 'x-btn-text-icon',
                                text: '&nbsp;',
								tooltip: '<b>$AUSWAHL_UEBERNEHMEN$</b>',
								disabled: true,
								handler: onSaveClick.createDelegate(this)
							},'-',
                            {
								id: 'move-prev',

								icon: 'catalog/client/custom/img/icons/prev.png',
								cls: 'x-btn-text-icon',
                                text: '&nbsp;&nbsp;',
								tooltip: '<b>$BACK$</b>',
								handler: moveToPreviousPanel.createDelegate(this),
								disabled: true
							},
							{
								id: 'move-next',

								icon: 'catalog/client/custom/img/icons/next.png',
								//iconCls: 'forward',
								cls: 'x-btn-text-icon',
                                text: '',
								tooltip: '<b>$FORWARD$</b>',
								handler: moveToNextPanel.createDelegate(this)
							}
						],

						items: [{
                            id: 'sub-center',
                            layout: 'border',

                            items: [
                                new Ext.Panel({
                                    id:'topology-panel',
                                    autoScroll:true,
                                    region: 'center',
                                    width: 300,
                                    split: true,
                                    items: new Ext.DataView({
                                        autoHeight: true,
                                        layout: 'fit',
                                        id: 'topology-view',
                                        store: new Ext.data.JsonStore({
                                            url: 'topology/get-topology-table',
                                            root: 'values',
                                            fields: ['topoTyp','Pictures','PicturesLeft','PicturesMiddle','PicturesRight','PictureBottom','PictureTop'],
                                            autoLoad: false
                                        }),
                                        tpl: new Ext.XTemplate(
                                            '<center><table id="topology-table" class="topology" cellspacing="0" style="border-collapse: collapse">',
                                                '<tpl for=".">',
                                                    '<tpl if="topoTyp == 1">',
                                                        '<tpl for="Pictures">',
                                                            '<tr><td  style="border: 1px solid lightgrey"><img id="{id}" src="{src}" /></td></tr>',
                                                        '</tpl>',
                                                    '</tpl>',
                                                    '<tpl if="topoTyp == 2">',
                                                        '<tr>',
                                                            '<td>',
                                                                '<table>',
                                                                    '<tpl for="PicturesLeft">',
                                                                        '<tr><td  style="border: 1px solid lightgrey"><img id="{id}" src="{src}" /></td></tr>',
                                                                    '</tpl>',
                                                                '</table>',
                                                            '</td>',
                                                            '<td valign="bottom" >',
                                                                '<table>',
                                                                    '<tpl for="PicturesMiddle">',
                                                                        '<tr><td  style="border: 1px solid lightgrey"><img id="{id}" src="{src}" /></td></tr>',
                                                                    '</tpl>',
                                                                '</table>',
                                                            '</td>',
                                                            '<td>',
                                                                '<table>',
                                                                    '<tpl for="PicturesRight">',
                                                                        '<tr><td  style="border: 1px solid lightgrey"><img id="{id}" src="{src}" /></td></tr>',
                                                                    '</tpl>',
                                                                '</table>',
                                                            '</td>',
                                                        '</tr>',
                                                        '<tr><td colspan="3" style="text-align:center"><img src="{PictureBottom}" /></td></tr>',
                                                    '</tpl>',
                                                    '<tpl if="topoTyp == 3">',
                                                        '<tr><td colspan="3" style="text-align:center"><img src="{PictureTop}" /></td></tr>',
                                                        '<tr>',
                                                            '<td>',
                                                                '<table>',
                                                                    '<tpl for="PicturesLeft">',
                                                                        '<tr><td  style="border: 1px solid lightgrey"><img id="{id}" src="{src}" /></td></tr>',
                                                                    '</tpl>',
                                                                '</table>',
                                                            '</td>',
                                                            '<td>',
                                                                '<table>',
                                                                    '<tpl for="PicturesMiddle">',
                                                                        '<tr><td  style="border: 1px solid lightgrey"><img id="{id}" src="{src}" /></td></tr>',
                                                                    '</tpl>',
                                                                '</table>',
                                                            '</td>',
                                                            '<td>',
                                                                '<table>',
                                                                    '<tpl for="PicturesRight">',
                                                                        '<tr><td  style="border: 1px solid lightgrey"><img id="{id}" src="{src}" /></td></tr>',
                                                                    '</tpl>',
                                                                '</table>',
                                                            '</td>',
                                                        '</tr>',
                                                    '</tpl>',
                                                '</tpl>',
                                            '</table></center>'
                                        ),

                                        singleSelect: true,
                                        //overClass:'x-view-over',
                                        itemSelector:'div.thumb-wrap',
                                        emptyText: 'Topology'
                                    })
                                }),
                                new Ext.Panel({
                                    region: 'east',
                                    layout: 'fit',
                                    width: 250,
									id:'rohrrichtung-panel'
                                    /*items: [{
                                        //html: '<center><img src="catalog/client/custom/img/RH_KOORD_mit_Rohr.jpg" /></center>'
										html: '<center><img src="catalog/client/custom/img/WITgifs/RH/blank.png" /></center>'
                                    }]
									*/
                                })
                            ]
                        }]
					}]
				}]
			});
			
			var openMode = '$*.OPEN_MODE_CASCADE$';

			centerPanel 		= Ext.getCmp('center-panel');
			descriptionView	 	= Ext.getCmp('description-view');
			topologyView 		= Ext.getCmp('topology-view');
			rohrrichtungView 	= Ext.getCmp('rohrrichtung-view');
			historyTree			= Ext.getCmp('history-tree');
			
			switch(openMode){
				case "NEW" : // Normal Mode
						Cascade.panel.systemcharakteristik.init(0);
						//Cascade.panel.sollwerte_rohrumschliessendes_teil.init(0);
						centerPanel.layout.setActiveItem( 0 );
		
						addEntryToHistory({
							id: 'systemcharakteristik',
							title: '$SYSTEMCHARAKTERISTIK$'}
						);
					break;
				case "LAGER"	: //KANN ENTFALLEN WENN NEUIMPLEMENTIERUNG FERTIG IST !!!!!!!!!!!		
						/*Cascade.panel.systemcharakteristik2.init( 0 );
						centerPanel.layout.setActiveItem( 0 );
		
						addEntryToHistory({
							id: 'systemcharakteristik2',
							title: '$SYSTEMCHARAKTERISTIK2$'}
						);*/
					break;
				case "LAGER2011" :
						Cascade.panel.lager.systemcharakteristik.init( 0 );
						centerPanel.layout.setActiveItem( 0 );	
						
						Ext.Ajax.request( {
							url 	: 'index/getProductObjectPanel',
							params  : {
								'value' : openMode
							},
							success : function(response, options) {
								var message	= Ext.util.JSON.decode(response.responseText);
								
								addEntryToHistory({
									id		: message.id,
									title	: message.title});
							}
						});						
					break;	
				default :						
						// Get History from Server
						Ext.Ajax.request( {
							url : 'index/get-history',
							success : this.restoreHistory
						});
					break;	
			}			
		},

		// Restore the global history
		restoreHistory : function( response, options ) {
			var bFoundLager2011 = false;
			var history = Ext.util.JSON.decode( response.responseText );			
			for ( var i=0, len = history.length; i < len; ++i ) {
				var node = history[i];				
				node.title = decodeURIComponent(node.title);
				//17. Juli 2012 - hier wird für die Lagerauswahl 2011 das rechte Bild gesetzt, wenn man aus der Lastkette komme
				if(node.id == 'lager.systemcharakteristik')
					bFoundLager2011 = true;
					
				if ( typeof Cascade.panel[node.id] == "undefined" ) {
					createNewPanel(node);
				}

				Cascade.panel[node.id].init( i );
				addEntryToHistory(node);
			}

			centerPanel.layout.setActiveItem(node.id);
			updateViewport( node.id );
			
			//17. Juli 2012
			if(bFoundLager2011)
				Cascade.panel.lager.systemcharakteristik.setPicture();
		},

		// Forms call this Handler onActionComplete
        // Forms haben submit-Action, load-Action etc....
        // 1) Form submitted
        // 2) ActionComplete ... --> getNextPanel() wird aufgerufen
        //    deshalb hier der Test, für welche Action eigentlich unserHandler aufgerufen wurde ...
		getNextPanel : function(form, action)
		{
            // Wenn gerade ein submit erfolgreich durchgeführt wurde ....
            // hier kann man nochmal validieren und den Ajax-Request unterdrücken, mit dem das nächste
            // Panel aufgerufen wird. Aber im Store steht der Mist dann schon ... theoretisch kann dann
            // der Server auch validieren?
			if ( action.type == "submit" ) {
				var valid = true;
                if ( typeof action.result != "undefined")
                {
                    var result = action.result;

                    if ( typeof result.validate != "undefined" ) {
                        // Hier Validierungen durchführen
                        // Vielleicht aber auch mal nach eigen vtypes schauen
                        // Die sind vielleicht besser geeignet
                        if (result.validate.message != '')
                        {
                            valid = false;
                            Ext.MessageBox.alert('Message', result.validate.message);
                        }
                    }
                }
				
				if ( valid ) {
					Ext.Ajax.request({
						url: 'index/get_next_panel',
						params : {
							activepanel: centerPanel.layout.activeItem.id
						},
						//success: Cascade.app.setNextPanel
						success: setNextPanel
					});
				}
			}

            // Wenn gerade ein load erfolgreich durchgeführt wurde ....
            // der richtige Moment, um Felder zu disablen, zu hiden ...

			if ( action.type == "load" ) {
				var result = action.result;

                // hier form resetten oder enabled-Array liefern ...
                // Achtung: da die Panels "ewig" leben müssen oft die Controls die disabled werden
                // auch wieder enabled werden.
                // form.reset();  Mist, da werden die geladenen Werte überschrieben
				if ( typeof result.enabled != "undefined" ) {
                    for ( var i=0, len = result.enabled.length; i < len; ++i) {
                        try{
                        	form.findField( result.enabled[i] ).enable();
                        }
                        catch(err){}
                    }
                }
				if ( typeof result.disabled != "undefined" ) {
                    for ( var i=0, len = result.disabled.length; i < len; ++i) {
                        form.findField( result.disabled[i] ).disable();
                    }
                }
				form.result = result;
			}

		},

		/**
		 * Returns the Viewport component
		 *
		 * @return object
		 */
		getViewport : function()
		{
			return viewport;
		},

		switchPanel : function(id) {
			var panel 		= Ext.getCmp('center-panel');
			var layout 		= panel.layout;
			var formPanel 	= layout.activeItem;

			var idx 		= panel.items.indexOfKey( id );

			layout.setActiveItem( idx );
		},
		setTopologyPicture: function(strFile){
			Ext.getCmp( 'topology-panel' ).body.update( '<center><img src="' + strFile + '" /></center>' );
		}
    };
}(); // end of app

// end of file
