<script type="text/javascript">
	/* table data */
	var addressList 				= [];
	var familyList 					= []; 
	var academicList 				= [];
	var additionalPersonalList 		= [];
	var prevEmpList 				= [];
	var proMembershipList 			= [];
	var proLicenseList 				= [];
	var recognitionList 			= [];
	var bankList 					= [];
	var recurList 					= [];
	var thirdPartyList 				= [];
	var pcbList						= [];
	var eipList						= [];
	var ecList						= [];
	var proEducationList			= [];
	var proCertificateList			= [];
	
$(document).ready(function(){
	console.log('document ready 1');
	console.log('not success actionType');
	actionType(); 		//init action type based on infotype
	console.log('success actionType');
	isFamilyStudent(); 	//init form occupation based on student status
	formConstruct();	//init form based on selected action type id
}); 

$('#action_type_form').on('submit', function(e){
	e.preventDefault();
	$('#btn-submit-form').prop('disabled','disabled');
	
	var form = formDataCleanUp(formIdToInputObject('#action_type_form'));
	var data = {
		token:'<?php echo $_SESSION['token'];?>',
		form:form,
		uri:'<?php echo $this->uri->segment(3); ?>',
		param:'<?php echo $this->uri->segment(4); ?>',
	}

	var url 		= '<?php echo base_url('hr/api/staffprofiling/actionProfile'); ?>';
	if(data.uri == 'new_action_type')
	{
		var redirect 	= '<?php echo base_url('hr/StaffProfile/StaffDetail/').$staff['id']; ?>';
	}
	if(data.uri == 'mysetting'){
		var redirect 	= '<?php echo base_url('admin/user/mysetting/').$staff['id']; ?>';
	}
	if(data.uri == 'setting'){
		var redirect 	= '<?php echo base_url('admin/user/setting/').$staff['id']; ?>';
	}

	$.ajax({
		url: url,
		type: 'POST',
		data:data,
		dataType: 'JSON',
		success: function(data){
			localStorage.setItem("status",data.status);
			localStorage.setItem("msg",data.msg);
			
			if (localStorage.getItem("status") != null) {
				if(localStorage.getItem("status").toLowerCase() == 'success')
				{
					iziToast.success({
						position: 'bottomRight',
						title: localStorage.getItem("status"),
						message: localStorage.getItem("msg")
					});
					if(redirect) location.replace(redirect);
				}
				if(localStorage.getItem("status").toLowerCase() == 'error')
				{
					iziToast.error({
						position: 'bottomRight',
						title: localStorage.getItem("status"),
						message: localStorage.getItem("msg")
					});
				}
				localStorage.clear();
			}
		}
	});

});



/*
	hide and unhide infotype in the forms
*/
function infoType(elem) {
	var forms = $(elem).data('form');
	var is_check = $(elem).prop('checked');
	if(is_check){
		$('#'+forms).removeClass('d-none');
	}else{
		$('#'+forms).addClass('d-none');
	}
}

/*
	object building on which items will be submitted during ajax request
	only checked infotype will be submitted using ajax request
*/
function formDataCleanUp(obj){
	var container = [];

	var main_form = {
		info_type : -1,
		user_id : obj.user_id,
		staff_id : obj.staff_id,
		action_type : obj.action_type,
		efective_date : obj.efective_date,
		title : obj.title,
		gender : obj.gender,
		ic_no : obj.nric,
		passport_expired_date : obj.passport_expired_date,
		working_expired_date : obj.working_expired_date,
		passport_issued_country : obj.passport_issue_country,
		staff_phone : obj.staff_phone,
		staff_ext_no : obj.staff_ext_no,
		birth_date : obj.staff_birthdate,
		birth_place : obj.staff_birthplace,
		hobby : obj.staff_hobby,
		nationality : obj.staff_nationality,
		religion : obj.staff_religion,
		race : obj.staff_race,
		residential_status : obj.residential_status,
		marital_status : obj.marital_status,
		married_date : obj.married_date,
		primary_email : obj.primary_email,
		secondary_email : obj.secondary_email
	}

	container.push(main_form);
	/*  ------------------check if join group checked--  */
	if(obj.join_group_checkbox){
		var join_group = {
			info_type:0,
			info_type_name: 'join_group',
			value : true,
			hiring_reason: obj.join_group_reason_hiring,
			hiring_position : obj.join_group_position,
			position_id : obj.join_group_position_information,
			position_information : obj.join_group_position_information,
			employee_grade : obj.join_group_position_grade,
			reporting_to : obj.join_group_reporting_to,
			branch:obj.join_group_branch,
			personnel_area  : obj.join_group_personnel_area,
			personal_subarea: obj.join_group_personal_subarea,
			emp_group:obj.join_group_employee_group,
			contract_type:obj.join_group_contract_element,
			emp_subgroup:obj.join_group_employee_subgroup,
			status:obj.join_group_employment_status,
			business_entity : obj.join_group_business_entity,
		}
		container.push(join_group);
	}

	/* --------check if address is checked-------------- */
	if(obj.address_checkbox){
		var address = {
			info_type:1,
			info_type_name:'address',
			value: true,
			list: addressList,
		}

		container.push(address);
	}

	/* ----------check if family info is checked-------- */
	if (obj.family_info_checkbox) {
		var family_info = {
			info_type:2,
			info_type_name:'family info',
			value: true,
			list:familyList,
		}
		container.push(family_info);
	};

	/* -----check if academic qualification is checked-- */
	if (obj.academic_qualification_checkbox) {
		var academic = {
			info_type:3,
			info_type_name:'academic education',
			value:true,
			list:academicList,
		}
		container.push(academic);
	};

	/* ---check if additional personal data is checked-- */
	if (obj.additional_personal_data_checkbox) {
		var personal_data = {
			info_type:4,
			info_type_name:'additional personal data',
			value:true,
			list:additionalPersonalList,
		}
		container.push(personal_data);
	};

	/* -check if employment detail is checked----------- */
	if(obj.employment_detail_checkbox){
		var prev_emp = {
			info_type:5,
			info_type_name:'previous employment detail',
			value:true,
			list:prevEmpList
		}
		container.push(prev_emp)
	}
	
	/* ---check if professional membership is checked--- */
	if(obj.professional_membership_checkbox){
		var pro_membership = {
			info_type:6,
			info_type_name:'professional membership',
			value:true,
			list:proMembershipList
		}
		container.push(pro_membership);
	}

	/* --check if professional licenses is checked----- */
	if(obj.professional_licenses_checkbox){
		var pro_license = {
			info_type:7,
			info_type_name:'professional licenses',
			value:true,
			list:proLicenseList
		}
		container.push(pro_license);
	}

	/* -----check if recognition is checked----------- */
	if(obj.recognition_checkbox){
		var pro_license = {
			info_type:8,
			info_type_name:'recognition',
			value:true,
			list:recognitionList
		}
		container.push(pro_license);
	}

	/*-------------------------------------------------*/
	if(obj.contract_element_checkbox){
		var contract = {
			info_type:9,
			info_type_name:'contract element',
			value:true,
			user_id:obj.user_id,
			contract_type:obj.contract_type,
			confirmation:obj.contract_confirmation,
			duration:obj.contract_duration,
			confirmation_date:obj.contract_confirmation_date,
			probationary_period:obj.contract_probationary_period,
			probationary_period_type:obj.contract_probationary_period_type,
			employer_notice_period:obj.contract_employer_notice_period,
			employer_notice_period_type:obj.contract_employer_notice_type,
			employee_notice_period:obj.contract_employee_notice_period,
			employee_notice_period_type:obj.contract_employee_notice_type,
			confirmation_reminder:obj.confirmation_reminder, //farid 5/10/20
			resign_date:obj.resign_date,
			last_working_date:obj.last_working_date,
			phy_last_working_date:obj.phy_last_working_date,

		}
		container.push(contract);
	}

	/*-------------------------------------------------*/
	if(obj.basic_pay_checkbox){
		var basic_pay = {
			info_type:10,
			info_type_name:'basic pay',
			value:true,
			user_id:obj.user_id,
			scale_group:obj.basic_pay_scale_group,
			amount:obj.basic_pay_amount,
			start_date:obj.basic_pay_date_start,
			end_date:obj.basic_pay_date_end,
			reason:obj.basic_pay_reason,
			status:obj.basic_pay_status,
		}
		container.push(basic_pay);
	}

	/*------------------------------------------------*/
	if(obj.bank_detail_checkbox){
		var bank = {
			info_type:11,
			info_type_name:'bank details',
			value:true,
			list:bankList,
		}

		container.push(bank);
	}

	/*----------------------------------------------*/
	if(obj.statutory_detail_checkbox){
		var statutory = {
			info_type:12,
			info_type_name:'statutory details',
			value:true,
			user_id:obj.user_id,
			status:obj.statutory_status,
			year:obj.statutory_year,
			employee_epf_no:obj.statutory_epf_no,
			employee_rate:obj.statutory_ee_rate,
			employee_amount_percent:obj.statutory_ee_percent,
			employer_rate:obj.statutory_er_rate,
			employer_amount_percent:obj.statutory_er_percent,
			employee_socso_no:obj.statutory_socso,
			employee_income_tax_no:obj.statutory_income_tax,
			employee_pcb_deduction:obj.statutory_pcb_deduction,
			employee_zakat_deduction:obj.statutory_zakat_deduction,
			employee_pcb_deduction_percent:obj.statutory_pcb_deduction_percent,
			employee_zakat_deduction_percent:obj.statutory_zakat_deduction_percent,
		}
		container.push(statutory);
	}

	/*----------------------------------------------*/
	if(obj.recurring_pay_checkbox){
		var recurring = {
			info_type:13,
			info_type_name:'recurring pay / deduction',
			value:true,
			list:recurList,
		}

		container.push(recurring);
	}

	/*----------------------------------------------*/
	if(obj.third_party_checkbox){
		var third_party = {
			info_type:14,
			info_type_name:'third party payment',
			value:true,
			list:thirdPartyList,
		}
		container.push(third_party);
	}

	/*---------------------------------------------*/
	if(obj.pcb_checkbox){
		var pcb = {
			info_type:15,
			info_type_name:'pcb consideration',
			value:true,
			list:pcbList
		}

		container.push(pcb);
	}

	/*--------------------------------------------- newly add */
	if(obj.education_in_progress_checkbox){
		var eip = {
			info_type:16,
			info_type_name:'education in progress',
			value:true,
			list:eipList
		}

		container.push(eip);
	}

	/*--------------------------------------------- newly add */
	if(obj.emergency_contact_checkbox){
		var ec = {
			info_type:17,
			info_type_name:'emergency contact',
			value:true,
			list:ecList
		}

		container.push(ec);
	}

	/*--------------------------------------------- newly add */
	if(obj.professional_education_checkbox){
		var proEducation = {
			info_type:18,
			info_type_name:'professional education',
			value:true,
			list:proEducationList
		}

		container.push(proEducation);
	}

	/*--------------------------------------------- newly add */
	if(obj.professional_certificate_checkbox){
		var proCertificate = {
			info_type:19,
			info_type_name:'professional certificate',
			value:true,
			list:proCertificateList
		}

		container.push(proCertificate);
	}

	return container; 
}


