<html><body>
<script>
var list_attachment_timer;
var site_url 				= "<?=site_url()?>";
var site_url_breadcrumb 	= "<?=site_url()?>";
var uri_string 				= "<?=preg_replace('/[^a-z0-9]/i', '_', (uri_string()))?>";
var n 						= uri_string.lastIndexOf('_');
var title 					= uri_string.substring(n + 1);
var a 						= uri_string.split("_"),i;
var title_list 				= '';
var count_notify 			= 0;
var breadcrumb_default 		= '';
var menu_title = $('#title_'+uri_string).val();
var menu_description = $('#description_'+uri_string).val();
var submenu 				= '';
var submenu_list 			= '';
var navigation_list 		= '';
var active_menu_list		= [];
var menu_title_nav_id		= '';
var breadcrumb_default_active = '';
var loadingButton = $( '.loadingButton' ).ladda();
var saveBtn = $( '.saveBtn' ).ladda();
var submitBtn = $( '.submitBtn' ).ladda();
var printBtn = $( '.printBtn' ).ladda();
var printBtnGl = $( '.printBtnGl' ).ladda();
var cancelBtn = $( '.cancelBtn' ).ladda();
var backBtn = $( '.backBtn' ).ladda();
var addDetailBtn = $( '.addDetailBtn' ).ladda();
var editDetailBtn = $( '.editDetailBtn' ).ladda();
var deleteDetailBtn = $( '.deleteDetailBtn' ).ladda();
var saveDetailBtn = $( '.saveDetailBtn' ).ladda();
var refreshDetailBtn = $( '.refreshDetailBtn' ).ladda();
var cancelSubmitBtn = $( '.cancelSubmitBtn' ).ladda();
var approveBtn = $( '.approveBtn' ).ladda();
var rejectBtn = $( '.rejectBtn' ).ladda();
var browseBtn = $( '.browseBtn' ).ladda();
var exportExcelBtn = $( '.exportExcelBtn' ).ladda();
var setDataModal = $('.setDataModal').ladda();
var generateInvoiceBtn = $('.generateInvoiceBtn').ladda();
var generateCoiBtn = $('.generateCoiBtn').ladda();
var input_cache_loaded = 0;

loadingButton.click(function(){
	let btn = $(this);
	startLoadingButton(btn);
	setTimeout(function(){
		stopLoadingButton(btn);
	},3000)
});

// print button di panggil di masing2 view
// printBtn.click(function(){
// 	let btn = $(this);
// 	startLoadingButton(btn);
// 	printArea();
// 	setTimeout(function(){
// 		stopLoadingButton(btn);
// 	},1000)
// });

	for (i = 0; i < a.length; i++) {
		submenu = a[i]+' ';
		if(i>0)
		{
			title_list 		+= '-> ';
			submenu_list 	+= '_';
			navigation_list += '/';
		}
		if(a.length-1 == i)
		{
			breadcrumb_default_active 	= "active";
			site_url_breadcrumb 		= window.location.href ;
			submenu						= menu_title?menu_title:a[i];
			menu_title_nav_id			= 'menu_title_nav';
		}
		submenu_list 			+= a[i].toLowerCase();
		navigation_list 		+= a[i].toLowerCase();
		site_url_breadcrumb 	= site_url+navigation_list;
		breadcrumb_default 		+= '<li class="breadcrumb-item '+breadcrumb_default_active+'"><a id="'+menu_title_nav_id+'" href="'+site_url_breadcrumb+'">'+capitalizeFistLetter(submenu)+'</a></li>';
		title_list += submenu;
		active_menu_list.push(submenu_list);
	}
	if( menu_description != '')
	{
		set_title(menu_description);
	} else
	set_title(submenu);
	<?php
if ($this->bc->get_title()) {?>
			set_title(capitalizeFistLetter('<?=$this->bc->get_title()?>'));
		<?php
}
if ($this->bc->get_title_nav()) {?>
			set_title_nav(capitalizeFistLetter('<?=$this->bc->get_title_nav()?>'));
		<?php
}
if ($this->bc->get_sub_title()) {?>
			set_sub_title(capitalizeFistLetter('<?=$this->bc->get_sub_title()?>'));
		<?php
}
if ($this->bc->getBreadcrumbCount() > 0) {
    ?>
			add_breadcrumb('<?=$this->bc->render();?>');
		<?php
} else {
    ?>
			add_breadcrumb(breadcrumb_default);
		<?php
}
$get_menu = $this->modules->get_menu();
if ($get_menu['isModules'] == 1) {
    for ($i = 0; $i <= 10; $i++) {
        ?>
			$('.btn_modules_'+'<?=$i;?>').addClass("disabled");
			<?php
}
    if (count($this->modules->get_modules_list()) > 0) {
        foreach ($this->modules->get_modules_list() as $list_modules) {
            ?>
				$('.btn_modules_'+'<?=$list_modules['fidModules'];?>').removeClass("disabled");
				<?php
}
    }
}

