/*
 * Ext JS Library 2.1
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */


var ExtTree=function(el,root,options)
//options的参数curl,ourl,treeMode(1:可编辑，0:不可编辑),lurl
{
	var catalogURL='#';
	var operateURL='#';
	var supplierURL='#';
	var sid=0;
	var siname="";
	var leafURL=null;
	var treeMode=0;
	var btnDel=null;
	var btnAdd=null;
	var btnReName=null;
	if(options!=null){
		var catalogURL=options.curl;
		if(options.treeMode==1)
		{
			treeMode=options.treeMode;
			operateURL=options.ourl;
			supplierURL=options.surl;
		}else if(options.treeMode==3){
			treeMode=options.treeMode;
			operateURL=options.ourl;
			supplierURL=options.surl;
			sid=options.sid;
			siname=options.siname;
		}
		
		leafURL=options.lurl;
	}
	
	var rootJson=root;
    var objel=el;
    var  myMask = new Ext.LoadMask(el, {msg:"Please wait..."});
    var Tree = Ext.tree;
    var rootNode=null;
    var treePanel= null;

    var nowNode=null;
    var nowRow=null;
    var nowName=null;
    var SearchWindowEx=Ext.extend(SearchWindow,{
			initWin:function(){		
				SearchWindowEx.superclass.initWin.call(this);
				
				var callback=function(conn,response,options){
					myMask.hide();
					if(response.responseText=='success')
					{
						nowNode.appendChild(new Ext.tree.TreeNode({id:this.store.getAt( this.nowRow ).get('supplierid'),leaf:true,text:this.store.getAt( this.nowRow ).get('suppliername')}));
					}									
					else alert(response.responseText);
				};
				this.windowL.on("hide",function(targer){
					myMask.hide();
				});
				this.grid.on('rowdblclick',function( e, rowIndex, event ){
					if(this.nowRow!=null && nowNode!=null){
		            	var ajax=new Ext.data.Connection({autoAbort : false, serializeForm : function(form){
							       return Ext.lib.Ajax.serializeForm(form);
				  				}
						});
						//alert(nowNode.text);
						ajax.request({
							   url: operateURL,
							   params: { type:'insert',id:this.store.getAt( this.nowRow ).get('supplierid'),father:nowNode.id}
						});							
						ajax.on("requestcomplete",callback.bind(this));
						e.ownerCt.hide();
	            	}
				})
			} 
		})
	if(treeMode==1)
	{
	    btnDel=new Ext.Button({
	        text: '删除'        
	    })
	    btnAdd=new Ext.Button({
	        text: '添加'        
	    })
	    
	    btnReName=new Ext.Button({
	        text: '重命名'        
	    })
	   	btnInsert=new Ext.Button({
	        text: '添加供应商'        
	    })
		btnReName.on("click",function(btn,e){		
			if(nowNode){
				if(!nowNode.isLeaf())		
				{
					var ajax=new Ext.data.Connection({autoAbort : false, serializeForm : function(form){
							       return Ext.lib.Ajax.serializeForm(form);
			  				}
					});
					
					Ext.MessageBox.prompt('重命名', '请填写新的目录名:', function(btn, text){
			                if(btn == 'ok' && text){
								nowName=text;
								ajax.request({
									   url: operateURL,
									   params: { id:nowNode.id,siname:text,type:"rename"}
								});
								myMask.show();
			                }
			            });
			        ajax.on("requestcomplete",function(conn,response,options){
							myMask.hide();
							if(response.responseText=='success')
								nowNode.setText(nowName);
							else alert(response.responseText);
					})
				}
				else{
					alert("公司名不能在此处更改");
				}
			}
			else{
				alert('请先选择一个目录');
			}
		});
		
		btnAdd.on("click",function(btn,e){		
			if(nowNode){
				if(!nowNode.isLeaf())		
				{
					var ajax=new Ext.data.Connection({autoAbort : false, serializeForm : function(form){
							       return Ext.lib.Ajax.serializeForm(form);
			  				}
					});
					
					Ext.MessageBox.prompt('添加目录', '请填写新的目录名:', function(btn, text){
			                if(btn == 'ok' && text){
								nowName=text;
								ajax.request({
									   url: operateURL,
									   params: {father:nowNode.id,siname:text,type:"add"}
								});
								myMask.show();							
			                }
			            });
			            
	
					
					ajax.on("requestcomplete",function(conn,response,options){
							//alert(response.responseText);
							myMask.hide();
							if(response.responseText.indexOf('success')>=0)
							{
								nowNode.appendChild(new Ext.tree.TreeNode({id:response.responseText.substring(response.responseText.indexOf('@')+1,response.responseText.length),leaf:false,isTarget:true,text:nowName}));
							}
							else alert(response.responseText);
					})
				}
				else{
					alert("您选择的不是目录,请重新选择");
				}
			}
			else{
				alert('请先选择一个目录');
			}
		});
		
		btnDel.on("click",function(btn,e){		
			if(nowNode){
				if(confirm("您确定此项目吗(其子项也会被删除)?")==true)
				{
					myMask.show();
					var ajax=new Ext.data.Connection({autoAbort : false, serializeForm : function(form){
							       return Ext.lib.Ajax.serializeForm(form);
			  				}
					});
					ajax.request({	   url: operateURL,
									   params: {father:nowNode.parentNode.id,id:nowNode.id,isCompany:nowNode.isLeaf(),type:"del"}
								});
				 	ajax.on("requestcomplete",function(conn,response,options){
								myMask.hide();
								if(response.responseText=='success')
								{
									if(nowNode.id==rootNode.id)
									{
										treePanel.hide();
									}
									else {
										nowNode.remove();
										//treePanel.getLoader().load(nowNode.parentNode);	
									}
								}
								else alert(response.responseText);
								
					});
	
				}
	
			}
			else{
				alert('请先选择一个目录');
			}
		});
		
		btnInsert.on("click",function(btn,e){	
				if(nowNode){
				if(!nowNode.isLeaf())		
				{
					myMask.show();
					
					var win=new SearchWindowEx(supplierURL);
					win.show('',false);	
					//windowL.show();
				}
				else{
					alert("您选择的不是目录,请重新选择");
				}
			}
			else{
				alert('请先选择一个目录');
			}

		});

	}else if(treeMode==3){
	   	btnInsert=new Ext.Button({
	        text: '添加供应商'        
	    })		
		btnDel=new Ext.Button({
	        text: '删除'        
	    })
		btnInsert.on("click",function(btn,e){	
			if(nowNode){
				if(!nowNode.isLeaf())		
				{
					var callback2=function(conn,response,options){
						myMask.hide();
						if(response.responseText=='success')
						{
							nowNode.appendChild(new Ext.tree.TreeNode({id:sid,leaf:true,text:siname}));
						}									
						else alert(response.responseText);
					};
					myMask.show();					
					if(nowNode!=null){
		            	var ajax=new Ext.data.Connection({autoAbort : false, serializeForm : function(form){
							       return Ext.lib.Ajax.serializeForm(form);
				  				}
						});
						ajax.request({
							   url: operateURL,
							   params: { type:'insert',id:sid,father:nowNode.id}
						});							
						ajax.on("requestcomplete",callback2.bind(this));
	            	}
				}
				else{
					alert("您选择的不是目录,请重新选择");
				}
			}
			else{
				alert('请先选择一个目录');
			}

		});

		btnDel.on("click",function(btn,e){		
			if(nowNode){
				if(!nowNode.isLeaf()){
					alert("您没有权限对目录进行操作，请选择一家供应商");	
				}else if(confirm("您确定此项目吗?")==true)
				{
					myMask.show();
					var ajax=new Ext.data.Connection({autoAbort : false, serializeForm : function(form){
							       return Ext.lib.Ajax.serializeForm(form);
			  				}
					});
					ajax.request({	   url: operateURL,
									   params: {father:nowNode.parentNode.id,id:nowNode.id,isCompany:nowNode.isLeaf(),type:"del"}
								});
				 	ajax.on("requestcomplete",function(conn,response,options){
								myMask.hide();
								if(response.responseText=='success')
								{
									if(nowNode.id==rootNode.id)
									{
										treePanel.hide();
									}
									else {
										nowNode.remove();
										//treePanel.getLoader().load(nowNode.parentNode);	
									}
								}
								else alert(response.responseText);
								
					});
	
				}
	
			}
			else{
				alert('请先选择一个目录');
			}
		});
	
	}
	
	if(treeMode==1)
    {
    	treePanel=new Tree.TreePanel({
                el:objel,
                animate:true, 
                autoScroll:true,
                loader: new Tree.TreeLoader({dataUrl:catalogURL}),
                enableDD:true,
                containerScroll: true,
                buttons:[btnDel,btnAdd,btnReName,btnInsert],
                dropConfig: {appendOnly:true},
                width:225,
                height:220
            });
    }else if(treeMode==3){
    	  treePanel=new Tree.TreePanel({
                el:objel,
                animate:true, 
                autoScroll:true,
                loader: new Tree.TreeLoader({dataUrl:catalogURL+"?id="+sid}),
                enableDD:false,
                containerScroll: true,
                buttons:[btnDel,btnInsert],
                width:225,
                height:220
            });
    }
    else
    {
    	treePanel=new Tree.TreePanel({
                el:objel,
                animate:true, 
                autoScroll:true,
                loader: new Tree.TreeLoader({dataUrl:catalogURL}),
                enableDD:false,
                containerScroll: true,
                width:225,
                height:250
            });
    }
    
    return {
        init : function(){
            // yui-ext tree
           var tree =treePanel;
            
            // add a tree sorter in folder mode
            new Tree.TreeSorter(tree, {folderSort:true});
            if(treeMode==1){
	            tree.on('beforenodedrop',function(e){     
				     if(e.point=='append'){   
			            if(confirm("您确定要将\""+e.dropNode.text+"\"插入到\""+e.target.text+"\"目录下吗?")==true)
						{
							var ajax=new Ext.data.Connection({autoAbort : false, serializeForm : function(form){
								       return Ext.lib.Ajax.serializeForm(form);
	  							  }
							});
							ajax.request({
							   url: operateURL,
							   params: { id:e.dropNode.id,newfather:e.target.id,oldfather:e.dropNode.parentNode.id,type:"update"}
							});
							ajax.on("requestcomplete",function(conn,response,options){
								myMask.hide();
								if(response.responseText="success")
								{
									alert("更新成功");
								}
								else alert("更新目录时出现异常,请刷新页面后重试");
							})
							myMask.show();
	
						}	
						else e.cancel=true;
			         }
			         
			    });  
	        }
	        tree.on('click' ,function(node,e ){
			    	//alert('click');
			    	nowNode=node;
			}) ; 
            if(leafURL!=null)
			{
			   	tree.on('append',function(tree, parent,node, refNode ){
			   		if(node.isLeaf())
			   		{
			   			node.attributes.hrefTarget='_blank';
			   			node.attributes.href=leafURL+'?id='+node.id;
			   		}
			   	});
			}   
            // set the root node
            var root = new Tree.AsyncTreeNode({
                text: rootJson.text, 
                draggable:false, // disable root node dragging
                id:rootJson.id
            });
            tree.setRootNode(root);
            
            // render the tree
            tree.render();
            
            root.expand(false, /*no anim*/ false);
            rootNode=tree.getRootNode();
            
                     
        }
    };
    
    
    
}
		

//Ext.EventManager.onDocumentReady(TreeTest.init, TreeTest, true);