/*
	make all infotype follow the value of all[master] infotype checkbox
*/
function allType() {
	var all_info = $('#all-checkbox').prop('checked');
 	$.each($('input[type="checkbox"]'),function(index,value){
 		if(all_info != $(value).prop('checked')){
 			$(value).trigger('click');
 		}
 	});
}


function actionType(){
	console.log('function actionType run');
	var action_type 	= $('#action-type').val();	
	var workflowB64 	= $('#workflowSelect').find(':selected').data('workflow');
	var workflowJSON  	= JSON.parse(atob(workflowB64));
	console.log("workflowJSON => "+workflowJSON);
	
	$(workflowJSON).each(function(index,row){
		if(action_type == index){
				console.log('action type : '+action_type);
				console.log('index : '+index);
				console.log(row);

<?php /*akmal 20201228 to hide this part from current user usetting  */ 
if ($this->router->fetch_class()=='StaffProfile' && $this->router->fetch_method()=='new_action_type') { ?>

				if(row.joining_group != $('input[name="join_group_checkbox"]').prop('checked').toString()){
					$('input[name="join_group_checkbox"]').trigger('click');
					console.log('found join group');
				}
<?php } ?>
				if(row.address != $('input[name="address_checkbox"]').prop('checked').toString()){
					$('input[name="address_checkbox"]').trigger('click');
					console.log('found address');
				}

				if(row.family_info != $('input[name="family_info_checkbox"]').prop('checked').toString()){
					$('input[name="family_info_checkbox"]').trigger('click');
					console.log('found family info ');
				}

				if(row.academic_qualification != $('input[name="academic_qualification_checkbox"]').prop('checked').toString()){
					$('input[name="academic_qualification_checkbox"]').trigger('click');
				}

				/* newly added */
				if(row.education_in_progress != $('input[name="education_in_progress_checkbox"]').prop('checked').toString()){
					$('input[name="education_in_progress_checkbox"]').trigger('click');
				}

				if(row.emergency_contact != $('input[name="emergency_contact_checkbox"]').prop('checked').toString()){
					$('input[name="emergency_contact_checkbox"]').trigger('click');
				}

				if(row.additional_personal_data != $('input[name="additional_personal_data_checkbox"]').prop('checked').toString()){
					$('input[name="additional_personal_data_checkbox"]').trigger('click');
				}

<?php /*akmal 20201228 to hide this part from current user usetting  */ 
if ($this->router->fetch_class()=='StaffProfile' && $this->router->fetch_method()=='new_action_type') { ?>
				if(row.previous_employment_detail != $('input[name="employment_detail_checkbox"]').prop('checked').toString()){
					$('input[name="employment_detail_checkbox"]').trigger('click');
				}
<?php } ?>

				if(row.professional_membership != $('input[name="professional_membership_checkbox"]').prop('checked').toString()){
					$('input[name="professional_membership_checkbox"]').trigger('click');
				}

				if(row.professional_license != $('input[name="professional_licenses_checkbox"]').prop('checked').toString()){
					$('input[name="professional_licenses_checkbox"]').trigger('click');
				}

				/* newly added */
				if(row.professional_education != $('input[name="professional_education_checkbox"]').prop('checked').toString()){
					$('input[name="professional_education_checkbox"]').trigger('click');
				}

				if(row.professional_certificate != $('input[name="professional_certificate_checkbox"]').prop('checked').toString()){
					$('input[name="professional_certificate_checkbox"]').trigger('click');
				}

				if(row.recognition != $('input[name="recognition_checkbox"]').prop('checked').toString()){
					$('input[name="recognition_checkbox"]').trigger('click');
				}

<?php /*akmal 20201228 to hide this part from current user usetting  */ 
if ($this->router->fetch_class()=='StaffProfile' && $this->router->fetch_method()=='new_action_type') { ?>

				if(row.contract_element != $('input[name="contract_element_checkbox"]').prop('checked').toString()){
					$('input[name="contract_element_checkbox"]').trigger('click');
				}

				if(row.basic_pay != $('input[name="basic_pay_checkbox"]').prop('checked').toString()){
					$('input[name="basic_pay_checkbox"]').trigger('click');
				}

				if(row.bank_detail != $('input[name="bank_detail_checkbox"]').prop('checked').toString()){
					$('input[name="bank_detail_checkbox"]').trigger('click');
				}
<?php } ?>

				if(row.statutory_detail != $('input[name="statutory_detail_checkbox"]').prop('checked').toString()){
					$('input[name="statutory_detail_checkbox"]').trigger('click');
				}

				if(row.recurring != $('input[name="recurring_pay_checkbox"]').prop('checked').toString()){
					$('input[name="recurring_pay_checkbox"]').trigger('click');
				}

				if(row.third_party != $('input[name="third_party_checkbox"]').prop('checked').toString()){
					$('input[name="third_party_checkbox"]').trigger('click');
				}
		}
	});
}