?>
	document.title = "<?=get_myconf('app_name')?>"+' | '+title_list;
	$(document).ready(function() {
		var arrayLength = active_menu_list.length;
		for (var i = 0; i < arrayLength; i++) {
			//Do something
			// if((arrayLength-1) == i)
			if(active_menu_list[i]!='')
			{
				$('#'+active_menu_list[i]).addClass('active');
				$('#'+active_menu_list[i]).children('ul').addClass('collapse in');
				// $('#'+uri_string).addClass('open');
				$('#'+active_menu_list[i]).parents('a').attr("aria-expanded","true");
				$('#'+active_menu_list[i]).parents('ul').attr("aria-expanded","true");
				if(active_menu_list[i]!='main')
				{
					$('#'+active_menu_list[i]).closest('ul').addClass('collapse in');
				}
				$('#'+active_menu_list[i]).parents('li').addClass('active');
			}
		}
		// Chozen Select
        $('.chosen-select').chosen({width: "100%"});
		// Date Picker
		$('.input-group.date').datepicker({
			todayBtn: "linked",
			keyboardNavigation: false,
			forceParse: false,
			calendarWeeks: true,
			autoclose: true,
			format: "dd-mm-yyyy"
		});
		// Date Range Picker
		$('#daterange .input-daterange').datepicker({
			keyboardNavigation: false,
			forceParse: false,
			autoclose: true,
			format: "dd-mm-yyyy"
		});
		// Custom Filter toggle
		$('.filter-toggle').on('click', function () {
			var ibox = $(this).closest('div.ibox');
			var button = $(this).find('i');
			var content = ibox.children('.ibox-content').children('.filter-content');
			content.slideToggle(200);
			button.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down');
			ibox.toggleClass('').toggleClass('border-bottom');
			setTimeout(function () {
				ibox.resize();
				ibox.find('[id^=map-]').resize();
			}, 50);
		});
		$('.nominal').keyup(function(event) {
			  // skip for arrow keys
			  if(event.which >= 37 && event.which <= 40){
			   event.preventDefault();
			  }

			  $(this).val(function(index, value) {
				  value = value.replace(/,/g,''); // remove commas from existing input
				  return numberWithCommas(value); // add commas back in
			  });
		});
		refreshAttachment();
	});

	// Minimalize menu
	$('.navbar-minimalize').click(function () {
	// save state in local storage
		saveUserData("mini-navbar",$('.mini-navbar').is(":visible"));
		SmoothlyMenu();
	});
	// get visibility state from local storage
	var miniNavbar = "<?=$this->session->userdata('mini-navbar')?>";
	if(miniNavbar)
	{
		if (miniNavbar == 'true') {
		// console.log('miniNavbar: ' + miniNavbar);
			$("body").removeClass('mini-navbar');
			SmoothlyMenu();
		}else{
			$("body").addClass('mini-navbar');
			SmoothlyMenu();
		}
	}

	function add_breadcrumb(breadcrumb)
	{
		$('#menu_breadcrumb').append(breadcrumb);
	}

	function capitalizeFistLetter(str)
	{
		return str.charAt(0).toUpperCase() + str.substr(1).toLowerCase();
	}

	function quotedStr(str)
	{
		return '\''+str+'\'';
	}

	function set_title(txt)
	{
		 $('#menu_title').text(txt);
	}

	function set_title_nav(txt)
	{
		 $('#menu_title_nav').text(txt);
	}

	function set_sub_title(txt)
	{
		 $('#sub_title').text(txt);
	}

