<?php
ini_set('max_execution_time', 300);
	require "_header.php";
	require "commonincludefiles.php";
	$section = "smsn";

	if($_REQUEST["ID"]!="" && isset($_REQUEST["ID"])){
		$user_id = Escape($_REQUEST["ID"]);
		$mode="edit";

		if($EDIT == "false"){
			redirectToPage();
		}
		$section .= ",".$user_id;

		$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"];
			$moduleids = $row["module_ids"];
			$menuids = $row["menu_ids"];
			$pageids = $row["page_ids"];
			//$user_role = $row["user_role"];
			//echo $menuids;
		}
	}
	else{
		$mode="add";
		if($ADD == "false"){
			redirectToPage();
		}
		$user_id=0;
		$moduleids = "";
		$menuids = "";
		$pageids = "";
	}
?>

<script type="text/javascript">
Ext.onReady(function(){
    var varpath='';
    var UType = '';
    var formMode ="";
    var user_id 	= "";
    var moduleids 	= "";
    var menuids 	= "";
    var pageids 	= "";
    var UserType    = "";

    var labelArray;
		labelArray = [['Username :<span class="comp">*</span>'],
			 	      ['Password :<span class="comp">*</span>'],
				      ['Confirm Password :<span class="comp">*</span>'],
					    ['Power User :<span class="comp"></span>']
					  ];

	 formMode 	= '<?php echo $mode;?>';
     user_id 	= '<?php echo $user_id;?>';
	 moduleids 	= '<?php echo $moduleids;?>';
     menuids 	= '<?php echo $menuids;?>';
     pageids 	= '<?php echo $pageids;?>';



	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.'
	});



    varpath =  'get-user-access-tree.php?userid='+user_id+'&moduleid='+moduleids+'&menuid='+menuids+'&pageid='+pageids;

	var tree = new Ext.tree.TreePanel({
        useArrows:true,
        autoScroll:true,
        animate:true,
        enableDD:true,
        loadMask: true,
        containerScroll: true,
        rootVisible: true,
	 	animCollapse: true,
		setRootNode : function(node){
			this.root = node;
			node.ownerTree = this;
			if(moduleids != ""){
				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,
                        requestMethod: 'POST',
						baseAttrs: { uiProvider: Ext.ux.TreeCheckNodeUI },
						listeners: {'beforeload':function(){

								//	Ext.MessageBox.wait('Loading your data, please wait...', 'Data Load')
								
					            },
					            'load':function()
					            {
					            	//Ext.MessageBox.hide();
					            	//alert('Loading data Successfully');
					            	//Ext.getCmp('btnSave').enable();
						        }
							}
						 //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();
					}
				}
				
			},
			'beforeload':function(node){

					Ext.MessageBox.wait('Loading your data, please wait...', 'Data Load')
			//				 	Ext.getCmp('btnSave').disable();	

			},
            'load':function(node)
            {
            	Ext.MessageBox.hide();
            	Ext.getCmp('btnSave').enable();
				
            }
	    }
	});

		root = new Ext.tree.AsyncTreeNode({
		text: 'COLLEGE MANAGEMENT SYSTEM',
		draggable:false,
		id:'node-root',
		uiProvider: Ext.ux.TreeCheckNodeUI
	});

	tree.setRootNode(root);
	root.expand();


	/*root.cascade(function(n){
	  loader.doPreload(n);
	  n.loaded=true;
	  n.ui.updateExpandIcon();
	});*/


	var simple = new Ext.FormPanel({
        labelWidth: 117,
        url:'save-user.php?ID=<?php echo $user_id ; ?>',
        frame:true,
		autoScroll:true,
        bodyStyle:'padding:5px 5px 0',
        width:500,
		height:410,
        defaultType: 'textfield',
		items :[
				{
					xtype: 'textfield',
					labelSeparator:'',
					fieldLabel :labelArray[0] ,
					name: 'username',
					width:190
					,allowBlank:false
				},{
					labelSeparator:'',
					fieldLabel :labelArray[1] ,
					name:'password',
					width:190,
					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',
					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[3],
					name:'poweruser',
					id:'poweruser',
					tabIndex:5,
					width:190,
					allowBlank:true,
					handler: function(){
	                       // alert(Ext.getCmp('faculty').getValue(checked = true));
							if(Ext.getCmp('faculty').getValue(checked = true))
							{
								Ext.getCmp('hod').setValue(checked = false);
								Ext.getCmp('faculty').setValue(checked = false);
							}
							
						}
				},
				{
					labelSeparator:'',
					xtype: 'checkbox',
					fieldLabel :'HOD',
					name:'hod',
					id:'hod',
					value:'HOD',
					hidden:false,
					tabIndex:5,
					width:190,
					allowBlank:true,
					handler: function(){
                        // alert(Ext.getCmp('faculty').getValue(checked = true));
						if(Ext.getCmp('hod').getValue(checked = true) && formMode != 'edit')
						{
							if(Ext.getCmp('faculty').getValue(checked = true) || Ext.getCmp('poweruser').getValue(checked = true) )
							{
								Ext.getCmp('faculty').setValue(checked = false);
								Ext.getCmp('poweruser').setValue(checked = false);
							}
							menuids = '<?php echo $HODMenuRights;?>';
                            pageids=  '<?php  echo $HODPageRights;?>';
                            moduleids = '1,3';
                            tree.show();
                            tree.getLoader().dataUrl = 'get-user-access-tree.php?userid='+user_id+'&moduleid='+moduleids+'&menuid='+menuids+'&pageid='+pageids;
                            tree.getRootNode().reload();
                            tree.getRootNode().checked=true;
                            tree.getRootNode().expand(true);
                            tree.getLoader().load();
                            
						}
						else
						{
                       		
					    	menuids 	= '<?php echo $menuids; ?>';
                            pageids 	= '<?php echo $pageids; ?>';
                            moduleids 	= '<?php echo $moduleids; ?>';
                            tree.show();
                            tree.getLoader().dataUrl = 'get-user-access-tree.php?userid='+user_id+'&moduleid='+moduleids+'&menuid='+menuids+'&pageid='+pageids;
                            tree.getRootNode().reload();
                            tree.getRootNode().checked=true;
							tree.getLoader().load();
	                            
						}
						
						
					    
					 }
				},{
					labelSeparator:'',
					 xtype: 'checkbox',
					fieldLabel :'Faculty',
					name:'faculty',
					id:'faculty',
					value:'Faculty',
					hidden:false,
					tabIndex:5,
					width:190,
					allowBlank:true,
					handler: function(){
                       // alert(Ext.getCmp('faculty').getValue(checked = true));
                       	if(Ext.getCmp('faculty').getValue(checked = true) && formMode != 'edit' )
						{
    						if(Ext.getCmp('hod').getValue(checked = true) ||
								Ext.getCmp('poweruser').getValue(checked = true))
							{
								Ext.getCmp('hod').setValue(checked = false);
								Ext.getCmp('poweruser').setValue(checked = false);
									
							}
							menuids = "<?php echo $FacultyMenuRights; ?>";
                            pageids = "<?php echo $FacultyPageRights; ?>";
                            moduleids = '1,3';

                            tree.show();
                            tree.getLoader().dataUrl = 'get-user-access-tree.php?userid='+user_id+'&moduleid='+moduleids+'&menuid='+menuids+'&pageid='+pageids;
                            tree.getRootNode().reload();
                            tree.getRootNode().expand(true);
                            tree.getLoader().load();
                            tree.getRootNode().checked = false;
						}
                       	else
						{
                       		
					    	menuids 	= '<?php echo $menuids; ?>';
                            pageids 	= '<?php echo $pageids; ?>';
                            moduleids   = '<?php echo $moduleids; ?>';
                            tree.show();
                            tree.getLoader().dataUrl = 'get-user-access-tree.php?userid='+user_id+'&moduleid='+moduleids+'&menuid='+menuids+'&pageid='+pageids;
                            tree.getRootNode().reload();
                            tree.getRootNode().checked=true;
							tree.getLoader().load();
	                            
						}
					}
				},tree,{
					name: 'msgv',
					id:'msgv',
					hiddenName: 'msgv',
					hidden: true
				},{
					name: 'cn',
					id:'cn',
					hiddenName: 'cn',
					hidden: true
				},{
					name: 'msgSectionTree',
					id:'msgSectionTree',
					hiddenName: 'msgSectionTree',
					hidden: true
				}

			]
	});

	var UserAddEditWindow = new Ext.Window({
		title: 'Create User',
		width:450,
		autoHeight:true,
		modal:true,
		border: false,
		layout: 'fit',
		closeAction:'close',
		collapsible:true,
		items: simple,
		buttonAlign: 'center',
		buttons:[
			{
				text: 'Save',
				name:'btnSave',
				id:'btnSave',
				disabled:true,
				handler: function(){
					var msg = "" , selNodes = tree.getChecked();
					Ext.each(selNodes, function(node){
						if(msg.length > 0){
							msg += ', ';
						}
						msg += node.id;
					});
					simple.getForm().findField('msgv').setValue(msg);
					simple.getForm().submit({
						waitMsg: 'Saving...',
						success: function (){
							Ext.MessageBox.show({
								   title: 'Message',
								   msg: 'User saved successfully.',
								   buttons: Ext.MessageBox.OK,
								   icon:Ext.MessageBox.INFO
							});
							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',
				name:'btnReset',
				id:'btnReset',
				handler: function (){
					var msg = Ext.getCmp('cn').getValue();
					simple.getForm().reset();
					tree.collapseAll();
					tree.getRootNode().expand();
				}
			},{
				text: 'Close',
				name:'btnClose',
				id:'btnClose',
				handler: function (){
					UserAddEditWindow.hide();
				}
			},{
				text: 'Expand All',
				name:'btnexpand',
				id:'btnexpand',
				handler: function (){
					tree.expandAll();
				}
			},{
				text: 'Collapse All',
				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();
	simple.getForm().findField('username').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();
		  }
});
	if(formMode=='edit'){
		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; ?>");
		<?php if($user_role =='Faculty')
		{ ?>
		simple.getForm().findField('faculty').setValue(1);
		<?php }?>

		<?php if($user_role =='PowerUser')
		{ ?>
		simple.getForm().findField('poweruser').setValue(1);
		<?php }?>
		Ext.getCmp('btnReset').disable();
	}

});
</script>
<div align="center"><div id="main-content" align="left"><div id="tree-div"></div></div></div>

<?php require "_footer.php"; ?>