function removeWorkflow() {
	toastConfirm('Are you sure you want to remove this workflow ?', function(){
		var id = $('#workflowSelect').val();
		var data = {
			token:'<?php echo $_SESSION['token']; ?>',
			work_id:id,
		};
		ajxRequest('<?php echo base_url('hr/api/staffprofiling/remove_workflow'); ?>', 'POST', data, '<?php echo current_url(''); ?>');
	});
}

function positionSelect(elem) 
{
	console.log($(elem).val());
	$('#designation').empty();
	var options = '';
	<?php if(!empty($designations)) foreach ($designations as $key => $designation): ?>
		if ($(elem).val() == <?php echo $designation->position_id; ?>) {
			
			let option_list = `<option value="<?php echo $designation->id; ?>"><?php echo $designation->designation; ?></option>`;
			options += option_list;

			// options += '<option value="<?php echo $designation->id; ?>"><?php echo $designation->designation; ?></option>'; 
		};
  	<?php endforeach ?>
  	$('#designation').append('<option disabled selected>Please Select Designations</option>'+options);
}

function subgroupSelect(elem) 
{
	console.log($(elem).val());
	$('#position').empty();
	$('#designation').empty();
	var options = '';
	<?php if(!empty($jobPositions)) foreach ($jobPositions as $key => $jobPositions): ?>
		if ($(elem).val() == <?php echo $jobPositions->parent_id; ?>) {
			
			<?php if($jobPositions->level > 0){ ?>
				let option_list = `<option value="<?php echo $jobPositions->id; ?>" data-grade="<?php echo $jobPositions->grade; ?>">
								<?php echo $jobPositions->grade; ?> (<?php echo integerToRoman($jobPositions->level); ?>) - <?php echo $jobPositions->position; ?> 
							   </option>`;
			<?php }else{ ?>
				let option_list = `<option value="<?php echo $jobPositions->id; ?>" data-grade="<?php echo $jobPositions->grade; ?>">
								<?php echo $jobPositions->grade; ?> - <?php echo $jobPositions->position; ?>
							   </option>`;
			<?php } ?>
			
			options += option_list;

			// options += '<option value="<?php echo $designation->id; ?>"><?php echo $designation->designation; ?></option>'; 
		};
  	<?php endforeach ?>
  	$('#position').append('<option disabled selected>Please Select Positions</option>'+options);
}

function isFamilyStudent() {
	var status = $('select[name="family_student"]').val();
	$('input[name="family_occupation"]').val('');
	if(status == 0){
		$('#sect-family-occupation').addClass('d-none');
	}else{
		$('#sect-family-occupation').removeClass('d-none');
	}
}

function removeItem(elem) {
	var i 		= $(elem).find('i').first();
	var pos 	= i.data('index');
	var table   = i.data('table');

	if(table == '#tbl-address'){
		addressList.splice(pos,1);
	}

	if(table == '#tbl-familyInfo'){
		familyList.splice(pos,1);
	}

	if (table == '#tbl-academicQualification'){
		academicList.splice(pos,1);
	}

	/* newly added */
	if (table == '#tbl-educationInProgress'){
		eipList.splice(pos,1);
	}

	if (table == '#tbl-emergencyContact'){
		ecList.splice(pos,1);
	}

	if (table == '#tbl-personalData'){
		additionalPersonalList.splice(pos,1);
	}

	if (table == '#tbl-previousEmployment'){
		prevEmpList.splice(pos,1);
	}
	

	if (table == '#tbl-professionalMembership'){
		proMembershipList.splice(pos,1);
	}

	if (table == '#tbl-professionalLicense'){
		proLicenseList.splice(pos,1);
	}

	/* newly added */
	if (table == '#tbl-professionalEducation'){
		proEducationList.splice(pos,1);
	}

	if (table == '#tbl-professionalCertificate'){
		proCertificateList.splice(pos,1);
	}

	if (table == '#tbl-recognition'){
		recognitionList.splice(pos,1);
	}

	if (table == '#tbl-bankDetail'){
		bankList.splice(pos,1);
	}

	if (table == '#tbl-recurring'){
		recurList.splice(pos,1);
	}

	if (table == '#tbl-thirdParty'){
		thirdPartyList.splice(pos,1);
	}
	createtable(table);
}

