if(!w3d) var w3d = {};
if(!w3d.manager) w3d.manager = {};
if(!w3d.manager.user) w3d.manager.user = {};

var wmu = w3d.manager.user;

wmu.initManageUser = function() {
	var form = $('.userForm');
	
	wmu.getUserList(form);
	
	$('select.listBox', form).change(function() {
		wmu.selectUser(form, $(this).val());
	});
	$('.userFunc.create', form).click(function() {
		wmu.createUser(form);
	});
	$('.userFunc.modify', form).click(function() {
		wmu.modifyUser(form);
	});
	$('.userFunc.delete', form).click(function() {
		wmu.deleteUser(form);
	});
};

wmu.getUserList = function(form, selectedId) {
	var selector = $('select.listBox', form);
	
	$.ajax({
		url: '/manager/user/getlist',
		type: 'POST',
		cache: false,
		dataType: 'xml',
		async: false,
		success: function(xml) {
			var userList = $('Records', $(xml));
			
			selector.empty();
			$('Record', userList).each(function(i) {
				var userId = $(this).attr('ID');
				var userName = $(this).attr('Name');
				$("<option value='" + userId + "'>" + userName + "</option>").appendTo(selector);
			});
			wmu.selectUser(form, selectedId);
		},
		error: function() {
			alert('Loading user list has failed');
		}
	});
};

wmu.selectUser = function(form, selectedId) {
	var selector = $('select.listBox', form);
	var nameInput = $('#inp_userId', form);
	
	if ($('option', selector).length > 0) {
		var selectedOption;
		if (selectedId)
			selectedOption = $('option[value=' + selectedId + ']', selector);
		else
			selectedOption = $('option:first', selector);
			
		$('option', selector).removeAttr('selected');
		selectedOption.attr('selected', 'selected');
		nameInput.val(selectedOption.text());
		// userInfo에 selectedId 전달
		selectedId = selectedOption.val();
	}
	else {
		nameInput.val('');
		// userInfo에 selectedId로 -1을 전달 ( 선택된 유저가 없음을 의미 )
		selectedId = '-1';
	}
	
	//alert("사용자 정보 리셋!"); //선택 유저 : selectedId
	wmu.getUserInfo(form, selectedId);
};

wmu.getUserInfo = function(form, selectedId) {
	var usernameInput = $('#inp_userName', form);
	var passwdInput = $('#inp_userPassword', form);
	var profileNameInput = $('#inp_profileName', form);
	var userFabricCountInput = $('#inp_userFabrics', form);
	var userTypeInput = $('#permRadios', form);
	var clientGroupSelect = $('#sl_clientGroup', form);
	
	if (selectedId == '-1') {
		usernameInput.val('');
		passwdInput.val('');
		profileNameInput.val('');
		userFabricCountInput.val(0);
		$(':radio', userTypeInput).removeAttr('checked');
		$(':radio:first', userTypeInput).attr('checked', 'checked');
		
		return;
	}
	
	$.ajax({
		url: '/manager/user/getinfo',
		type: 'POST',
		cache: false,
		data: {uid: selectedId},
		dataType: 'json',
		async: false,
		success: function(response) {
			if (response['success']) {
				usernameInput.val(response['username']);
				passwdInput.val('');
				profileNameInput.val(response['profileName']);
				userFabricCountInput.val(response['userFabricCount']);
				$(':radio', userTypeInput).removeAttr('checked');
				$(':radio[value=' + response['userType'] + ']', userTypeInput).attr('checked', 'checked');
				clientGroupSelect.val(response['clientGroupId']);
			}
			else {
				switch (response['reason']) {
					case 'DoesNotExist':
						alert('Loading user information has failed : Does not exist');
						break;
					default:
						alert('Loading user information has failed : ' + response['reason']);
				}
				// getlist
			}
		},
		error: function() {
			alert('Loading user information has failed');
		}
	});
};

wmu.createUser = function(form) {
	var selector = $('select.listBox', form);
	
	var username = $('#inp_userName', form).val();
	var passwd = $('#inp_userPassword', form).val();
	var profileName = $('#inp_profileName', form).val();
	var userFabricCount = $('#inp_userFabrics', form).val();
	var userTypeInput = $('#permRadios', form);
	var userType = $(':radio:checked', userTypeInput).val();
	var clientGroupSelect = $('#sl_clientGroup', form);
	var clientGroupId = clientGroupSelect.val();
	
	var validationMsg = '';
	if (username.length == 0) {
		validationMsg += 'Input ID.\n';//'사용자 아이디를 입력하십시오.\n';
	}
	else if (username.length < 2) {
		validationMsg += 'ID must be at least 2 characters long.\n';//'사용자 아이디는 적어도 2자 이상이어야 합니다.\n';
	}
	if (passwd.length == 0) {
		validationMsg += 'Input password.\n';//'사용자 암호를 입력하십시오.\n'
	}
	else if (passwd.length < 4) {
		validationMsg += 'Password must be at least 4 characters long.\n';//'사용자 암호는 적어도 4자 이상이어야 합니다.\n';
	}
	if (profileName.length == 0) {
		validationMsg += 'Input name.\n';//'사용자 이름을 입력하십시오.\n'
	}
	else if (profileName.length < 2) {
		validationMsg += 'Name must be at least 2 characters long.\n';//'사용자 이름은 적어도 2자 이상이어야 합니다.\n';
	}
	if (userFabricCount.length > 0 && parseInt(userFabricCount, 10) != userFabricCount) {
		validationMsg += 'Upload Limit must have integer value.\n';//'사용자 원단 개수에는 정수값을 입력해야 합니다.\n';
	}
	if (validationMsg.length > 0) {
		alert(validationMsg);
		return;
	}
	
	$.ajax({
		url: '/manager/user/create',
		type: 'POST',
		cache: false,
		data: {username: username, passwd: passwd, profileName: profileName, userFabricCount: userFabricCount, userType: userType, cgid: clientGroupId},
		dataType: 'json',
		async: false,
		success: function(response) {
			if (response['success']) {
				wmu.getUserList(form, response['id']);
			}
			else {
				switch (response['reason']) {
					case 'NameAlreadyExists':
						alert('Creating user has failed : Already exists');
						break;
					default:
						alert('Creating user has failed : ' + response['reason']);
				}
			}
		},
		error: function() {
			alert('Creating user has failed');
		}
	});
};

