/////////////////////////////////////////////////////////////////////////////////////////
// subgrids.js
// Watch My Domains SED v3
// (c) Softnik Technologies. All rights reserved.
/////////////////////////////////////////////////////////////////////////////////////////

$(function() 
{
	LoadUserGrid();
	initEnterKeyHandler('useradmin-adminpassword-confirm', 'superadmin-update');
	initEnterKeyHandler('userselfadmin-password-confirm', 'userselfadmin-update');
	$('#superadmin-update').click(function(event) {saveAdminUser();});
	$('#useradmin-update').click(function(event) {saveUserData();});
	$('#userselfadmin-update').click(function(event) {saveUserPassword();});
	showUserData(null);
	
});

/////////////////////////////////////////////////////////////////////////////////////////

var current_user_id = 0;

/////////////////////////////////////////////////////////////////////////////////////////

function LoadUserGrid()
{
	jQuery("#UserTable").jqGrid({
		url: base_grid_ajax_url + '?' + DGA_USER_GRID,
		editurl: base_grid_ajax_url + '?' + DGA_USER_GRID_EDIT,
		datatype: "json",
		altRows:true,
		altclass: "gridAltRowClass",
		colNames:['User Name', 'Password', 'Active','Access', 'Display Name'],
		colModel:[
			{name:'name',index:'name', width:110, sortable:true, editable:true,editrules:{custom:true, custom_func:string_length_check}},
			{name:'password',index:'password', width:0, hidden:true,editable:true,edittype:"password",editrules:{edithidden:true,custom:true, custom_func:string_length_check}},
			{name:'active',index:'active', width:60, sortable:true, fixed: true, align:'center',formatter:'checkbox',editable:true,edittype:"checkbox",editoptions:{value:"Yes:No"}},
			{name:'readwrite',index:'readwrite', width:80, sortable:true, align:'center', editable:false, fixed: true},
			{name:'display_name',index:'display_name', width:10, hidden:true, editable:false}
		],
		rownumbers: true,
		rowNum: 250,
		rowList:[],
		pgbuttons: false,
		pgtext: null,
		height: '300',
		width: 950,
		pager: '#UserPager',
		sortname: 'id',
		caption:"",
		viewrecords: false,
		sortorder: "desc",
		multiselect: false,
		multiboxonly:false,
		shrinkToFit: true,
		onSelectRow: function(ids) 	{showUserData(ids);},
		scrollOffset: 36
		});
		jQuery("#UserTable").jqGrid('navGrid','#UserPager',{search:false,edit:false,add:true,del:true
		},
		{ // edit option
			  beforeShowForm: function(form) { $('#tr_name', form).hide(); }
		},
		{ // add option
		  // beforeShowForm: function(form) { $('#tr_name', form).show(); }
			width: 'auto',
			closeOnEscape:true,
			closeAfterAdd: true,
			afterShowForm: function(form) 
			{
				centerDialog('editmodUserTable');
				setGridDialogColors();
			},
			afterComplete:function() 
			{
				$('#useradmin-error').html('');
			}
		},
		{	// Delete
			width: 'auto',
			closeOnEscape:true,
			afterShowForm: function(form) 
			{
				centerDialog('delmodUserTable');
				setGridDialogColors();
			},
			afterComplete:function() 
			{
				current_user_id = 0;
				showUserData(0);
				$('#useradmin-error').html('');
			}
		}
		);
}

/////////////////////////////////////////////////////////////////////////////////////////

function showUserData(ids)
{
	if(ids == null || ids == 0)
	{
		$('#username').html("");
		current_user_id = 0;
		$('#useradmin-dname').val('');
		$('#useradmin-password').val('');
		$('#useradmin-active').prop('checked', false);
		$('#useradmin-administrator').prop('checked',false);
	}
	else
	{
		current_user_id = ids;
		var username = jQuery("#UserTable").getCell(ids, "name"); 
		$('#username').html(username);
		var gurl = "lib/php/ajax/appsetup.php?" + ASA_GET_USER_DETAILS + "=" + ids;
		$.ajax({
			type: 'POST',
			url: gurl,
			cache: false
		}).done(function(data) {
			var x = jQuery.parseJSON(data);
			if(x.validate == 1)
				sessionRestart("timeout");
			else if(x.validate == -1)
				sessionRestart("badsession");
			else if(x.status == "ok")
			{
				showUserPermissions(x.permissions);
				$('#useradmin-active').prop('checked', x.active);
				$('#useradmin-readwrite').val(x.rw);
				$('#useradmin-dname').val(x.dname);
				$('#useradmin-administrator').prop('checked', x.admin);
			}
		}
		).fail(function(jqXHR,status, errorThrown) 
		{
			if(jqXHR.status == 403)
				custom_alert("Access Denied! No permission to edit.", "Problem");
			else if(jqXHR.status == 400)
				custom_alert("Invalid Session. Please login again.", "Problem");
			else if(jqXHR.status == 408)
				custom_alert("Session timeout. Please login again.", "Problem");
		});	
	}
}