function createtable(tableid) {
	var table = $(tableid).DataTable();
	table.clear().draw();

	/* create table for address*/
	if(tableid == '#tbl-address'){

		$.each(addressList, function(key,value){

			var type = '',state = '', country = '';
			<?php foreach ($residenceType as $key => $type): ?>
				if(value.type == '<?php echo $type->id?>'){
					type = '<?php echo $type->type;?>';
				}
			<?php endforeach ?>	
			<?php if($states) foreach ($states as $key => $state): ?>
				if(value.state == '<?php echo $state->id;?>'){
					state = '<?php echo $state->state;?>';
				}
			<?php endforeach ?>
			<?php foreach ($countries as $key => $country): ?>
				if(value.country == '<?php echo $country->id; ?>'){
					country = '<?php echo $country->country; ?>';
				}
			<?php endforeach ?>

			table.row.add([
				'<b>Type : </b> '+type+'<br/><b>Address : </b> '+value.address+'<br/>\
				 <b>Postcode : </b>'+value.postcode+'<br/>\
				 <b>City : </b>'+value.city+'<br/>\
				 <b>State : </b>'+state+'<br/>\
				 <b>Country : </b>'+country+'<br/>\
				 <b>Contact : </b>'+value.contact_header+value.contact_number,
				 '<div class="btn-group">\
					<button type="button" class="btn btn-success btn-sm"\
					data-toggle="modal" data-target="#modal-editAddress" data-content="'+btoa(JSON.stringify(value))+'" data-key="'+key+'"\
					onclick="editAddress(this)">\
						<i class="fa fa-edit"></i>\
					</button>\
					<button class="btn btn-danger btn-sm" type="button"\
					onclick="removeItem(this)" >\
						<i data-index="'+key+'" data-table="#tbl-address" ></i>\
						<i class="fas fa-trash-alt"></i>\
					</button>\
				</div>'
			]).draw();

		});
	}
	/* end create table for address*/

	$('#pcb_name').empty('');
	/* create table for family info*/
	if (tableid == '#tbl-familyInfo') {
		var pcb_table = $('#tbl-pcb').DataTable();
		pcb_table.clear().draw();

		$.each(familyList, function(key,value){

			var relation = '',oku_status = '',student_status = '';

			<?php foreach ($relations as $key => $relation): ?>
				if(value.relation == '<?php echo $relation->id; ?>'){
					relation = '<?php echo $relation->relations; ?>';
				}
			<?php endforeach ?>

			<?php foreach ($qualifications as $key => $qualification): ?>
				if(value.academic_level == <?php echo $qualification->id; ?>){
					var qualification = '<?php echo $qualification->level; ?>';
				}
			<?php endforeach ?>

			if (value.oku_status == 0){ 
				oku_status = 'Yes';
			}else{
				oku_status = 'No';
			}

			if (value.student_status == 0) {
				student_status = 'Yes';
			}else{
				student_status = 'No';
			}

			console.log(value);
			table.row.add([
				'<b>Name : </b>'+value.name+'<br/>\
				<b>NRIC / passport No : </b>'+value.ic_no+'<br/>\
				<b>Relation : </b>'+relation+'<br/>\
				<b>Birthdate : </b>'+value.birthdate+'<br/>\
				<b>Contact No : </b>'+value.contact_header+''+value.contact_no+'<br/>\
				<b>Email : </b>'+value.email+'<br/>\
				<b>Academic Level : </b>'+qualification+'<br/>\
				<b>Address : </b>'+value.address+'<br/>\
				<b>Occupation : </b>'+value.occupation+'<br/>\
				<b>University : </b>'+value.academic_institution+'<br/>\
				<b>Status (OKU) : </b>'+oku_status+'<br/>\
				<b>Status (Student) : </b>'+student_status,
				'<div class="btn-group">\
					<button type="button" class="btn btn-success btn-sm" \
					data-toggle="modal" data-target="#modal-editFamilyInfo" data-content="'+btoa(JSON.stringify(value))+'" data-key="'+key+'" \
					onclick="editFamilyInfo(this)">\
						<i class="fa fa-edit"></i>\
					</button>\
					<button class="btn btn-danger btn-sm" \
					type="button" \
					onclick="removeItem(this)">\
						<i data-index="'+key+'" data-table="#tbl-familyInfo" ></i>\
						<i class="fas fa-trash-alt"></i>\
					</button>\
				</div>'
			]).draw(true);


			if(value.relation == 2){
				$('#pcb_name').append('<option value="'+key+'">'+value.name+'</option>');
			}


			//create table for pcb ....
			if(value.pcb_consideration){
				var responsibility = '';
				if(value.responsibility == '0'){
					responsibility = 'Employee';
				}else{
					responsibility = 'Spouse';
				}

				pcb_table.row.add([
					value.name,
					value.ic_no,
					responsibility,
					'<div class="btn-group">\
						<button class="btn btn-danger btn-sm"><i class="fa fa-trash-alt"></i></button>\
					</div>'
				]).draw(true);
			}

		});
	};
	/* end create table for family info*/

	/* create table for academic qualification*/
	if (tableid == '#tbl-academicQualification'){
		$.each(academicList,function(key,value){
			var level = '';
			<?php foreach ($qualifications as $key => $qualification): ?>
				if (value.level_id == '<?php echo $qualification->id; ?>') {
					level = '<?php echo $qualification->level; ?>';
				};
			<?php endforeach ?>
			var filename = '';

			if(value.table){
				let attachment = JSON.parse(value.table);	
				if(!attachment.error){
					filename = attachment.orig_name;
				}
			}

			table.row.add([
				'<b>Level : </b>'+level+'<br/>\
				<b>Year Graduated : </b>'+value.year+'<br/>\
				<b>University / Institution : </b>'+value.institution+'<br/>\
				<b>Program : </b>'+value.program+'<br/>\
				<b>Final Result / CGPA :  </b>'+value.cgpa+'<br/>\
				<b>Attachment : </b>'+filename,
				'<div class="btn-group">\
					<button type="button" class="btn btn-success btn-sm" \
					data-toggle="modal" data-target="#modal-editAcademic" data-content="'+btoa(JSON.stringify(value))+'" data-key="'+key+'"\
					onclick="editAQualification(this)" >\
						<i class="fa fa-edit"></i>\
					</button>\
					<button class="btn btn-danger btn-sm" \
					type="button" \
					onclick="removeItem(this)">\
						<i data-index="'+key+'" data-table="#tbl-academicQualification" ></i>\
						<i class="fas fa-trash-alt"></i>\
					</button>\
				</div>'
			]).draw(true);
		});
	};
	/*end create table for academic qualification*/

	/* create table for personal data*/
	if (tableid == '#tbl-personalData') {
		$.each(additionalPersonalList, function(key,value){
			
			var filename = '';

			if(value.table){
				let attachment = JSON.parse(value.table);
				if(!attachment.error){
					filename = attachment.orig_name;
				}
			}

			table.row.add([
				value.detail,
				value.description,
				filename,
				'<div class="btn-group">\
					<button type="button" class="btn btn-success btn-sm" \
					data-toggle="modal" data-target="#modal-editPersonalData" data-content="'+btoa(JSON.stringify(value))+'" data-key="'+key+'"\
					onclick="editPersonalData(this)">\
						<i class="fa fa-edit"></i>\
					</button>\
					<button class="btn btn-danger btn-sm" type="button"\
					onclick="removeItem(this)">\
						<i data-index="'+key+'" data-table="#tbl-personalData" ></i>\
						<i class="fas fa-trash-alt"></i>\
					</button>\
				</div>'
			]).draw(true);

		});
	};
	/* end: create table for personal data*/

	/* create previous employment history */
	if(tableid == '#tbl-previousEmployment'){
		$.each(prevEmpList, function(key,value){

			table.row.add([
				'<b>Employer Name : </b>'+value.employer_name+'<br/>\
				<b>Employer Address : </b>'+value.employer_address+'<br/>\
				<b>Position : </b>'+value.position+'<br/>\
				<b>Date Join : </b>'+value.date_enter+'<br/>\
				<b>Date To : </b>'+value.date_exit+'<br/>\
				<b>Length of Service : </b>'+value.length_of_service+'<br/>\
				<b>Descripiton : </b>'+value.description,
				'<div class="btn-group">\
					<button type="button" class="btn btn-success btn-sm" \
					data-toggle="modal" data-target="#modal-editPrevEmployment" data-content="'+btoa(JSON.stringify(value))+'" data-key="'+key+'"\
					onclick="editPreviousEmpHistory(this)">\
						<i class="fa fa-edit"></i>\
					</button>\
					<button type="button" class="btn btn-danger btn-sm" \
					onclick="removeItem(this)">\
						<i data-index="'+key+'" data-table="#tbl-previousEmployment" ></i>\
						<i class="fas fa-trash-alt"></i>\
					</button>\
				</div>'
			]).draw(true);

		});
	}
	/* end : create previous employment history */

	/* create table for professional memberships */
	if (tableid == '#tbl-professionalMembership') {
		$.each(proMembershipList, function(key,value){
			var filename = '';
			if(value.table){
				let attachment = JSON.parse(value.table);
				if (!attachment.error) {
					filename = attachment.orig_name;
				}
			}
			
			table.row.add([
				'<b>Professional Bodies  : </b>'+value.professional_body+'<br/>\
				<b>Name of Membership : </b>'+value.certificate+'<br/>\
				<b>Type of Membership : </b>'+value.membership+'<br/>\
				<b>Membership No : </b>'+value.membership_no+'<br/>\
				<b>Year : </b>'+value.year+'<br/>\
				<b>Attachment : </b>'+filename,
				'<div class="btn-group">\
					<button type="button" class="btn btn-success btn-sm" \
					data-toggle="modal" data-target="#modal-editProMembership" data-content="'+btoa(JSON.stringify(value))+'" data-key="'+key+'"\
					onclick="editProfessionalMembership(this)">\
						<i class="fa fa-edit"></i>\
					</button>\
					<button type="button" class="btn btn-danger btn-sm" \
					onclick="removeItem(this)">\
						<i data-index="'+key+'" data-table="#tbl-professionalMembership" ></i>\
						<i class="fas fa-trash-alt"></i>\
					</button>\
				</div>'
			]).draw(true);

		});
	};
	/* end : create table for professional memberships*/

	/* create table for professional license */
	if(tableid == '#tbl-professionalLicense'){
		$.each(proLicenseList,function(key,value){
			console.log("license");
			console.log(value);
			var filename = '';
			if(value.table){
				let attachment = JSON.parse(value.table);
				if(!attachment.error){
					filename = attachment.orig_name;
				}
			}

			table.row.add([
				'<b>Name of License : </b>'+value.profession+'<br/>\
				<b>License No : </b>'+value.license_no+'<br/>\
				<b>License Body/Authority : </b>'+value.license_body_authority+'<br/>\
				<b>Register Date : </b>'+value.register_date+'<br/>\
				<b>Latest Renewed Date : </b>'+value.renewal_date+'<br/>\
				<b>Next Renewal Date : </b>'+value.next_renewal_date+'<br/>\
				<b>Attachment : </b>'+filename,
				'<div class="btn-group">\
					<button type="button" class="btn btn-success btn-sm" \
					data-toggle="modal" data-target="#modal-editProLicense" data-content="'+btoa(JSON.stringify(value))+'" data-key="'+key+'"\
					onclick="editProfessionalLicense(this)">\
						<i class="fa fa-edit"></i>\
					</button>\
					<button type="button" class="btn btn-danger btn-sm" \
					onclick="removeItem(this)">\
						<i data-index="'+key+'" data-table="#tbl-professionalLicense" ></i>\
						<i class="fas fa-trash-alt"></i>\
					</button>\
				</div>'
			]).draw(true);

		});
	}
	/* end : create table for professional license*/

	/* create table for recognition */
	if(tableid == '#tbl-recognition'){
		$.each(recognitionList,function(key,value){

			var filename = '';
			if(value.table){
				let attachment = JSON.parse(value.table);
				if(!attachment.error){
					filename = attachment.orig_name;
				}
			}

			table.row.add([
				'<b>Achievement : </b>'+value.achievement+'<br/>\
				<b>Award : </b>'+value.award+'<br/>\
				<b>Year : </b>'+value.year+'<br/>\
				<b>Attachment : </b>'+filename,
				'<div class="btn-group">\
					<button type="button" class="btn btn-success btn-sm" \
					data-toggle="modal" data-target="#modal-editRecognition" data-content="'+btoa(JSON.stringify(value))+'" data-key="'+key+'"\
					onclick="editRecognition(this)">\
						<i class="fa fa-edit"></i>\
					</button>\
					<button type="button" class="btn btn-danger btn-sm" \
					onclick="removeItem(this)">\
						<i data-index="'+key+'" data-table="#tbl-recognition" ></i>\
						<i class="fas fa-trash-alt"></i>\
					</button>\
				</div>'
			]).draw(false);

		});
	}
	/* end: create table for recognition */

	/* create table bank details */
	if (tableid == '#tbl-bankDetail') {
		$.each(bankList,function(key,value){

				var filename = '';var bank_name = '';
				if(value.table){
					let attachment = JSON.parse(value.table);
					if(!attachment.error){
						filename = attachment.orig_name;
					}
				}

				<?php foreach ($banks as $key => $bank): ?>
					if(value.bank_id == '<?php echo $bank->id; ?>'){
						bank_name = '<?php echo $bank->name; ?>';
					}
				<?php endforeach ?>

				table.row.add([
					'<b>Bank Name</b> : '+bank_name+'<br/>\
					<b>Branch</b> : '+value.branch+'<br/>\
					<b>Account No</b> : '+value.acc_no+'<br/>\
					<b>Status : </b>'+value.status+'<br/>\
					<b>Attachment : </b>'+filename,
					'<div class="btn-group">\
						<button type="button" class="btn btn-success btn-sm" \
						data-toggle="modal" data-target="#modal-editBankDetail" data-content="'+btoa(JSON.stringify(value))+'" data-key="'+key+'"\
						onclick="editBankDetail(this)">\
							<i class="fa fa-edit"></i>\
						</button>\
						<button class="btn btn-danger btn-sm" \
						type="button" \
						onclick="removeItem(this)">\
							<i data-index="'+key+'" data-table="#tbl-bankDetail"></i>\
							<i class="fas fa-trash-alt"></i>\
						</button>\
					</div>'
				]).draw(true);
		});
	};
	/* end : create table bank details */

	/* create table for recurrig pay and deduction */
	if (tableid == '#tbl-recurring') {
		$.each(recurList,function(key,value){
			var recurring = ''; var status = '';

			if(value.recurring == 0){
				recurring = 'Payment';
			}else{
				recurring = 'Deduction';
			}

			if(value.status == 0){
				status = 'Ongoing'
			}else{
				status = 'End';
			}

			table.row.add([
				'<b>Recurring : </b>'+recurring+'<br/>\
				<b>Type : </b>'+value.type+'<br/>\
				<b>From : </b>'+value.date_from+'<br/>\
				<b>To : </b>'+value.date_to+'<br/>\
				<b>Amount : RM</b>'+value.amount+'<br/>\
				<b>Status : </b>'+status,
				'<div class="btn-group">\
					<button type="button" class="btn btn-success btn-sm" \
					data-toggle="modal" data-target="#modal-editRecurring" data-content="'+btoa(JSON.stringify(value))+'" data-key="'+key+'"\
					onclick="editRecurring(this)">\
						<i class="fa fa-edit"></i>\
					</button>\
					<button class="btn btn-danger btn-sm" \
					type="button" \
					onclick="removeItem(this)">\
						<i data-index="'+key+'" data-table="#tbl-recurring" ></i>\
						<i class="fas fa-trash-alt"></i>\
					</button>\
				</div>'
			]).draw(false);
		});
	};  
	/* end: create table for recurring pay and deduction*/
	
	/* create third party payment */
	if(tableid == '#tbl-thirdParty'){
		$.each(thirdPartyList, function(key,value){
			var status = '';
			if(value.status == 0){
				status = 'Ongoing';
			}else{
				status = 'End';
			}

			table.row.add([
				'<b>From : </b>'+value.date_start+'<br/>\
				<b>To : </b>'+value.date_end+'<br/>\
				<b>Organisation / Institution : </b>'+value.type+'<br/>\
				<b>Status : </b>'+status+'<br/>\
				<b>Amount : </b>'+value.amount,
				'<div class="btn-group">\
					<button type="button" class="btn btn-success btn-sm" \
					data-toggle="modal" data-target="#modal-editThirdParty" data-content="'+btoa(JSON.stringify(value))+'" data-key="'+key+'"\
					onclick="editThirdParty(this)">\
						<i class="fa fa-edit"></i>\
					</button>\
					<button class="btn btn-danger btn-sm" \
					type="button" \
					onclick="removeItem(this)">\
						<i data-index="'+key+'" data-table="#tbl-thirdParty" ></i>\
						<i class="fas fa-trash-alt"></i>\
					</button>\
				</div>'
			]).draw(true);
		});
	}
	/* end : create third party payments */

	/* newly added --- create table for education in progress */
	if (tableid == '#tbl-educationInProgress'){
		$.each(eipList,function(key,value){
			if(value.status == 0) var status = 'On Going';
			else if(value.status == 1) var status = 'Graduated';
			else if(value.status == 2) var status = 'Withdrawn';
			else if(value.status == 3) var status = 'Deferred';

			table.row.add([
				'<b>Program : </b>'+value.program+'<br/>\
				<b>University / Institution : </b>'+value.institution+'<br/>\
				<b>Progress Paper In Hand : </b>'+value.progress_paper+'<br/>\
				<b>Start Date : </b>'+value.date_start+'<br/>\
				<b>Expected Date of Completion  :  </b>'+value.date_end+'<br/>\
				<b>Status : </b>'+status,
				'<div class="btn-group">\
					<button type="button" class="btn btn-success btn-sm" \
					data-toggle="modal" data-target="#modal-editEducationInProgress" data-content="'+btoa(JSON.stringify(value))+'" data-key="'+key+'"\
					onclick="editEducationInProgress(this)" >\
						<i class="fa fa-edit"></i>\
					</button>\
					<button class="btn btn-danger btn-sm" \
					type="button" \
					onclick="removeItem(this)">\
						<i data-index="'+key+'" data-table="#tbl-educationInProgress" ></i>\
						<i class="fas fa-trash-alt"></i>\
					</button>\
				</div>'
			]).draw(true);
		});
	};
	/*end create table for education in progress */

	/* newly added --- create table for emergency contact */
	if (tableid == '#tbl-emergencyContact'){
		$.each(ecList,function(key,value){

			table.row.add([
				'<b>Name : </b>'+value.name+'<br/>\
				<b>Relation : </b>'+value.relation+'<br/>\
				<b>Contact Number : </b>'+value.phone+'<br/>\
				<b>Email : </b>'+value.email+'<br/>\
				<b>Address : </b>'+value.address,
				'<div class="btn-group">\
					<button type="button" class="btn btn-success btn-sm" \
					data-toggle="modal" data-target="#modal-editEmergencyContact" data-content="'+btoa(JSON.stringify(value))+'" data-key="'+key+'"\
					onclick="editEmergencyContact(this)" >\
						<i class="fa fa-edit"></i>\
					</button>\
					<button class="btn btn-danger btn-sm" \
					type="button" \
					onclick="removeItem(this)">\
						<i data-index="'+key+'" data-table="#tbl-emergencyContact" ></i>\
						<i class="fas fa-trash-alt"></i>\
					</button>\
				</div>'
			]).draw(true);
		});
	};
	/*end create table for emergency contact */
	
	/* newly added create table for academic education */
	if (tableid == '#tbl-professionalEducation'){
		$.each(proEducationList,function(key,value){
			var filename = '';

			if(value.table){
				let attachment = JSON.parse(value.table);	
				if(!attachment.error){
					filename = attachment.orig_name;
				}
			}

			table.row.add([
				'<b>Level : </b>'+value.level+'<br/>\
				<b>Name of Professional Association : </b>'+value.associate_name+'<br/>\
				<b>Name of Course Study : </b>'+value.program+'<br/>\
				<b>Date Graduated : </b>'+value.date_finish+'<br/>\
				<b>Final Result :  </b>'+value.result+'<br/>\
				<b>Attachment : </b>'+filename,
				'<div class="btn-group">\
					<button type="button" class="btn btn-success btn-sm" \
					data-toggle="modal" data-target="#modal-editProfessionalEducation" data-content="'+btoa(JSON.stringify(value))+'" data-key="'+key+'"\
					onclick="editProfessionalEducation(this)" >\
						<i class="fa fa-edit"></i>\
					</button>\
					<button class="btn btn-danger btn-sm" \
					type="button" \
					onclick="removeItem(this)">\
						<i data-index="'+key+'" data-table="#tbl-professionalEducation" ></i>\
						<i class="fas fa-trash-alt"></i>\
					</button>\
				</div>'
			]).draw(true);
		});
	};
	/*end create table for academic education*/

	/* newly added create table for academic certificate */
	if (tableid == '#tbl-professionalCertificate'){
		$.each(proCertificateList,function(key,value){
			var filename = '';

			if(value.table){
				let attachment = JSON.parse(value.table);	
				if(!attachment.error){
					filename = attachment.orig_name;
				}
			}

			table.row.add([
				'<b>Name of Certification Body : </b>'+value.associate_name+'<br/>\
				<b>Name of Certification Programme : </b>'+value.program+'<br/>\
				<b>Date Finish : </b>'+value.date_finish+'<br/>\
				<b>Result :  </b>'+value.result+'<br/>\
				<b>Attachment : </b>'+filename,
				'<div class="btn-group">\
					<button type="button" class="btn btn-success btn-sm" \
					data-toggle="modal" data-target="#modal-editProfessionalCertificate" data-content="'+btoa(JSON.stringify(value))+'" data-key="'+key+'"\
					onclick="editProfessionalCertificate(this)" >\
						<i class="fa fa-edit"></i>\
					</button>\
					<button class="btn btn-danger btn-sm" \
					type="button" \
					onclick="removeItem(this)">\
						<i data-index="'+key+'" data-table="#tbl-professionalCertificate" ></i>\
						<i class="fas fa-trash-alt"></i>\
					</button>\
				</div>'
			]).draw(true);
		});
	};
	/*end create table for academic certificate */

}