wmu.modifyUser = function(form) {
	var selector = $('select.listBox', form);
	var selectedValue = selector.val();
	var selectedOption = $('option[value=' + selectedValue + ']', selector);
	
	var username = $('#inp_userName', form).val();
	var passwd = $('#inp_userPassword', form).val();
	var profileName = $('#inp_profileName', form).val();
	var userFabricCount = $('#inp_userFabrics', form).val();
	var userTypeInput = $('#permRadios', form);
	var userType = $(':radio:checked', userTypeInput).val();
	var clientGroupSelect = $('#sl_clientGroup', form);
	var clientGroupId = clientGroupSelect.val();
	
	var validationMsg = '';
	if (username.length > 0 && username.length < 2) {
		validationMsg += 'ID must be at least 2 characters long.\n';//'사용자 아이디는 적어도 2자 이상이어야 합니다.\n';
	}
	if (passwd.length > 0 && passwd.length < 4) {
		validationMsg += 'Password must be at least 4 characters long.\n';//'사용자 암호는 적어도 4자 이상이어야 합니다.\n';
	}
	if (profileName.length > 0 && profileName.length < 2) {
		validationMsg += 'Name must be at least 2 characters long.\n';//'사용자 이름은 적어도 2자 이상이어야 합니다.\n';
	}
	if (userFabricCount.length > 0 && parseInt(userFabricCount, 10) != userFabricCount) {
		validationMsg += 'Upload Limit must have integer value.\n';//'사용자 원단 개수에는 정수값을 입력해야 합니다.\n';
	}
	if (validationMsg.length > 0) {
		alert(validationMsg);
		return;
	}
	
	$.ajax({
		url: '/manager/user/modify',
		type: 'POST',
		cache: false,
		data: {uid: selectedValue, username: username, passwd: passwd, profileName: profileName, userFabricCount: userFabricCount, userType: userType, cgid: clientGroupId},
		dataType: 'json',
		async: false,
		success: function(response) {
			if (response['success']) {
				wmu.getUserList(form, selectedValue);
			}
			else {
				var failReasons = response['reason'];
				var errorMsg = '';
				
				if (failReasons.search('DoesNotExist') > -1) {
					errorMsg += 'Does not exist.\n';//' : 수정할 사용자가 존재하지 않습니다.\n';
				}
				if (failReasons.search('NameAlreadyExists') > -1) {
					errorMsg += 'Same name already exists.\n';//' : 동일한 이름의 사용자가 이미 존재합니다.\n';
				}
				if (failReasons.search('ItIsMyself') > -1) {
					errorMsg += 'Administrators can not deprive your own permission.\n';//' : 관리자 본인의 권한을 해제할 수 없습니다.\n';
				}
				if (failReasons.search('NoChanges') > -1) {
					errorMsg += 'No changes.\n';//' : 변경 사항이 없습니다.\n';
				}
				alert('Modifying user information has failed\n' + errorMsg);
			}
		},
		error: function() {
			alert('Modifying user information has failed');
		}
	});
};

wmu.deleteUser = function(form) {
	var selector = $('select.listBox', form);
	var selectedValue = selector.val();
	var selectedOption = $('option[value=' + selectedValue + ']', selector);
	
	if (selectedOption.length == 0 || !confirm("Delete [" + selectedOption.text() + "]?")) {
		return;
	}
	
	$.ajax({
		url: '/manager/user/delete',
		type: 'POST',
		cache: false,
		data: {uid: selectedValue},
		dataType: 'json',
		async: false,
		success: function(response) {
			if (response['success']) {
				wmu.getUserList(form);
			}
			else {
				switch (response['reason']) {
					case 'DoesNotExist':
						alert('Deleting user has failed\n : Does not exist');
						break;
					case 'ItIsMyself':
						alert('Deleting user has failed\n : Administrators can not delete your own');
						break;
					default:
						alert('Deleting user has failed : ' + response['reason']);
				}
			}
		},
		error: function() {
			alert('Deleting user has failed');
		}
	});
};