if (brodos == undefined) brodos = {};

Ext.namespace("brodos");

brodos.tbrowser.Window = function (config){

	this.title = '';
	
	this.layout = 'fit';

	this.hideMode = 'offsets';
	
	this.closeAction = 'hide';
	
	this.modal = true;
	
	this.hidden = true;
	
	this.resizable = false;
	
	this.plain = true;
	
	this.height = 'auto';
	
	this.minWidth = 450;
	
	this.width = 450;
	
	this.clearCachesAndSubmit = false;
	
	this.ajax1 = false;
	
	this.ajax2 = false;
	
	this.buttonwasclicked = false;

	brodos.tbrowser.Window.superclass.constructor.call(this, config);
}

Ext.extend( brodos.tbrowser.Window, Ext.Window, 
	/**
	 * @scope brodos.tbrowser.Window
	 */
{
	activeBrowser: null,
	
	initComponent: function(){	
		
		this.doneButton = new brodos.button.Done({
			handler: function(){
                    //this.checkForActiveRequests();
					this.handleButtonEvent();
			},
			scope: this
		});	
	
		Ext.apply(this,{
		
			buttons:[
			 this.doneButton
			]
		
		});
		brodos.tbrowser.Window.superclass.initComponent.apply(this, arguments);	
		
		this.addListener('hide',function(){
				this.remove(this.activeBrowser);
            },
			this
		);	
	},

	startTbrowser: function(tbrowser,title){		
		this.add(tbrowser);
		this.show();
		this.activeBrowser = tbrowser;
		this.setTitle(title);
		this.setWidth(this.activeBrowser.width+ tbwin.getFrameWidth() +4);
		this.center();
		tbrowser.grid.getEl().mask(localization.getStringForKey('TBrowser_LoadMask_Loading'), 'x-mask-loading');
		tbrowser.addListener('tbrowserloaded',function(){
			this.center();
			tbrowser.grid.getEl().unmask();
		},this);
		
		tbrowser.addListener('tbrowsercommited', function(response){
	
		},this);
		
		tbrowser.addListener('tbrowserdeleted', function(response){
			this.clearCachesAndSubmit = true; 
		},this);
		
		tbrowser.grid.addListener('beforeedit', function(e){
			this.checkForDoubleActiveKeys = true;
			this.checkForDoubleInactiveKeys = true;
		},this);
		
		tbrowser.grid.addListener('afteredit', function(e) {
			var col = this.activeBrowser.uniqueColumn;
			if (e.field == col ){
			
				this.checkForDoubleActiveKeys = false;
				this.checkForDoubleInactiveKeys = false;
		
				var f = this.activeBrowser.hardFilters;
				var extendFilters = '';
				
				for (var r = 0 ; r < f.length; r++){
						extendFilters = extendFilters+'<filter operation="'+f[r]['operation']+'" op2="'+f[r]['value']+'" op1="'+f[r]['key']+'"></filter>'
				}
				
				extendFilters = extendFilters+'<filter operation="EQ" op2="'+e.value.toUpperCase()+'" op1="'+col+'"></filter>';
				
				Ext.Ajax.request({
					url: this.activeBrowser.providerUrl,
					params:{
						action: 'getData',
						subject: this.activeBrowser.subject,
						queryXml: '<data-query xmlns="http://brodos.net/schemas/dataStorage/2008/01"><query-definition key="'+this.activeBrowser.queryDefinitionKey+'"><paging limit="1" maxcount="10"></paging><column type="CHAR" name="'+col+'"></column><filter-relation type="AND">'+extendFilters+'</filter-relation></query-definition></data-query>'
					},
					scope: this,
					success: function(response, result){
						var root = response.responseXML;
						var q = Ext.DomQuery;
						var paging = q.selectNode('paging', root);
						var pagingcount = paging.getAttribute("count");
						if (pagingcount > 0){
							if (typeof this.runner != 'undefined'){
								this.runner.stop(this.task);
							}
							Ext.Msg.show({
								title: brodos.translation.get('TBrowser_KeyExistsError'),
								msg: brodos.translation.get('TBrowser_KeyExistsErrorText'),
								buttons: Ext.Msg.OK,
								fn:  function(){
									e.record.set(col, e.originalValue);
									e.grid.getSelectionModel().selectRow(e.row, false);
									e.grid.getView().focusRow(e.row);
									e.grid.startEditing(e.row, e.column);
									e.record.commit();
									this.checkForDoubleActiveKeys = true;
								},
								animEl: 'elId',
								icon: Ext.MessageBox.WARNING
							});
							
						}else{
							this.checkForDoubleActiveKeys = true;
						}		
					}
				});
				
				
				var f2 = this.activeBrowser.hardFilters;
				var extendFilters2 = '';
				var filters2 = [];
				
				for (var r = 0 ; r < f2.length; r++){
					filters2[r] = new Array();
					filters2[r]['key'] = f2[r]['key'];
					filters2[r]['operation'] = f2[r]['operation'];
					if ( f2[r]['key'] == 'ISACTIVE' ) {
						filters2[r]['value'] = '0';
					}
					else {
						filters2[r]['value'] = f2[r]['value'];
					}
				}
				
				
				for (var k = 0 ; k < filters2.length; k++){
					extendFilters2 = extendFilters2+'<filter operation="'+filters2[k]['operation']+'" op2="'+filters2[k]['value']+'" op1="'+filters2[k]['key']+'"></filter>';
				}
				
				extendFilters2 = extendFilters2+'<filter operation="EQ" op2="'+e.value.toUpperCase()+'" op1="'+col+'"></filter>';
				
				
				var cm = this.activeBrowser.grid.getColumnModel()
				var columns = '';
				
				for ( o = 0 ; o < cm.config.length; o++ ){
					if (cm.config[o].id == 'checker'){
						o++;
					}
					columns += '<column name="'+cm.config[o].dataIndex+'"></column>'
				}				
				
				Ext.Ajax.request({
					url: this.activeBrowser.providerUrl,
					scope: this,
					params:{
						action: 'getData',
						subject: this.activeBrowser.subject,
						queryXml: '<data-query xmlns="http://brodos.net/schemas/dataStorage/2008/01"><query-definition key="'+this.activeBrowser.queryDefinitionKey+'"><paging limit="1" maxcount="10"></paging>'+columns+'<filter-relation type="AND">'+extendFilters2+'</filter-relation></query-definition></data-query>'
					},
					success: function(response, result){
						var root = response.responseXML;
						var q = Ext.DomQuery;
						var paging = q.selectNode('paging', root);
						var pagingcount = paging.getAttribute("count");
						
						if (pagingcount > 0){
							if (typeof this.runner != 'undefined'){
								this.runner.stop(this.task);
							}	
							var dataSetRow = q.selectNode('row', root);
							var dataSetKey = dataSetRow.getAttribute("key");
							var recPos = this.activeBrowser.grid.getStore().getAt(e.row);
							var values = q.jsSelect('column', root);
							
							
								if ( recPos.phantom == true ){
									// it s a new Record so just update
									Ext.Ajax.request({
										url: this.activeBrowser.providerUrl,
										scope: this,
										params: {
											action: 'store',
											subject: this.activeBrowser.subject,
											queryXml: '<?xml version="1.0" encoding="UTF-8"?><data-input xmlns="http://brodos.net/schemas/dataStorage/2008/01"><dataset key="'+dataSetKey+'"><column name="ISACTIVE">1</column></dataset></data-input>'
										},
										success: function( response,result ){
											for (var i = 0 ; i < values.length; i++) {
											
								        		var name = values[i].getAttribute("name");

												var text = [];
												for (var n=0;n<values[i].childNodes.length;n++) {
													if (values[i].childNodes[n].nodeType == 3) {
														text.push(values[i].childNodes[n].nodeValue);
													}
												}
												var value = text.join('');
												
												recPos.set(name, value);
												recPos.isNew = false;
												recPos.id = dataSetKey;
												recPos.phantom = false;												
											}
											recPos.commit();
											e.grid.getSelectionModel().selectRow(e.row, false);
											e.grid.getView().focusRow(e.row);
										},
										failure: function(){
										
										}
									});
								}else{
									// its a old record delete the old one
									var delId = recPos.id;
									Ext.Ajax.request({
										url: this.activeBrowser.providerUrl,
										scope: this,
										params: {
											action: 'store',
											subject: this.activeBrowser.subject,
											queryXml: '<?xml version="1.0" encoding="UTF-8"?><data-input xmlns="http://brodos.net/schemas/dataStorage/2008/01"><dataset key="'+delId+'"><column name="ISACTIVE">0</column></dataset></data-input>'
										},
										success: function( response,result ){
											
										},
										failure: function(){
										
										}
									});
									// update with deleted Record which was found
									Ext.Ajax.request({
										url: this.activeBrowser.providerUrl,
										scope: this,
										params: {
											action: 'store',
											subject: this.activeBrowser.subject,
											queryXml: '<?xml version="1.0" encoding="UTF-8"?><data-input xmlns="http://brodos.net/schemas/dataStorage/2008/01"><dataset key="'+dataSetKey+'"><column name="ISACTIVE">1</column></dataset></data-input>'
										},
										success: function( response,result ){
											for (var i = 0 ; i < values.length; i++) {
												var name = values[i].getAttribute("name");

												var text = [];
												for (var n=0;n<values[i].childNodes.length;n++) {
													if (values[i].childNodes[n].nodeType == 3) {
														text.push(values[i].childNodes[n].nodeValue);
													}
												}
												var value = text.join('');
											
												recPos.set(name, value);
												recPos.isNew = false;
												recPos.id = dataSetKey;
												recPos.phantom = false;
											}
											recPos.commit();
											e.grid.getSelectionModel().selectRow(e.row, false);
											e.grid.getView().focusRow(e.row);
										},
										failure: function(){
										
										}
									});
								}
							Ext.Msg.show({
								title: brodos.translation.get('TBrowser_DeletedKeyFound'),
								msg: brodos.translation.get('TBrowser_DeletedKeyFoundText'),
								buttons: Ext.Msg.OK,
								fn:  function(){
									this.checkForDoubleInactiveKeys = true;
								},
								animEl: 'elId',
								icon: Ext.MessageBox.WARNING
							});
						}else{
							this.checkForDoubleInactiveKeys = true;
						}
					}
				});
			};
			this.clearCachesAndSubmit = true;
		},this);
		
	},
	
	/*checkForActiveRequests: function(){
		
		var task = {
			run: function() {
				if ( typeof this.keyExistAjax != 'undefined' || typeof this.keyExistAjax2 != 'undefined' ){
					if (!Ext.Ajax.isLoading(this.keyExistAjax.tId) && !Ext.Ajax.isLoading(this.keyExistAjax2.tId) ) {
						runner.stop(task);
						this.closeWindowQ();
					}
				}else{
					this.closeWindowQ();
					runner.stop(task);
				}
			},
			interval: 100,
			scope: this
		}
		var runner = new Ext.util.TaskRunner();
		runner.start(task);

	},*/
	
	/*handleButtonEvent: function(){
		if(this.activeBrowser.gridStore.getModifiedRecords().length > 0){
			this.buttonwasclicked = true;
			
		}else{
			this.hide();
		}	
	},*/
	
	handleButtonEvent: function(){
		if(this.activeBrowser.gridStore.getModifiedRecords().length > 0){	
			this.task = {
				run: function() {
					if ( this.checkForDoubleActiveKeys && this.checkForDoubleInactiveKeys ) {
						this.runner.stop(this.task);
						this.saveModifiedRecords();
					}
				},
				interval: 100,
				scope: this
			}
			this.runner = new Ext.util.TaskRunner();
			this.runner.start(this.task);
		}else{
			this.saveModifiedRecords();
		}

	},
	
	/*closeWindowQ: function(){
		if (this.buttonwasclicked){
			this.saveModifiedRecords();			
		}else{
		
		}
	},*/
	
	saveModifiedRecords: function(){ 
		if(this.activeBrowser.gridStore.getModifiedRecords().length > 0){
			var queryXml = this.activeBrowser.createDataInputFromRecords(this.activeBrowser.gridStore.getModifiedRecords());
			var oParams = new Object();
			oParams.action = "store";
			oParams.subject = this.activeBrowser.subject;
			oParams.language = this.activeBrowser.localization.language;
			oParams.queryXml = queryXml;
			this.activeBrowser.grid.loadMask.show();
			Ext.Ajax.request({
				url: this.activeBrowser.providerUrl,
				success: function() {
						document.forms[0].clearcache.value = 1;
						this.hide.defer(100, this);
						this.hideWindowAction();
				},
				failure: this.activeBrowser.onSaveChangesFailure.createDelegate(this.activeBrowser),
				params: oParams,
				scope:this
			});
		}
		else {
			this.hideWindowAction();
			this.hide();			
		}
	},
	
	hideWindowAction: function(){
		if (this.clearCachesAndSubmit == true){
			if ( typeof document.forms[0].debtopbuttonpressed != 'undefined'){
				if (document.forms[0].debtopbuttonpressed.value == 'SHOW'){
					
				}else{
					document.forms[0].submit();
				}
			}						
			else if (  typeof document.forms[0].topbuttonpressed != 'undefined' ){
				if ( document.forms[0].topbuttonpressed.value == 'SHOW' ){
				
				}else{
					document.forms[0].submit();
				}
			}
			else if ( typeof document.forms[0].arttopbuttonpressed != 'undefined' ){
				if (document.forms[0].arttopbuttonpressed.value == 'SHOW'){
					
				}else{
					document.forms[0].submit();
				}
			}
			else
			{
				document.forms[0].submit();
			}
		}
	}
});