/*
	ajax function to upload content
*/
function uploadAttachment(infotype,attachment_id,func) {
	formData = new FormData();
    formData.append('token','<?php echo $_SESSION['token']; ?>');
    formData.append('infotype',infotype);
    formData.append('staff_id','<?php echo $staff['id']; ?>'); //fake it
    formData.append('attachment',$(attachment_id).prop('files')[0]);
	$.ajax({
		url: '<?php echo base_url('hr/api/staffprofiling/uploadAttachment'); ?>',
		type: "POST",             
        data: formData, 
        contentType:false,       
        cache: false,             
        processData:false,  
		success: function(data){
			func(data);
		},
		error: function(){
			iziToast.error({
				position: 'bottomRight',
				title: 'Failed',
				message: 'Uploading attachments failed'
			});
		}
	});
}


/*------------ INFOTYPE FUNCTIONALITIES  -------------------*/
function addAddress() {
	var form = formIdToInputObject('#action_type_form');
	var list = {
		user_id:form.user_id,
		type:form.address_type,
		address:form.address_place,
		postcode:form.address_postcode,
		city:form.address_city,
		state:form.address_state,
		country:form.address_country,
		contact_header:form.address_contact_header,
		contact_number:form.address_contact_number
	};

	addressList.push(list);

	var input_address1 = $('textarea[name="address_place"]').val('');
	var input_address2 = $('input[name="address_postcode"]').val('');
	var input_address3 = $('input[name="address_city"]').val('');
	var input_address4 = $('input[name="address_contact_number"]').val('');
	createtable('#tbl-address');
}

