Ext.ns('Ext.wc');

function questionFieldsDataRenderer(val)
{
	//function(val){return (!val || val== '') ? /*'<font color=\"#c0c0c0\">[Empty]</font>'*/'&#160;' : stripHTML(val); /*val.replace(/<br>/gi,'');*/   }
	if(!val || val == '') return '&#160;';
	var v = stripHTML(val)
	if(v != val)
		v = '<font color="#808080" style="font-size:6">[HTML]</font> '+v;
	return v;
	
}

function wcbqAddTextField(obj,text,space)
{
	if( obj.cmp =='field')
	{
		
		var fl = obj.field;
		if(fl)
			{
			
				if(Ext.isIE)
				{
					var pos = obj.field.fCaret;
				}
				else 
				{					
					var pos= getCaretPosition(  fl.getId() );
				}
				
				var t = fl.getValue();
				if(space)
				{
					//tu se preverjanje �e je �e presledek al če je na za�etku da ne dodamo
					text = ' '+text+' ';
				}
				
				fl.setValue( t.substring(0,pos) + text+t.substring(pos,t.length) );
				setCaretPosition(fl.getId(),pos+text.length);
				
				if(Ext.isIE)
				{
					obj.field.fCaret += text.length;
				}
				fl.fireEvent('change',fl,fl.getValue());
			
			}	
	
		
		
		}
	else if(obj.cmp == 'grid')
	{
		//if the position was on the grid we have saved the row and column that was editet
		obj.grid.startEditing(obj.gRow,obj.gCell);
		var fl = obj.grid.activeEditor;
		var pos= obj.fCaret;
			
		var t = fl.getValue();
		
		if(space)
			{
				//tu se preverjanje �e je �e presledek al �e je na za�etku da ne dodamo
				text = ' '+text+' ';
			}
		
		
		fl.setValue( t.substring(0,pos) +text+t.substring(pos,t.length) );
		setCaretPosition(fl.field.getId(),pos+text.length);
		
	
	}
}

/**
 * 
 * @class Ext.ux.CalcTBar
 * @extends Ext.Toolbar
 * A toolbar with operators, numbers and sings for adding into fields
 */