/////////////////////////////////////////////////////////////////////////////////////////

function positionUserAdminWindow()
{
	if(!user_auth_exists)
	{
		$('#useradminbox').fadeTo('slow',.6);
		$('#useradminbox').append('<div style="position: absolute;top:0;left:0;width: 100%;height:100%;z-index:2;opacity:0.4;filter: alpha(opacity = 50)"></div>');
	}
	if(basic_auth_mode)
	{
		$('#useradminbox').hide();
		$('#superadminbox').css('border-width', 0);
		$('#superadminbox').css('margin-bottom', 0);
		$('#superadminbox').css('padding-bottom', 0);
	}
	
	var dtw = $('#usertablebox').width();
	jQuery("#UserTable").setGridWidth(dtw, true); 
	
	var dth = $('#useradmin-infobox').height();
	if($(window).width() < 768) 
		dth = 200;
	jQuery("#UserTable").setGridHeight(dth-60); 
}

/////////////////////////////////////////////////////////////////////////////////////////

function string_length_check(value, colname) 
{
	len = value.length;
	if (len < 6) 
	   return [false, colname + ": Please enter atleast 6 characters."];
	else 
	   return [true,""];
}

/////////////////////////////////////////////////////////////////////////////////////////

function onAfterUserAdminWindowPopup()
{
	positionUserAdminWindow();
	setDefaultFontSizes();
	$('#useradmin-error').html('');
	
	var gurl = "lib/php/ajax/appsetup.php?" + ASA_GET_USER_ADMIN_DATA;
	$.ajax({
		type: 'POST',
		url: gurl,
		cache: false
	}).done(function(data) {
		var x = jQuery.parseJSON(data);
		if(x.validate == 1)
			sessionRestart("timeout");
		else if(x.validate == -1)
			sessionRestart("badsession");
		else
		{
			$('#useradmin-category').html(x.catlist);
			$('#useradmin-admin').val(x.saname);
			$('#cbuaselectall').change(function () 
			{
				$('.cbua').each(function() 
				{
					$('#'+this.id).prop('checked', $('#cbuaselectall').is(':checked'));
				});
			});
		}
	}
	).fail(function(jqXHR,status, errorThrown) 
	{
		if(jqXHR.status == 403)
			custom_alert("Access Denied! No permission to edit.", "Problem");
		else if(jqXHR.status == 400)
			custom_alert("Invalid Session. Please login again.", "Problem");
		else if(jqXHR.status == 408)
			custom_alert("Session timeout. Please login again.", "Problem");
	});
}

/////////////////////////////////////////////////////////////////////////////////////////

function saveAdminUser()
{
	$('#useradmin-error').html('');
	
	var adminremoved = false;
	var admuser = $('#useradmin-admin').val();
	var admpass01 = $('#useradmin-adminpassword').val();
	var admpass02 = $('#useradmin-adminpassword-confirm').val();
	if(admpass01 == "" && admpass02 == "" && admuser == "")
	{
		adminremoved = true;
	}
	else
	{
		if(admpass01 !== admpass02)
		{
			$('#useradmin-error').html("Administrator Passwords don't match");
			return;
		}
		if(admpass01 == "" || admpass01.length < 8)
		{
			$('#useradmin-error').html("Administrator Passwords should have minimum 8 characters.");
			return;
		}
		if(admuser != "" && admuser.length < 5)
		{
			$('#useradmin-error').html("Admin user name should have minimum 5 characters.");
			return;
		}
	}
	
	var gurl = "lib/php/ajax/appsetup.php?" + ASA_SAVE_SUPER_ADMIN;
	var datastr = "user=" + encodeURIComponent(admuser) + "&pass=" + encodeURIComponent(admpass01);
	$.ajax({
		type: 'POST',
		url: gurl,
		data: datastr,
		cache: false
	}).done(function(data) {
		var x = jQuery.parseJSON(data);
		if(x.validate == 1)
			sessionRestart("timeout");
		else if(x.validate == -1)
			sessionRestart("badsession");
		else if(x.status == "ok")
		{
			$('#useradmin-error').html("Super administrator details saved");
			if(adminremoved)
				alert_and_exec("You have removed password protection for this application. It will now reload.", logout);
			else if(user_auth_exists == false)
				logout();
		}
		else
			$('#useradmin-error').html(x.error);
	}
	).fail(function(jqXHR,status, errorThrown) 
	{
		if(jqXHR.status == 403)
			custom_alert("Access Denied! No permission to edit.", "Problem");
		else if(jqXHR.status == 400)
			custom_alert("Invalid Session. Please login again.", "Problem");
		else if(jqXHR.status == 408)
			custom_alert("Session timeout. Please login again.", "Problem");
	});
}

