<?php 
	require "_header.php";
	require "commonincludefiles.php"; 
    
	if ($_REQUEST["ID"]!="" && isset($_REQUEST["ID"])){
		$user_id	= $_REQUEST["ID"];
		$mode="edit";
	
		$limit=1;
		$start=0;
		$condition="";
		$order_field="";
		$order_type="";
		if($user_id!=""){
           $condition .= " and user_id='$user_id' ";
    	}

		$objUserMgmt = new UserMgmt();
		$out = $objUserMgmt->getAllRecords($limit,$start,$condition,$order_field,$order_type);
		if(dbRows($out)){
			$row=dbArray($out);
			extract($row);	
			$user_id= $row["user_id"];
			$user_name= $row["user_name"];
			$user_password= $row["user_password"];
			$menuids = $row["menu_ids"];
			$pageids = $row["page_ids"];
			$subpageids = $row["subpage_ids"];
		}    	
	}	
	else{
		$mode="add";
		if($ADD == "false"){
			redirectToPage();
		}
		$user_id=0;
		$menuids = "";
		$pageids = "";
		$subpageids = "";
	}
?>
<!--<div id="main-content" align="left">
<script language="javascript" type="text/javascript">
-->

<script type="text/javascript">

Ext.onReady(function(){

   	var labelArray;
		labelArray = [['Username :<span class="comp">*</span>'],
			 	      ['Password :<span class="comp">*</span>'],
				      ['Confirm Password :<span class="comp">*</span>'],
					  ['Company Name :<span class="comp">*</span>'],
					  ['Power User :<span class="comp">*</span>'],
					  
					  ];
					  
	var formMode 	= '<?php echo $mode;?>';	
	var user_id 	= '<?php echo $user_id; ?>';
	var menuids 	= '<?php echo $menuids; ?>';
	var pageids 	= '<?php echo $pageids; ?>';
	var subpageids 	= '<?php echo $subpageids; ?>';
	var resbool		= "";	
		
	Ext.apply(Ext.form.VTypes, {
		password : function(val, field) {
			if (field.initialPassField) {
				var login = Ext.getCmp(field.initialPassField);
				return (val == login.getValue());
			}
			return true;
		},
		passwordText : 'Passwords do not match.'
	});
	
	var companyliststore = new Ext.data.Store({
		url: 'data/getcompanylist.php',          
		reader: new Ext.data.JsonReader({			
		fields: ['company_id','company_name'],
		root: 'rows'
		}),autoLoad:true
	});

	var varpath =  'get-user-access-tree.php?userid='+user_id+'&menuid='+menuids+'&pageid='+pageids+'&subpageids='+subpageids;
	
	var tree = new Ext.tree.TreePanel({
        useArrows:true,
        autoScroll:true,
        animate:true,
        enableDD:true,
        containerScroll: true,
        rootVisible: true,
	 	animCollapse: true,
		setRootNode : function(node){
			this.root = node;
			node.ownerTree = this;
			if(menuids != ""){
				this.root.attributes.checked = true;
			} else{
				this.root.attributes.checked = false;
			}
		}
		,getChecked : function(a, startNode){
			
			startNode = startNode || this.root;
			var r = [];
			var f = function(){
				if(this.attributes.checked){
					r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
				}
			};
			startNode.cascade(f);
			return r;
    	}
		,loader: new  Ext.tree.TreeLoader({
                        dataUrl:varpath,
						baseAttrs: { uiProvider: Ext.ux.TreeCheckNodeUI } //add uiProvider attribute
                })

		,listeners: {
            'checkchange': function(node, checked){							
			
				var sibling = false;

				if(checked){
                    Ext.get('cn').dom.value = tree.getChecked().join(',');
					
					// chech all parents of selected node
					if(node.parentNode != null){
						node.parentNode.getUI().toggleCheck(checked);
					}
				
				} else{
					// chech all childs of selected node								
					if(node.parentNode != null){
						node.parentNode.eachChild(function(n) {
							if(n.attributes.checked){
								sibling=true;																	
							}												
						});	
						if(sibling==false)	
							node.parentNode.getUI().toggleCheck(checked);
							
						
						/*node.eachChild(function(n){
							n.getUI().toggleCheck(checked);
						});	
							*/
					}				
                    Ext.get('cn').dom.value = tree.getChecked().join(',');
                }
            },
			'append': function(tree,parent,node,idx){
				if(node.attributes.checked){
					if(node.isLeaf()==false){
						node.expand();
					}										  							
			  	}						
			}
        }
	});
	
	
	root = new Ext.tree.AsyncTreeNode({
		text: 'LEAD MANAGEMENT SOFTWARE',
		draggable:false,
		id:'node-root',
		uiProvider: Ext.ux.TreeCheckNodeUI
	});
	
	tree.setRootNode(root);
	root.expand();
	
	var simple = new Ext.FormPanel({
        labelWidth: 117, 
		//standardSubmit:true,
		url:"save-user.php",
        frame:true,
		autoScroll:true,
        bodyStyle:'padding:5px 5px 0',
        width:450,
		height:410,
        defaultType: 'textfield',
		items :[{
				   xtype: 'combo',
				   name: 'company_id',
				   id:'company_id',
				   hiddenName: 'company_heden',
				   tabIndex:1,
				   labelSeparator:'',	
				   fieldLabel :labelArray[3] ,
				   displayField:'company_name',
				   valueField: 'company_id',
				   width: 190,
				   blankText: '',
				   emptyText:'',
				   allowBlank:false,
				   triggerAction:'all',
				   mode:'local',			
				   selectOnFocus: true,	
				   store: companyliststore,
				   forceSelection:true,
				   editable:false
     			},{	
					xtype: 'textfield',
					labelSeparator:'',	
					fieldLabel :labelArray[0] ,
					name: 'username',
					tabIndex:2,
					width:190
					,allowBlank:false
				},{
					labelSeparator:'',	
					fieldLabel :labelArray[1] ,
					name:'password',
					width:190,
					tabIndex:3,
					inputType:'password',
					id: 'pass',
					minLength:      5,
					minLengthText:  'Password length must be between 5-15 characters.',
					maxLength:  	15,
					maxLengthText:  'Password length must be between 5-15 characters.'
					,allowBlank:false
				},{
					labelSeparator:'',	
					fieldLabel :labelArray[2] ,
					name:'password1',
					tabIndex:4,
					width:190,
					inputType:'password',
					vtype:'password',
					initialPassField: 'pass',
					minLength:      5,
					minLengthText:  'Password length must be between 5-15 characters.',
					maxLength:  	15,
					maxLengthText:  'Password length must be between 5-15 characters.'
					,allowBlank:false
				},{
					labelSeparator:'',
					 xtype: 'checkbox',	
					fieldLabel :labelArray[4],
					name:'poweruser',
					id:'poweruser',
					tabIndex:5,
					width:190,
					allowBlank:false
				},{		
					name: 'user_id',
					id:'user_id',
					value:user_id,
					hidden: true
				},tree,/*{		
					name: 'msgv',
					id:'msgv',
					hiddenName: 'msgv',
					hidden: true
				},*/{		
					name: 'cn',
					id:'cn',
					hiddenName: 'cn',
					hidden: true
				}
		
			]
	});
	
	var UserAddEditWindow = new Ext.Window({
		title: 'Create User',
		width:440,		
		autoHeight:true,
		modal:true,
		border: false,
		layout: 'fit',
		closeAction:'close',
		collapsible:true,
		items: simple,
		buttonAlign: 'center',
		buttons:[						
			{
				
				text: 'Save',
				iconCls: 'icon-save',		
				name:'btnSave',
				id:'btnSave',
				handler: function(){
					
					//alert(Ext.fly('tree').getSelectionModel().getSelectedNode());
					/*var msg = "" , selNodes = tree.getChecked();
					Ext.each(selNodes, function(node){
						if(msg.length > 0){
							msg += ', ';
						}
						msg += node.id;
					});
					simple.getForm().findField('msgv').setValue(msg);*/
					//alert (simple.getForm().findField('cn').getValue());
					simple.getForm().submit({
						waitMsg: 'Saving...',
						success: function (){
							Ext.MessageBox.show({
								   title: 'Message',
								   msg: 'User saved successfully.',
								   buttons: Ext.MessageBox.OK,
								   icon:Ext.MessageBox.INFO
							});
							if(formMode=='edit')
					    	{
								location.href="view-user.php";
						   }
						},
						failure: function () {
							Ext.MessageBox.show({
								title: 'Error',
								msg: 'User creation failed.',
								buttons: Ext.MessageBox.OK,
								icon:Ext.MessageBox.ERROR
							});
						}
					});   							
				}
			},{				
				
				text: 'Reset',
				iconCls: 'icon-reset',		
				name:'btnReset',
				id:'btnReset',
				handler: function (){
				if(formMode!='edit')
				{simple.getForm().reset();
				companyliststore.load();
				tree.getRootNode().reload();
				var msg = Ext.getCmp('cn').getValue();
				SetSectionValue('add',companyliststore,'company_id','company_id'); 
				}
				}
			},{
				text: 'Close',
				iconCls: 'icon-close',		
				name:'btnClose',
				id:'btnClose',			
				handler: function (){
					UserAddEditWindow.close();
					
				}
			},{
				text: 'Expand All',
				iconCls: 'icon-expand',		
				name:'btnexpand',
				id:'btnexpand',			
				handler: function (){
					tree.expandAll();
				}
			},{
				text: 'Collapse All',
				iconCls:'icon-collapse',
				name:'btncollapse',
				id:'btncollapse',			
				handler: function (){
					tree.collapseAll();
					tree.getRootNode().expand();
				}
			}
		]
	});

	var varWidth = (screen.width - UserAddEditWindow.width)/2;
	UserAddEditWindow.setPosition(varWidth,((screen.height/4)-110));
	UserAddEditWindow.show();
	SetSectionValue('add',companyliststore,'company_id','company_id'); 
	
	//simple.getForm().findField('company_id').focus(true,500);
	simple.getForm().findField('poweruser').on('check',function (){
		
		 if(simple.getForm().findField('poweruser').getValue()==false) 
		  {
			 tree.show();
			
			 var msg = Ext.getCmp('cn').setValue("");
			 tree.getRootNode().reload();
			 tree.getRootNode().checked=false;
		 } 
	      else
		  {
			tree.hide();
		  }
}); 
	
	simple.getForm().findField('username').on('blur',function (){
		
		var varusername=simple.getForm().findField('username').getValue();
		
		var user_id=simple.getForm().findField('user_id').getValue();	
		
		var resbool="";		
				
		if(varusername!="")
		{			
					Ext.Ajax.request({
							  loadMask: true,
							  sync : true,
							  url: 'data/checkusername.php',
							  params: {username:varusername,user_id:user_id},
							  success: function(resp) {
								resbool=Ext.decode(resp.responseText).success;	
										if(resbool=='false')
										{
										    Ext.MessageBox.show({
											   title: 'Error',
											   msg: 'User Name already exists!',
											   buttons: Ext.MessageBox.OK,
											   icon:Ext.MessageBox.ERROR
									  		});
										
											simple.getForm().findField('username').reset();	
											}
									 			
							  }				
							});		
		}

	});	 


	if(formMode=='edit'){
	
	companyliststore.on({'load':{
			fn: function(store, options){
				simple.getForm().findField('company_id').setRawValue('<?php print $company_id; ?>');
				simple.getForm().findField('company_id').setValue('<?php print $company_id; ?>');	
			}
		}});
		
		simple.getForm().findField('username').setValue("<?php echo $user_name; ?>");
		simple.getForm().findField('password').setValue("<?php print $user_password; ?>");
		simple.getForm().findField('password1').setRawValue("<?php print $user_password; ?>");				
	} 			
   
});
</script>
</head>
<body>
<div id="tree-div"></div>
</body>
</html>
<?php require "_footer.php";?>