Ext.ux.CalcTBar = Ext.extend(Ext.Toolbar,{
	/**
	 * what type of component we add
	 * textField or grid
	 * @type String
	 */
	cmp:'',
	field: null,
	enableOverflow:true,
	grid:null,
	fCaret:0,
	gRow:0,
	gCell:0,
	func:	function(text,space){
			wcbqAddTextField(this,text,space);
			return;
			
			},
	initComponent:function(){
		Ext.apply(this,{
			defaults:{scope:this},
			items:[{
				
				cls: 'ux-tbar-add-operator',
				text:'AND',
				handler: function(){this.func('AND',true);},
				width: 30
			}, {
				
				cls: 'ux-tbar-add-operator',
				text:'OR',
				handler: function(){this.func('OR',true);}, //eof handler
				width: 30
			}, {
				
				cls: 'ux-tbar-add-operator',
				text:'NOT',
				handler: function(){this.func('NOT',true)},
				width: 30
			}, {
				
				cls: 'ux-tbar-add-operator',
				text:'=',
				handler: function(){this.func('=',true);},
				width: 30
			}, {
				
				cls: 'ux-tbar-add-operator',
				text:'!',
				handler: function(){this.func('!',false)},
				width: 30
			}, {
				
				cls: 'ux-tbar-add-operator',
				text:'&lt;',
				handler: function(){this.func('<',false);}, //eof handler
				width: 30
			}, {
				
				cls: 'ux-tbar-add-operator',
				text:'>',
				handler: function(){this.func('>',false)},
				width: 30
			},
			{
				cls: 'ux-tbar-add-operator',
				text:'(',
				handler: function(){this.func('(');	},
				width: 30
			}, 
			{
				cls: 'ux-tbar-add-operator',
				text:')',
				handler: function(){this.func(')');	},
				width: 30
			},'-',
			{
				cls: 'ux-tbar-add-digit',
				text:'0',
				handler: function(){this.func('0');	},
				width: 30
			}, 
			{
				cls: 'ux-tbar-add-digit',
				text:'1',
				handler: function(){this.func('1');	},
				width: 30
			}, {
				
				cls: 'ux-tbar-add-digit',
				text:'2',
				handler: function(){this.func('2');},
				width: 30
			}, {
				
				cls: 'ux-tbar-add-digit',
				text:'3',
				handler: function(){this.func('3')},
				width: 30
			},
			{
				cls: 'ux-tbar-add-digit',
				text:'4',
				handler: function(){this.func('4');	},
				width: 30
			}, {
				
				cls: 'ux-tbar-add-digit',
				text:'5',
				handler: function(){this.func('5');},
				width: 30
			}, {
				
				cls: 'ux-tbar-add-digit',
				text:'6',
				handler: function(){this.func('6')},
				width: 30
			},
			{
				cls: 'ux-tbar-add-digit',
				text:'7',
				handler: function(){this.func('7');	},
				width: 30
			}, {
				
				cls: 'ux-tbar-add-digit',
				text:'8',
				handler: function(){this.func('8');},
				width: 30
			}, {
				
				cls: 'ux-tbar-add-digit',
				text:'9',
				handler: function(){this.func('9')},
				width: 30
			},'-', {
				cls: 'ux-tbar-add-sign',
				text:'==',
				handler: function(){this.func('==');	},
				hidden: this.showStyle == 'SQL',
				width: 30
			}, {
				cls: 'ux-tbar-add-sign',
				text:'!=',
				handler: function(){this.func('!=');	},
				hidden: this.showStyle == 'SQL',
				width: 30
			}, {
				
				cls: 'ux-tbar-add-sign',
				text:'+',
				handler: function(){this.func('+');},
				hidden: this.showStyle == 'SQL',
				width: 30
			}, {
				
				cls: 'ux-tbar-add-sign',
				text:'-',
				handler: function(){this.func('-')},
				hidden: this.showStyle == 'SQL',
				width: 30
			},
			{
				cls: 'ux-tbar-add-sign',
				text:'/',
				handler: function(){this.func('/');	},
				hidden: this.showStyle == 'SQL',
				width: 30
			}, 
			{
				
				cls: 'ux-tbar-add-sign',
				text:'*',
				handler: function(){this.func('*');},
				hidden: this.showStyle == 'SQL',
				width: 30
			}, {
				
				cls: 'ux-tbar-add-sign',
				text:'.',
				handler: function(){this.func('.')},
				hidden: this.showStyle == 'SQL',
				width: 30
			},
			{
				cls: 'ux-tbar-add-sign',
				text:',',
				handler: function(){this.func(',');	},
				hidden: this.showStyle == 'SQL',
				width: 30
			}]
		});
		//call the initComponent method of the superclass
		Ext.ux.CalcTBar.superclass.initComponent.call(this);
	}
	
	
} );