/*
	function modalView(url='',title='',subtitle='',modalsize='lg',message = [])
	{
		// size : ['sm' | 'lg' | 'xl']
		var options = {
			url: "<?=site_url()?>"+url,
			title: title,
			message: message,
			size: modalsize,
			subtitle: subtitle
		};

		eModal.ajax(options);
	}*/
	
	function modalView(modalOpt ,title='',subtitle='',modalsize='lg',message = []) {
		// size : ['sm' | 'lg' | 'xl']
		/*
		 * @params allowed elements:
		 *     buttons  {array}:           An array of objects to configure buttons to modal footer; only able if message == string
		 *     css      {object}:          CSS object try apply into message body; only able if message == string
		 *     data     {object}:          Used for iframe with post data parameters              
		 *     loading  {boolean}:         Set loading progress as message.
		 *     message  {string|object}:   The body message string or the HTML element. e.g.: $(selector);
		 *     size     {string}:          sm || lg || xl -> define the modal size.
		 *     subtitle {string}:          The header subtitle string. This appear in a smaller text.
		 *     title    {string}:          The header title string.
		 *     useBin   {boolean}:         Set message as recyclable.
		 **/
		if (isset(modalOpt.url)) {
			// modalView({url:'settings/settings/profile/input/1/',title:'Edit',subtitle:'Profile'})
			modalOpt.url = "<?= site_url() ?>"+modalOpt.url
			if (!(isset(modalOpt.size))) {
				modalOpt.size = "lg";
			}
			if (isset(modalOpt.buttons)) {
				modalOpt.buttons.push({text: 'CLOSE', style: 'primary', close: true });
			}
			// modalOpt.dataType = "json";
			eModal.ajax(modalOpt);
		}else{
			// modalView('settings/settings/profile/input/1/','Edit Profile ','','lg')
			var options = {
				url: "<?=site_url()?>"+modalOpt,
				title: title,
				message: message,
				size: modalsize,
				subtitle: subtitle
			};

			eModal.ajax(options);
			// swal.fire('incomplete params','url is not defined..!','error');
			// return;
		}
	}

	function isset(variable)
	{
		return typeof(variable) != "undefined" && variable !== null;
	}

	function UrlExists(url)
	{
		var http = new XMLHttpRequest();
		http.open('HEAD', url, false);
		http.send();
		return http.status!=404;
	}

	function get_image(img_url)
	{
		var return_img = "<?=base_url()?>assets/img/no-image.png'";
		if(UrlExists(img_url))
		{
			return_img = img_url;
		}
		return return_img;
	}

	function number_format(amount, decimalCount = 0, decimal = ".", thousands = ",")
	{
	  try {
		decimalCount = Math.abs(decimalCount);
		decimalCount = isNaN(decimalCount) ? 2 : decimalCount;

		const negativeSign = amount < 0 ? "-" : "";

		let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString();
		let j = (i.length > 3) ? i.length % 3 : 0;

		return negativeSign + (j ? i.substr(0, j) + thousands : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) + (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : "");
	  } catch (e) {
		console.log(e)
	  }
	}
	// check if browser support HTML5 local storage
	function localStorageSupport() {
		return (('localStorage' in window) && window['localStorage'] !== null)
	}

	function setActiveSkin(skinIndex)
	{
		var activeSkin = '';
		if(skinIndex == "skin-1")
		{
			$("body").removeClass("skin-0");
			$("body").removeClass("skin-2");
			$("body").removeClass("skin-3");
			$("body").removeClass("md-skin");
			$("body").addClass("skin-1");
			activeSkin = "skin-1";
		}else if(skinIndex == "skin-2")
		{
			$("body").removeClass("skin-0");
			$("body").removeClass("skin-1");
			$("body").removeClass("skin-3");
			$("body").removeClass("md-skin");
			$("body").addClass("skin-2");
			activeSkin = "skin-2";
		}else if(skinIndex == "skin-3")
		{
			$("body").removeClass("skin-0");
			$("body").removeClass("skin-1");
			$("body").removeClass("skin-2");
			$("body").removeClass("md-skin");
			$("body").addClass("skin-3");
			activeSkin = "skin-3";
		}else if(skinIndex == "md-skin")
		{
			$("body").removeClass("skin-0");
			$("body").removeClass("skin-1");
			$("body").removeClass("skin-2");
			$("body").removeClass("skin-3");
			$("body").addClass("md-skin");
			activeSkin = "md-skin";
		}else {
			$("body").removeClass("skin-0");
			$("body").removeClass("skin-1");
			$("body").removeClass("skin-2");
			$("body").removeClass("skin-3");
			$("body").removeClass("md-skin");
			activeSkin = "skin-0";
		}
		if(skinIndex != '')
		{
			saveUserData("skinColor",activeSkin);
		}
	}

	function saveUserData(key,value)
	{
		$.ajax({
			type: "POST",
			url: site_url+"main/saveUserData/",
			data: {
				key:key
				,value:value
			},
			dataType: 'json',
			success: function(response)
			{
				console.log(response);
			},
			error: function( jqXhr, textStatus, errorThrown ){
				var error_message = 'internal error';
				if(jqXhr.responseJSON !== undefined)
				{
					error_message = jqXhr['responseJSON']['message'];
				}
				swal.fire('error', error_message, "error");
			}
		});
	}

	function printArea()
	{
		$("div.PrintArea").printArea( {'mode':"iframe",'popHt':500,'popWd':400,extraCss:'<?=base_url()?>assets/css/printdiv.css','popClose':true,'popTitle':'Cetak','strict':true} );
	}

	function startLoadingButton(laddaButton)
	{
		laddaButton.ladda( 'start' );
	}

	function stopLoadingButton(laddaButton)
	{
		laddaButton.ladda( 'stop' );
	}

	function logoutApp()
	{
		swal.fire({
				title: "Logout?",
				text: "Are you sure ?",
				icon: "warning",
				showCancelButton: true,
				confirmButtonText: 'Yes',
				cancelButtonText: 'No',
		}).then(isConfirm => {
			if (isConfirm.value) {
				window.location = site_url+'login/signout';
			}else{
				return false;
			}
		});
	}

	function numberWithCommas(x) {
		var parts = x.toString().split(".");
		parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
		return parts.join(".");
	}

	function format_date(dateObject) {
		var d = new Date(dateObject);
		var day = d.getDate();
		var month = d.getMonth() + 1;
		var year = d.getFullYear();
		if (day < 10) {
			day = "0" + day;
		}
		if (month < 10) {
			month = "0" + month;
		}
		var date = day + "-" + month + "-" + year;

		return date;
	}

	function arrayToObj (unindexed_array) {
		var indexed_array = {}
		$.map(unindexed_array, function (n, i) {
			indexed_array[n['name']] = n['value']
		})
		return indexed_array
	}

	$.fn.displayAttachment = function(transnum_ref) {
		let content = $(this);
		$.ajax({
			type: "GET",
			url: site_url+"main/attachment/",
			data: {
				transnum_ref : transnum_ref
			},
			dataType: 'html',
			success: function(response)
			{
    	content.show();
				content.html(response);
			},
			error: function( jqXhr, textStatus, errorThrown ){
				var error_message = 'internal error';
				if(jqXhr.responseJSON !== undefined)
				{
					error_message = jqXhr['responseJSON']['message'];
				}
				// swal('error', error_message, "error");
			}
		});
	}

	function refreshAttachment()
	{
		var pk_data = $('.pk_data').val();
		pk_data = encode(pk_data);
		$('#attachment-data').displayAttachment(pk_data);
	}

	function deptStrToArray(dept_code)
	{
		var dept_code_explode = dept_code.split(",");
		return dept_code_explode;
	}

	function deptArrayToStr(array_dept)
	{
		dept_code_joined = array_dept.join(",");
		return dept_code_joined;
	}

	function printDocHtml(print_url,opt=null)
	{
		let post = [];
		if(opt)
		{
			if(opt.post) post = opt.post;
			if(opt.button) startLoadingButton(opt.button);
		}
		$.ajax({
		        url: site_url + print_url,
		        type: 'POST',
		        dataType: 'html',
		        data: {
		            ...post
		        },
		        success: function(result) {
					$('#print-html-content').html(result);
					$('#print-html-content').printThis({
						importCSS: false,
						importStyle: false,
						canvas: true,
						copyTagClasses: false,      // copy classes from the html & body tag
						loadCSS: ["<?=base_url()?>assets/css/print-doc-html.css","<?=base_url()?>assets/css/print-doc-html-bs.css"]
					});
					if(opt) if(opt.button) setTimeout(function() { stopLoadingButton(opt.button); }, 1000);
		        },
				error: function( jqXhr, textStatus, errorThrown ){
					var error_message = 'internal error';
					if(jqXhr.responseJSON !== undefined)
					{
						error_message = jqXhr['responseJSON']['message'];
					}
					swal.fire('error', error_message, "error");
					if(opt) if(opt.button) stopLoadingButton(opt.button);
				}
            });
	}

	function printDocPdf(print_url, opt = null) {
			let post = [];
			let dataPost = [];
			if (opt) {
				if (opt.post) {
					post = opt.post;
					dataPost = JSON.stringify({
						...post
					});
				}
				if (opt.button) startLoadingButton(opt.button);
			}
			$.ajax({
				url: site_url + print_url,
				type: 'POST',
				contentType: 'application/json',
				data: dataPost,
				error: function(jqXhr, textStatus, errorThrown) {
					var error_message = 'internal error';
					if (jqXhr.responseJSON !== undefined) {
						error_message = jqXhr['responseJSON']['message'];
					}
					swal.fire('error', error_message, "error");
					if (opt)
						if (opt.button) stopLoadingButton(opt.button);
				},
				success: function(data) {
					var height = $(window).height();
					var iframe_height = (height > 200) ? height - 200 : height;
					var is_popup = 1;
					var pdf = JSON.parse(data);
					var content = "<iframe width='100%' height='" + iframe_height + "' src='data:application/pdf;base64, " + encodeURI(pdf) + "'></iframe>";
					if (is_popup) {
						var options = {
							message: content,
							size: 'xl',
							hideHeader: true
						};
						eModal.alert(options);
					} else {
						let pdfWindow = window.open("")
						pdfWindow.document.write(content);
					}
					if (opt)
						if (opt.button) setTimeout(function() {
							stopLoadingButton(opt.button);
						}, 1000);
				}
			})
		}


	function showModalUrl(url,opt=null)
	{
		let post = null;
		let title = '';
		let sub_title = '';
		let id = '';
		let size = '';
		let buttons = null;
	
		if(opt)
		{
			if(opt.post) post = opt.post;
			if(opt.button) startLoadingButton(opt.button);
			if(opt.title) title = opt.title;
			if(opt.sub_title) sub_title = opt.sub_title;
			if(opt.id) id = opt.id;
			if(opt.size) size = opt.size;
			if(opt.buttons) buttons = opt.buttons;
		}
		
		if(id === '')
		{
			swal.fire('error', 'lookup "id" belum di setting', "error");
			return false;
		}
		eModal.setId(id);
		modalView({url:url,title:title,subtitle:sub_title,data:post,size:size,buttons:buttons});
	}
  //Save the value function - save it to localStorage as (ID, VALUE)
  function setLocalStorage(id, val){
      localStorage.setItem(id, val);// Every time user writing something, the localStorage's value will override . 
  }
  //get the saved value function - return the value of "v" from localStorage. 
  function getLocalStorage  (v){
      if (!localStorage.getItem(v)) {
          return "";// You can change this to your defualt value. 
      }
      return localStorage.getItem(v);
	}
	// set input cache value
	function loadInputCache()
	{
		if(input_cache_loaded == 0)
		{
			$('.input_cached').each(function(){
				let id = $(this).attr('id');
				let val = getLocalStorage(id);
				$(this).val(val);
				$(this).val(deptStrToArray(val)).trigger("chosen:updated");
	 		});
		}
		input_cache_loaded = 1;
	}

	function storeInputCache()
	{
		$('.input_cached').each(function(){
			let id = $(this).attr('id');
			let val = $(this).val();
			// console.log(val);
			setLocalStorage(id, val);
 		});
	}

	function humanize_mdate(fDate){
		let date = fDate;
		let dateReturn = '';
		// alert(date);
		if (date){
			let yr = date.substr(0,4);
			let mn = date.substr(5,2);
			let dt = date.substr(8,2);
			let mnList = [];
			let dateReturn ='';
			mnList['01'] = ['Jan','Januari'];
			mnList['02'] = ['Feb','Februari'];
			mnList['03'] = ['Mar','Maret'];
			mnList['04'] = ['Apr','April'];
			mnList['05'] = ['Mei','Mei'];
			mnList['06'] = ['Jun','Juni'];
			mnList['07'] = ['Jul','Juli'];
			mnList['08'] = ['Ags','Agustus'];
			mnList['09'] = ['Sep','September'];
			mnList['10'] = ['Okt','Oktober'];
			mnList['11'] = ['Nov','November'];
			mnList['12'] = ['Des','Desember'];
			//
			dateReturn = dt+' '+mnList[mn][0]+' '+yr;
		}
		return dateReturn;
	}
</script>
</body></html>