function addFamilyInfo() {
	var form = formIdToInputObject('#action_type_form');
	var list = {
		user_id:form.user_id,
		ic_no:form.family_nric,
		address:form.family_address,
		birthdate:form.family_birthdate,
		contact_header:form.family_contact_header,
		contact_no:form.family_contact,
		email:form.family_email,
		academic_level:form.family_academic,
		academic_institution:form.family_institution,
		name: form.family_name,
		relation: form.family_relation,
		occupation:form.family_occupation,
		oku_status:form.family_dissability,
		student_status:form.family_student,
	};
	familyList.push(list);

	$('input[name="family_name"]').val('');
	$('input[name="family_nric"]').val('');
	$('input[name="family_birthdate"]').val('');
	$('input[name="family_contact"]').val('');
	$('input[name="family_email"]').val('');
	$('textarea[name="family_address"]').val('');
	$('input[name="family_occupation"]').val('');
	$('input[name="family_institution"]').val('');

	createtable('#tbl-familyInfo');
}

function addQualification() {
	var form = formIdToInputObject('#action_type_form');
	let infotype = 'qualifications';
	// let infotype = 3;qualifications

	uploadAttachment(infotype,'input[name="academic_attachment"]',function (elem){
		var list = {
			user_id:form.user_id,
			level_id:form.academic_qualification,
			program:form.academic_program,
			institution:form.academic_university,
			year:form.academic_year_grad,
			cgpa:form.academic_cgpa,
			table:elem,
		};	
		academicList.push(list);
		createtable('#tbl-academicQualification');
	});
	$('input[name="academic_year_grad"]').val('');
	$('input[name="academic_university"]').val('');
	$('input[name="academic_program"]').val('');
	$('input[name="academic_cgpa"]').val('');
	$('input[name="academic_attachment"]').val('');
}