Ext.wc.DropQuestion = Ext.extend(Ext.dd.DropTarget,{
	ddGroup:'wcqbGroup',
	addSign:'$',
	textVar:'text',
	onDragClick : function(e){
					if(this.dropList && !e.within(this.dropList.dom))
					{
						Ext.destroy(
			           this.dropList,
			            this.dropView
			           
        				);		
        				this.dropList = null;
           			 this.dropView = null;
           			 Ext.getDoc().un('mousedown',this.onDragClick,this);	
					}
					 
				 },
	dropCond:function(dds,e,data){return true;},
	updateField:function(dds,e,value){
		wcbqAddTextField(this,value,true);
	},
	notifyDrop:function(dds,e,data)
	{
		return this.myNotifyDrop(dds,e,data);
	},
	myNotifyDrop:function(dds,e,data) { 
		//we send a request to get the answers type and answers data to show the possible values
		if(!this.dropCond(dds,e,data) )
			return false;
		this.RMconn.request({
			scope:this,
			params:{
				action:'getAnswer',id:data.node.attributes.id
			},
			success:function(resp){
				var r = Ext.decode(resp.responseText);
			if(r.success)
			{
				if(r.data != '')
				{
					if(!this.dropList)
					{
					this.dropList = new Ext.Layer({
						parentEl:document.body,
						constrain:false,
						zindex:12000,
						cls:'x-combo-list'
					});
					this.dropList.setSize(300,0)
					
					this.innerList = this.dropList.createChild({cls:'x-combo-list-inner'});
					
					 
		           
					 this.dropStore = new Ext.data.ArrayStore({
						fields:['id','odg']
					});
					
					
					this.dropView = new Ext.DataView({
							store: this.dropStore,
							applyTo: this.innerList,
							tpl: '<tpl for=\".\"><div class=\"x-combo-list-item\">{id}: {odg}</div></tpl>',
							selectedClass : 'x-combo-selected',
							itemSelector:'.x-combo-list-item',
							singleSelect: true
						});
						
						 this.dropView.mon(this.innerList, 'mouseover',function(e,t){
					  	 var item = this.dropView.findItemFromChild(t);
				        if(item){
				            var index = this.dropView.indexOf(item);
				            this.dropView.select(index);
				        }
					  },this );
						
						
						 this.dropView.on( 'click', function(dv,index){
									var selAns = dv.getStore().getAt(index).data.id; 	
									
									var addT = this.addSign+data.node.attributes[this.textVar];
									if(selAns != '')
										addT += '_'+selAns;	
									
									Ext.getDoc().un('mousedown',this.onDragClick,this);
									 Ext.destroy(
									           this.dropList,
									            this.dropView
							        			); 
						 			this.dropList = null;
						            this.dropView = null;
						            this.updateField(dds,e,addT);
						            
						           
		         		},this);	
					Ext.getDoc().on('mousedown',this.onDragClick,this);
					
							
					}
					//$formName.dropView.bindStore($formName.dropStore);
					this.dropStore.loadData( slashDelimitedToArray( r.data)  );
					//$formName.dropView.refresh();	
					
					this.dropList.setXY(e.xy);
					if(this.innerList.getHeight() > 150)
						this.innerList.setHeight(150);
					this.dropList.setHeight(this.innerList.dom.clientHeight);
					
					
					
						this.dropList.show();
					}
					else //if there is no data we add just the name of the question 
					{
								var addT = this.addSign+data.node.attributes[this.textVar];						
								
									
								this.updateField(dds,e,addT);
					}
				}		
			}//eof success of get answers data!!!
		}); //eof get answers data!!!
		
		return true;
	}
});
/*
* Sample json load code :
* Ext.getCmp('<combotree>').loadTree(url,params) 
* url : '../..../....Action.do?islem=giris '
* params : {'itemId':Ext.getCmp('item').getValue()}
*
 * Animal's TreeCombo modified by Wedgie to handle a maxHeight config setting.
 * This updated version fixes the following problems:
 *   1) Accounts for horizontal scrollbar when calculating required height
 *   2) Set height using correct method to fire resize and update the shadow
 *   3) Realigns the tree with the trigger field when the tree size changes
 */