/////////////////////////////////////////////////////////////////////////////////////////

function logout()
{
	window.location = "main.php?logout";
}

/////////////////////////////////////////////////////////////////////////////////////////

function saveUserData()
{
	$('#useradmin-error').html('');
	if(current_user_id <= 0)
	{
		$('#useradmin-error').html('Please select a user.');
		return;
	}
	var pass = $('#useradmin-password').val();
	if(pass != "")
	{
		if(pass.length < 6)
		{
			$('#useradmin-error').html('User passwords should be 6 characters or more.');
			return;
		}
	}
		
	var permids = "";
	$('.cbua').each(function() 
	{
		if($('#'+this.id).prop('checked'))
		{
			var cid = this.id.replace("cbua", "");
			if(permids != "")
				permids += ",";
			permids += cid;
		}
	});
	
	var gurl = "lib/php/ajax/appsetup.php"; 
	var datastr = "perms=" + permids;
	datastr += "&" + ASA_SAVE_USER_DETAILS + "=" + current_user_id;
	datastr += "&active=" + $('#useradmin-active').prop('checked');
	datastr += "&admin=" + $('#useradmin-administrator').prop('checked');
	datastr += "&rw=" + $('#useradmin-readwrite').prop('selectedIndex');
	datastr += "&dname=" + encodeURIComponent($('#useradmin-dname').val());
	datastr += "&p=" + encodeURIComponent($('#useradmin-password').val());
	$.ajax({
		type: 'POST',
		url: gurl,
		data: datastr,
		cache: false
	}).done(function(data) {
		var x = jQuery.parseJSON(data);
		if(x.validate == 1)
			sessionRestart("timeout");
		else if(x.validate == -1)
			sessionRestart("badsession");
		else if(x.status == "ok")
		{
			$('#useradmin-error').html("User details saved");
			showUserPermissions(x.permissions);
			$('#useradmin-active').prop('checked', x.active);
			$('#useradmin-readwrite').val(x.rw);
			$('#useradmin-dname').val(x.dname);
			$('#useradmin-administrator').prop('checked', x.admin);
		}
		else
			$('#useradmin-error').html(x.error);
		$("#UserTable").trigger("reloadGrid");
			
	}
	).fail(function(jqXHR,status, errorThrown) 
	{
		if(jqXHR.status == 403)
			custom_alert("Access Denied! No permission to edit.", "Problem");
		else if(jqXHR.status == 400)
			custom_alert("Invalid Session. Please login again.", "Problem");
		else if(jqXHR.status == 408)
			custom_alert("Session timeout. Please login again.", "Problem");
	});
}

/////////////////////////////////////////////////////////////////////////////////////////

function saveUserPassword()
{
	$('#userselfadmin-error').html('');
	var pass01 = $('#userselfadmin-password').val();
	var pass02 = $('#userselfadmin-password-confirm').val();
	if(pass01 !== pass02)
	{
		$('#userselfadmin-error').html("Passwords don't match");
		$('#userselfadmin-password-confirm').val('');
		return;
	}
	if(pass01 == "" || pass01.length < 6)
	{
		$('#userselfadmin-error').html("Passwords should have minimum 6 characters.");
		$('#userselfadmin-password').val('');
		$('#userselfadmin-password-confirm').val('');
		return;
	}
	var gurl = "lib/php/ajax/appsetup.php?" + ASA_SET_USER_PASSWORD + "=" + encodeURIComponent(pass01);
	$.ajax({
		type: 'POST',
		url: gurl,
		cache: false
	}).done(function(data) {
		var x = jQuery.parseJSON(data);
		if(x.validate == 1)
			sessionRestart("timeout");
		else if(x.validate == -1)
			sessionRestart("badsession");
		else if(x.status == "ok")
		{
			$('#userselfadmin-error').html("Password changed");
		}
		else
			$('#userselfadmin-error').html(x.error);
	}
	).fail(function(jqXHR,status, errorThrown) 
	{
		if(jqXHR.status == 403)
			custom_alert("Access Denied! No permission to edit.", "Problem");
		else if(jqXHR.status == 400)
			custom_alert("Invalid Session. Please login again.", "Problem");
		else if(jqXHR.status == 408)
			custom_alert("Session timeout. Please login again.", "Problem");
	});
}

/////////////////////////////////////////////////////////////////////////////////////////

function showUserPermissions(perms)
{
	$('.cbua').each(function() 
	{
		$('#'+this.id).prop('checked', false);
	});
	for(i = 0; i < perms.length; i++)
	{	
		var cid = perms[i].id;
		$('#cbua'+cid).prop('checked', true);
	}
}

/////////////////////////////////////////////////////////////////////////////////////////