function addPersonalData() {
	var form = formIdToInputObject('#action_type_form');
	let infotype = ''; 
	// let infotype = 4; 
	uploadAttachment(infotype,'input[name="personal_attachment"]',function(elem){
		var list = {
			user_id:form.user_id,
			detail:form.personal_details,
			description:form.personal_description,
			table:elem,
		};
		additionalPersonalList.push(list);
		createtable('#tbl-personalData');
	});
	$('input[name="personal_details"]').val('');
	$('textarea[name="personal_description"]').val('');
	$('input[name="personal_attachment"]').val('');
}

function addPreviousEmployent() {
	var form = formIdToInputObject('#action_type_form');
	var list = {
		user_id: form.user_id,
		employer_name : form.employment_employer_name,
		employer_address:form.employment_employer_address,
		position:form.employment_position,
		date_enter:form.employment_date_join,
		date_exit:form.employment_date_to,
		length_of_service:form.employment_length_of_service+' '+form.employment_length_of_service_type,
		description:form.employment_description,
	};
	prevEmpList.push(list);

	$('input[name="employment_date_join"]').val('');
	$('input[name="employment_date_to"]').val('');
	$('input[name="employment_employer_name"]').val('');
	$('textarea[name="employment_employer_address"]').val('');
	$('input[name="employment_position"]').val('');
	$('input[name="employment_length_of_service"]').val('');
	$('textarea[name="employment_description"]').val('');

	createtable('#tbl-previousEmployment');
}

function addProfessionalMembership() {
	var form = formIdToInputObject('#action_type_form');
	let infotype = 'membership';
	// let infotype = 6;
	uploadAttachment(infotype,'input[name="professional_attachment"]',function(elem){
		console.log(JSON.parse(elem));

		var list = {
			user_id:form.user_id,
			professional_body:form.professional_bodies,
			certificate:form.professional_certificate,
			membership:form.professional_membership,
			membership_no:form.professional_membership_number,
			year:form.professional_year,
			table:elem,
		};
		proMembershipList.push(list);
		createtable('#tbl-professionalMembership');
	});
	$('input[name="professional_bodies"]').val('');
	$('input[name="professional_certificate"]').val('');
	$('input[name="professional_membership"]').val('');
	$('input[name="professional_membership_number"]').val('');
	$('input[name="professional_year"]').val('');
	$('input[name="professional_attachment"]').val('');
}

function addProfessionalLicense(){
	var form = formIdToInputObject('#action_type_form');
	let infotype = 'license';
	// let infotype = 7;
	uploadAttachment(infotype,'input[name="license_attachment"]',function(elem){
		var list = {
			user_id: form.user_id,
			profession:form.license_profession,
			license_no:form.license_no,
			license_body_authority:form.license_body_authority,
			register_date:form.license_date_init,
			renewal_date:form.license_date_renewal,
			next_renewal_date:form.license_next_date_renewal,
			table:elem,
		};
		proLicenseList.push(list);
		createtable('#tbl-professionalLicense');
	});
	$('input[name="license_profession"]').val('');
	$('input[name="license_no"]').val('');
	$('input[name="license_date_init"]').val('');
	$('input[name="license_date_renewal"]').val('');
	$('input[name="license_next_date_renewal"]').val('');
	$('input[name="license_attachment"]').val('');
}

function addRecognition(){
	var form = formIdToInputObject('#action_type_form');
	let infotype = 'recognition'; 
	// let infotype = 8; 
	uploadAttachment(infotype,'input[name="recognition_attachment"]',function(elem){
		var list = {
			user_id:form.user_id,
			achievement:form.recognition_achievement,
			award:form.recognition_award,
			year:form.recognition_year,
			table:elem,
		};
		recognitionList.push(list);
		createtable('#tbl-recognition');
	});
	$('input[name="recognition_achievement"]').val('');
	$('input[name="recognition_award"]').val('');
	$('input[name="recognition_year"]').val('');
	$('input[name="recognition_attachment"]').val('');
}

function addBankDetails() {
	var form = formIdToInputObject('#action_type_form');
	let infotype = 'bank';
	// let infotype = 11;
	uploadAttachment(infotype,'input[name="bank_attachment"]',function(elem){
		console.log('uploading attachemnet for bank success');
		console.log(elem);

		var list = {
			user_id:form.user_id,
			bank_id:form.bank_name,
			branch:form.bank_branch,
			acc_no:form.bank_account_no,
			status:form.bank_status,
			table:elem,
		};
		bankList.push(list);
		createtable('#tbl-bankDetail');
	});
	$('input[name="bank_branch"]').val('');
	$('input[name="bank_account_no"]').val('');
	$('input[name="bank_status"]').val('');
	$('input[name="bank_attachment"]').val('');
}

function addRecuring() {
	var form = formIdToInputObject('#action_type_form');

	var list = {
		user_id:form.user_id,
		date_from:form.recurring_date_from,
		date_to:form.recurring_date_to,
		recurring:form.recurring_item_recurr,
		type:form.recurring_type,
		amount:form.recurring_amount,
		status:form.recurring_status,
	};
	recurList.push(list);
	$('input[name="recurring_date_from"]').val('');
	$('input[name="recurring_date_to"]').val('');
	$('input[name="recurring_type"]').val('');
	$('input[name="recurring_amount"]').val('');
	createtable('#tbl-recurring');
}

function addThirdParty() {
	var form = formIdToInputObject('#action_type_form');

	var list = {
		user_id:form.user_id,
		date_start:form.third_party_date_from,
		date_end:form.third_party_date_to,
		type:form.third_party_institute,
		amount:form.third_party_amount,
		status:form.third_party_status,
	};
	thirdPartyList.push(list);

	$('input[name="third_party_date_from"]').val('');
	$('input[name="third_party_date_to"]').val('');
	$('input[name="third_party_institute"]').val('');
	$('input[name="third_party_amount"]').val('');

	createtable('#tbl-thirdParty');
}

function addPCB(){
	var form = formIdToInputObject('#action_type_form');
	var family_index = form.pcb_name;
	var responsibility = form.pcb_responsibility;
	familyList[family_index].pcb_consideration = true;
	familyList[family_index].responsibility = responsibility;
	createtable('#tbl-familyInfo');
}