Ext.ux.TreeCombo = Ext.extend(Ext.form.TriggerField, {

    triggerClass: 'x-form-tree-trigger',

    initComponent : function(){
        this.editable = false;
        Ext.ux.TreeCombo.superclass.initComponent.call(this);
        this.on('specialkey', function(f, e){
            if(e.getKey() == e.ENTER){
                this.onTriggerClick();
            }
        }, this);
        this.getTree();
    },

    onTriggerClick: function() {
        this.getTree().show();
        this.getTree().getEl().alignTo(this.wrap, 'tl-bl?');
    },

    getTree: function() {
        if (!this.treePanel) {
            if (!this.treeWidth) {
                this.treeWidth = Math.max(200, this.width || 200);
            }
            if (!this.treeHeight) {
                this.treeHeight = 200;
            }
            this.treePanel = new Ext.tree.TreePanel({
                renderTo: Ext.getBody(),
                loader: this.loader || new Ext.tree.TreeLoader({
                    preloadChildren: (typeof this.root == 'undefined'),
                    url: this.dataUrl || this.url
                }),
                root: this.root || new Ext.tree.AsyncTreeNode({
                    text : 'Root', 
                    id: '0'
                    
                }),
                selModel : this.selModel || new Ext.tree.DefaultSelectionModel(),
                rootVisible: (typeof this.rootVisible != 'undefined') ? this.rootVisible : (this.root ? true : false),
                floating: true,
                autoScroll: true,
                minWidth: 200,
                minHeight: 200,
                width: this.treeWidth,
                height: this.treeHeight,
                autoHeight:this.autoHeight,
                shadow : ! this.autoHeight,
                listeners: {
                    hide: this.onTreeHide,
                    show: this.onTreeShow,
                    click: this.onTreeNodeClick,
                    expandnode: this.onExpandOrCollapseNode,
                    collapsenode: this.onExpandOrCollapseNode,
                    resize: this.onTreeResize,
                    scope: this
                }
            });
            this.treePanel.show();
            this.treePanel.hide();
            this.relayEvents(this.treePanel.loader, ['beforeload', 'load', 'loadexception']);
            if(this.resizable){
                this.resizer = new Ext.Resizable(this.treePanel.getEl(),  {
                   pinned:true, handles:'se'
                });
                this.mon(this.resizer, 'resize', function(r, w, h){
                    this.treePanel.setSize(w, h);
                }, this);
            }
        }
        return this.treePanel;
    },

    onExpandOrCollapseNode: function() {
        if (!this.maxHeight || this.resizable)
            return;  // -----------------------------> RETURN
        var treeEl = this.treePanel.getTreeEl();
        var heightPadding = treeEl.getHeight() - treeEl.dom.clientHeight;
        var ulEl = treeEl.child('ul');  // Get the underlying tree element
        var heightRequired = ulEl.getHeight() + heightPadding;
        if (heightRequired > this.maxHeight)
            heightRequired = this.maxHeight;
        this.treePanel.setHeight(heightRequired);
       
    },

    onTreeResize: function() {
        if (this.treePanel && this.wrap)
            this.treePanel.getEl().alignTo(this.wrap, 'tl-bl?');
    },

    onTreeShow: function() {
        Ext.getDoc().on('mousewheel', this.collapseIf, this);
        Ext.getDoc().on('mousedown', this.collapseIf, this);
    },

    onTreeHide: function() {
        Ext.getDoc().un('mousewheel', this.collapseIf, this);
        Ext.getDoc().un('mousedown', this.collapseIf, this);
    },

    collapseIf : function(e){
        if(!e.within(this.wrap) && !e.within(this.getTree().getEl())){
            this.collapse();
        }
    },

    collapse: function() {
        this.getTree().hide();
        if (this.resizer)
            this.resizer.resizeTo(this.treeWidth, this.treeHeight);
    },

    // private
    validateBlur : function(){
        return !this.treePanel || !this.treePanel.isVisible();
    },

    setValue: function(v) {
        this.startValue = this.value = v;
        if (this.treePanel) {
            var n = this.treePanel.getNodeById(v);
            if (n) {
                this.setRawValue(n.text);
            }
        }
    },

    getValue: function() {
        return this.value;
    },

    onTreeNodeClick: function(node, e) {
        this.setRawValue(node.text);
        this.value = node.id;
        this.fireEvent('select', this, node);
        this.collapse();
    },
    loadTree : function(url,pr) {
        var tp = this.treePanel;
        tp.getRootNode().removeAll();
        var conn = new Ext.data.Connection();
        conn.request({url: url || this.url,
                    params:pr||{}, 
            success: function(a){
                var tb_items = Ext.util.JSON.decode(a.responseText);    
                tp.getRootNode().appendChild(tb_items);
            }    
        });
    }
});
Ext.reg('treecombo', Ext.ux.TreeCombo);