/* newly added */
function addEducationInProgress() {
	var form = formIdToInputObject('#action_type_form');
	// if(form.eip_status == 0) var status = 'On Going';
	// else if(form.eip_status == 1) var status = 'Graduated';
	// else if(form.eip_status == 2) var status = 'Withdrawn';
	// else if(form.eip_status == 3) var status = 'Deferred';

	var list = {
		user_id: form.user_id,
		program:form.eip_program,
		institution:form.eip_institution,
		progress_paper:form.eip_progress_paper,
		date_start:form.eip_date_start,
		date_end:form.eip_date_end,
		status:form.eip_status,
	};
	eipList.push(list);

	$('input[name="eip_program"]').val('');
	$('input[name="eip_institution"]').val('');
	$('input[name="eip_progress_paper"]').val('');
	$('input[name="eip_date_start"]').val('');
	$('input[name="eip_date_end"]').val('');

	createtable('#tbl-educationInProgress');
}

function addEmergencyContact() {
	var form = formIdToInputObject('#action_type_form');
	var list = {
		user_id: form.user_id,
		name:form.ec_name,
		relation:form.ec_relation,
		phone:form.ec_phone,
		email:form.ec_email,
		address:form.ec_address,
	};

	ecList.push(list);

	$('input[name="ec_name"]').val('');
	$('input[name="ec_relation"]').val('');
	$('input[name="ec_phone"]').val('');
	$('input[name="ec_email"]').val('');
	$('textarea[name="ec_address"]').val('');

	createtable('#tbl-emergencyContact');
}

function addProfessionalEducation() {
	var form = formIdToInputObject('#action_type_form');
	let infotype = 'professional_academic/education';

	uploadAttachment(infotype,'input[name="professional_education_attachment"]',function (elem){
		var list = {
			user_id:form.user_id,
			type:form.professional_education_type,
			level:form.professional_education_level,
			associate_name:form.professional_education_associate_name,
			program:form.professional_education_program,
			date_finish:form.professional_education_date_finish,
			result:form.professional_education_result,
			table:elem,
		};	
		proEducationList.push(list);
		createtable('#tbl-professionalEducation');
	});

	$('input[name="professional_education_associate_name"]').val('');
	$('input[name="professional_education_program"]').val('');
	$('input[name="professional_education_date_finish"]').val('');
	$('input[name="professional_education_result"]').val('');
}

function addProfessionalCertificate() {
	var form = formIdToInputObject('#action_type_form');
	let infotype = 'professional_academic/certificate';

	uploadAttachment(infotype,'input[name="professional_certificate_attachment"]',function (elem){
		var list = {
			user_id:form.user_id,
			type:form.professional_certificate_type,
			associate_name:form.professional_certificate_associate_name,
			program:form.professional_certificate_program,
			date_finish:form.professional_certificate_date_finish,
			result:form.professional_certificate_result,
			table:elem,
		};	
		proCertificateList.push(list);
		createtable('#tbl-professionalCertificate');
	});

	$('input[name="professional_certificate_associate_name"]').val('');
	$('input[name="professional_certificate_program"]').val('');
	$('input[name="professional_certificate_date_finish"]').val('');
	$('input[name="professional_certificate_result"]').val('');
}
/*------------ END :INFOTYPE FUNCTIONALITIES  -------------------*/

function aedChange(elem){
	
	$('input[name="basic_pay_date_start"]').val($(elem).val());
	$('input[name="contract_confirmation_date"]').val($(elem).val());
}

function confirmDateChange(){

	var aefDate 		= $('input[name="efective_date"]').val();
	$('input[name="contract_confirmation_date"]').val(aefDate);

	var number 	   		= $('input[name="contract_probationary_period"]').val();
	var periodType 		= $('select[name="contract_probationary_period_type"] option:selected').text();
	var currentConfDate = $('input[name="contract_confirmation_date"]').val();
	var currentConfDateMoment	= moment(currentConfDate, "DD-MM-YYYY");
	var newConfDate				= moment(currentConfDateMoment).add(number, periodType);

	$('input[name="contract_confirmation_date"]').val(moment(newConfDate).format('DD-MM-YYYY'));

}

$(document).ready(function(){
console.log('document ready 2');
	var actionTypeList = [
	'Hiring',
	'Re-entry into company',
	'Promotion',
	'Change of pay',
	'Change of grade',
	'Secondment',
	'Transfer interdepartmental',
	'Transfer intradepartmental',
	'Long term absence',
	'Resume work',
	'Suspension',
	'Renewal contract',
	'Resignation',
	'Termination',
	'Retirement'];

	var tableList = [];
console.log('mula loop for var');
	for (var i = 0; i < 15; i++) {
		var obj = {
			bil:i+1,
			action_type:actionTypeList[i],
			joining_group:false,
			address:false,
			family_info:false,
			academic_qualification:false,
			education_in_progress:false,
			emergency_contact:false,
			additional_personal_data:false,
			previous_employment_detail:false,
			professional_membership:false,
			professional_license:false,
			professional_education:false,
			professional_certificate:false,
			recognition:false,
			contract_element:false,
			basic_pay:false,
			bank_detail:false,
			statutory_detail:false,
			recurring:false,
			third_party:false,
			// pcb_consideration:false,
		}
		tableList.push(obj);
	};
console.log('tamat loop for var');
	// createTable();

	/* create workflow */
	$('#btn-workflows').click(function(){
		
		data = {
			token : '<?php echo $_SESSION['token']; ?>',
			name : $('#workflowName').val(),
			workflow: tableList,
		};

		// ajxRequest('<?php //echo base_url('/hr/api/staffprofiling/create_workflow'); ?>', 'POST', data, '<?php //echo current_url(); ?>');
		
		ajxRequest('<?php echo base_url('/hr/api/staffprofiling/create_workflow'); ?>', 'POST', data, '<?php echo base_url('/hr/StaffProfile/add_workflow'); ?>');
	});
});

function openEditWorkflow() {
	// var workflowID 		= $('#workflowSelect').val();

	var dataPost = 
    {
        'workflowID'      : $('#workflowSelect').val(),
    }

    $.ajax({
		url: '<?php echo base_url('hr/staffprofile/get_workflow'); ?>',
		type: 'POST',
		data:dataPost,
		dataType: 'JSON',
		success: function(data){
			localStorage.setItem("status",data.status);
			localStorage.setItem("msg",data.msg);
			
			if (localStorage.getItem("status") != null) {
				if(localStorage.getItem("status").toLowerCase() == 'success')
				{
					$('#modal_workflow_id').val(data.workflowID);
					$('#modal_workflow_name').val(data.workflowName);
				}
				if(localStorage.getItem("status").toLowerCase() == 'failed')
				{
					iziToast.error({
						position: 'bottomRight',
						title: localStorage.getItem("status"),
						message: localStorage.getItem("msg")
					});
				}
				localStorage.clear();
			}
		}
	});
}

function updateWorkflow(){
	toastConfirm('Are you sure you want to update this workflow ?', function(){
		/* edit workflow */
		data = {
			token 	: '<?php echo $_SESSION['token']; ?>',
			work_id : $('#modal_workflow_id').val(),
			name 	: $('#modal_workflow_name').val(),
		};

		// ajxRequest('<?php //echo base_url('/hr/api/staffprofiling/update_workflow'); ?>', 'POST', data, '<?php //echo current_url(); ?>');
		ajxRequest('<?php echo base_url('/hr/api/staffprofiling/update_workflow'); ?>', 'POST', data, '<?php echo base_url('/hr/StaffProfile/add_workflow'); ?>');
	});
}

</script>