<?php
require_once('../../inc/dbcon.php');
require_once('../../inc/function.php');
require_once('../../inc/config.php');
header('Content-type: text/javascript');
ob_start("ob_html_compress" );
?>
var time =0;
myLazyLoad = new LazyLoad({
	elements_selector: "img"
});
$(document).ready(function(e) {
	$('nav, section').hide();
    noClick();
    autoRefresh();
    $(window).on("popstate", function (e) {
        loadPage();
    });
});
$(document).ajaxComplete(function(){
    	$('[title]').tooltip({trigger: "hover"});
        $('button[data-toggle="modal"]').css('z-index','3');
    });
$(window).load(function(e){
	$('nav, section').show();
	initComponent();
	console.log('avasv');
});
function noClick(){
	$("#leftsidebar a:not(.logout,.url)").click(function(e) {
            e.preventDefault();
            var hr = $(this).attr('href');
            if(hr!='javascript:void(0);' && hr!='#'){
                history.pushState(null, null, hr);
                loadPage();
            }
	});
};
function noClick2(){
	myLazyLoad.update();
	$("#hasil a:not(.url)").click(function(e) {
			e.preventDefault();
			var hr = $(this).attr('href');
			if(hr!='javascript:void(0);' && hr!='#'){
				history.pushState(null, null, hr);
                loadPage();
			}
	});
};
function loadPage(){
	time = 0;
	var p = getQueryVariable('page');
	$(".menu li[class='active']").removeAttr('class');
    $(".menu a.toggled").removeAttr('toggled').closest('li').removeAttr('active');
    $('.menu ul.ml-menu').css('display','none').closest('li').find('a').removeClass('toggled');
    if(typeof(p)=='undefined' || p=='http:' || p=='home' || p=='dashboard' || p=='<?php echo getConfig($connect, 'base_url');?>'){
    	document.title = "Dashboard - Bluepos";
        $(".ttl").text('Dashboard');
		$("a[href='<?php echo getConfig($connect, 'base_url');?>?page=home']").addClass('toggled').closest('li').addClass('active');
        $.ajax({url:'<?php echo getConfig($connect, 'base_url');?>route_ajax.php',
                data:getUrl2(),
                type:'GET',
                beforeSend: function(a){
                    Pace.stop();
                    Pace.start();
                    Pace.bar.render();
                },
                success: function(msg){
                    $("#hasil").html(msg.html);
                    var sMsg = JSON.stringify(msg);
                    savePage('home',sMsg);
                },
                error: function(a, e, t) {
                    swal({
                        title: "Terjadi kesalahan!",
                        text: formatErrorMessage(a,e),
                        type: "error",
                        showCancelButton: !1,
                        closeOnConfirm: !0
                    }, function() {
                        if(a.responseText){
                            $("#hasil").html(a.responseText);
                        }else{
                            $("#hasil").html("Error : "+formatErrorMessage(a,e));
                        }
                    });
                }
        }).done(function(){
            Pace.stop();
            initComponent();
        });
	}else{
    	var lht = getQueryVariable('lihat');
        var edt = getQueryVariable('edit');
        var hps = getQueryVariable('hapus');
        var add = getQueryVariable('add');
		$(".menu a[href='<?php echo getConfig($connect, 'base_url');?>?page="+p+"']").addClass('toggled').closest('.menu li').addClass('active').closest('.menu ul').css('display','block').closest('.menu li').find('.menu a').addClass('toggled');
		$(".menu a[href='<?php echo getConfig($connect, 'base_url');?>?page="+p+"']").closest('ul.ml-menu').closest('li').find('a').addClass('toggled');
        var pg = getPage(p);
        $.ajax({url:'<?php echo getConfig($connect, 'base_url');?>route_ajax.php',
				data:getUrl2(),
				type:'GET',
				beforeSend: function(a){
					Pace.stop();
                    Pace.start();
					Pace.bar.render();
				},
				success: function(msg){
					$("#hasil").html(msg.html);
                    document.title = msg.title+" - Bluepos";
        			$(".ttl").text(msg.title);
                    var sMsg = JSON.stringify(msg);
                    savePage(p,sMsg);
				},
                error: function(a, e, t) {
                	console.log(a.responseText);
                    swal({
                        title: "Terjadi kesalahan!",
                        text: formatErrorMessage(a,e),
                        type: "error",
                        showCancelButton: !1,
                        closeOnConfirm: !0
                    }, function() {
                        if(a.responseText){
                        	$("#hasil").html(a.responseText);
                        }else{
                        	$("#hasil").html("Error : "+formatErrorMessage(a,e));
                        }
                    });
                }
		}).done(function(){
        	Pace.stop();
            initComponent();
        });
	}
};
function getPathVariable(variable) {
  var path = location.pathname;
  var parts = path.substr(1).split('/'), value;
  if(!variable){
  	value = parts[0];
  }else{
      while(parts.length) {
        if(parts.shift() === variable){
            value = parts.shift();
        }else{
            parts.shift();
        }
      }
  }
  return value;
};
function autoRefresh(){
	var inRef = setInterval(function(){
    						time++;
                            if(time==120){
                            	loadPage();
                             }
                             if($(".modal").length>0){
                             	if(!$(".modal").is(':hidden')){
                             		time=0;
                             	}
                             }
                             if(getUrlVars()['lihat'] || getUrlVars()['edit'] || getUrlVars()['add'] || getUrlVars()[0]=='home'){
                             	time =0;
                             }
                             },1000);
    $(document).keydown(function(e){
    	time = 0;
    });
}
function getUrl2(){
	var search = location.search.substring(1);
	return JSON.parse('{"' + decodeURI(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')
};
function getQueryVariable(variable){
       var query = window.location.search.substring(1);
       var vars = query.split("&");
	   var jurl = {};
       for (var i=0;i<=vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){
			      return pair[1];
			   }else{
			      return JSON.parse('{"'+pair[0]+'":"'+pair[1]+'"}');
			   }
       }
       return '';
};

function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('#') + 1).split('!');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
};
function autoFocusModal(){
	$('button[data-toggle="modal"], a[data-toggle="modal"]').click(function(e) {
            var tg = $(this).attr('data-target');
			setTimeout(function(){
					$(tg+" form .form-line >*:first").focus();	
			},100);
     });
};
function cekNotif(){
	$.ajax({url:'<?php echo getConfig($connect, 'base_url');?>processData.php',
			type:'POST',
			data:{p:'cek-notif'},
			success: function(a){
				if(a.jml>0){
					$(".label-count").text(a.jml);
					var phtml='<li> <a href="<?php echo getConfig($connect, 'base_url');?>#konfirmasi-barang" class="waves-effect waves-block">'+
							  '<div class="icon-circle bg-orange"> <i class="material-icons">assignment_ind</i> </div>'+
							  '<div class="menu-info"><h4>'+a.jml+' Barang Menunggu konfirmasi</h4>'+
							  '<p> <i class="material-icons">access_time</i> '+a.time+'</p></div></a></li>';
				}else{
					$(".label-count").text('');
					var phtml= '<li class="waves-effect waves-block" style="padding:10px"><div class="icon-circle bg-light-green"> <i class="material-icons">check_circle</i> </div>'+
								'<div class="menu-info"><h4><em>Tidak ada notifikasi</em></h4><p><em>=======</em></p></div></li>';
				}
				$(".notif-list").html(phtml);
				activateNotificationAndTasksScroll();
			}
	});
};
function notif(pesan){
	$.notify({message: pesan},
    		 {type: 'warning',
              allow_dismiss: true,
              newest_on_top: true,
              timer:1500,
              delay:1500,
              placement: {from: 'top',align: 'right'},
              animate: {enter:'animated bounceInRight',exit:'animated bounceOutRight'}
             });
};
function initComponent() {
    $.AdminBSB.input.activate();
    $.AdminBSB.select.activate();
    $.AdminBSB.table.activate();
    $.AdminBSB.DatePicker.activate();
    $.AdminBSB.summerNote.activate();
    $.AdminBSB.formValidate.activate();
    initAjax();
    initFormatNumber();
    $('.back').click(function(e) {
    	self.history.back();
	});
    $(".img-remove").click(function(e){
    	$(".img-view").remove();
        $(".fdata").val("");
        $(".inputFile").val("");
    });
    $('[data-toggle="modal"]').click(function(e){
    	var mdl = $(this).data("target");
        $(mdl+" form")[0].reset();
    });
    autoFocusModal();
    if($(".timepicker").length>0){
    	$(".timepicker").timepicker();
    }
    Pace.ignore(function(){
  		cekNotif();
	});
    noClick2();
	myLazyLoad.update();
};

function validateImage(elmt){
	$('.page-loader-wrapper').show();
    var rId = getRndInteger(0,99);
	var val = $(elmt);
    var reader = new FileReader();
    var fdata = $(elmt)[0].files[0];
    var ename = $(elmt).attr('name');
    var n_elm = '<input type="hidden" class="fdata" name="'+ename+'" id="'+rId+'_gambar">';
    $(n_elm).insertAfter(elmt);
    switch(val.val().substring(val.val().lastIndexOf('.') + 1).toLowerCase()){
        case 'gif': case 'jpg': case 'png': case 'jpeg' : case 'bmp' : case 'webmp' :
        	reader.onload = function(e) {
            	val.attr('id',rId+"_input");
            	$("#"+rId+"_gambar").val(reader.result);
                $('.img-view').remove();
                var html ='<p align="center" class="img-view" id="'+rId+'_img" style="text-align:center;"><img src="'+reader.result+'" style="max-height:100px;" class="center"><button type="button" class="btn bg-red waves-effect no-padding btn-xs img-remove" onClick="$(\'.img-view\').remove();$(\'#'+rId+'_gambar\').remove();$(\'#'+rId+'_input\').val(\'\');"><i class="material-icons">delete</i></button></p>';
                $(html).insertAfter("#"+rId+"_gambar");
                $('.page-loader-wrapper').fadeOut();
			};
            reader.readAsDataURL(fdata);
            $('.page-loader-wrapper').fadeOut();
            break;
        default:
            val.val('');
            $('.page-loader-wrapper').fadeOut();
            break;
    };
};

function validateExcel(elmt){
	var val = $(elmt);
    switch(val.val().substring(val.val().lastIndexOf('.') + 1).toLowerCase()){
        case 'xls': case 'xlsx':
        	
            break;
        default:
            val.val('');
            swal({
                    title: "Pilih File Excel!",
                    text: "Pilih Hanya file Excel (xls,xlsx)",
                    type: "error",
                    showCancelButton: !1,
                    closeOnConfirm: !0
                });
            break;
    };
};

function cekImage(elm){
	var val = $(elm);
    if(val.val()){
        switch(val.val().substring(val.val().lastIndexOf('.') + 1).toLowerCase()){
            case 'gif': case 'jpg': case 'png': case 'jpeg' : case 'bmp' : case 'webmp' :
                return true;
            break;
            default:
                val.val('');
                swal({
                    title: "Pilih Foto!",
                    text: "Pilih Hanya Foto",
                    type: "error",
                    showCancelButton: !1,
                    closeOnConfirm: !0
                });
            break;
        }
    }
};

function formatErrorMessage(jqXHR, exception) {
    if (jqXHR.status === 0) {
        return ('Tidak bisa terhubung ke server.\nPerika koneksi internet anda!');
    } else if (jqXHR.status == 404) {
        return ('Halaman yang diminta tidak tersedia');
    } else if (jqXHR.status == 500) {
        return ('Internal Server Error');
    } else if (exception === 'parsererror') {
        return ('Requested JSON parse failed.');
    } else if (exception === 'timeout') {
        return ('Timeout error \nSilahkan coba lagi.');
    } else if (exception === 'abort') {
        return ('Ajax request aborted.');
    } else {
        return ('Uncaught Error.\n' + jqXHR.responseText);
    }
};

function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min) ) + min;
};
String.prototype.capitalize = function() {
     return this.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
};
function initFormatNumber(){
	var $form = $("form");
	var $input = $form.find("input.formatNumber"); 
    if ($form.length>0 && $input.length>0){
    	$form.ready(function(e){
        	$input.each(function(index, element) {
                var $val = $(this).val();
                var $newVal1 = $val.replace(/[\D\s\._\-]+/g, "");
                $newVal1 = $newVal1 ? parseInt($newVal1, 10 ) : 0;
                var $newVal2 = $newVal1.toLocaleString("id-ID");
                $(this).val($newVal2);
            });
    	});
        $input.keyup(function(e) {
            var selection = window.getSelection().toString();
            if ( selection !== '' ) {
                return;
            }
            if ( $.inArray( event.keyCode, [38,40,37,39] ) !== -1 ) {
                return;
            }
            var $this = $(this);
            var input = $this.val();
            var input = input.replace(/[\D\s\._\-]+/g, "");
            input = input ? parseInt( input, 10 ) : 0;
            $this.val( function() {
                return ( input === 0 ) ? "" : input.toLocaleString( "id-ID" );
            });
        });
    }
};
function savePage(pageName, sData){
	if(!window.localStorage || typeof(Storage)=='undefined'){
		return false;
	}else{
		/*window.localStorage.setItem(pageName,sData);*/
		return true;
	}
};

function getPage(pageName){
	if(!window.localStorage || typeof(Storage)=='undefined'){
		return false;
	}else{
		var sData = window.localStorage.getItem(pageName);
		if(sData){
			var jData = JSON.parse(sData);
			return jData.html;
		}else{
			return false;
		}
	}
};
function getChartJs(type,cdata,customLabels) {
    var config = null;
	if (type === 'bar') {
        config = {
            type: 'bar',
            data: {
                labels: (customLabels)?customLabels:["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus","September","Oktober","November","Desember"],
                datasets: JSON.parse(cdata)
            },
            options: {
                responsive: true,
                legend: {show: true}
            }
        }
    }else if (type === 'horizontalBar') {
        config = {
            type: 'horizontalBar',
            data: {
                labels: (customLabels)?customLabels:["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus","September","Oktober","November","Desember"],
                datasets: JSON.parse(cdata)
            },
            options: {
                responsive: true,
                legend: false
            }
        }
	}else if (type === 'line') {
        config = {
            type: 'line',
            data: {
                labels: (customLabels)?customLabels:["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus","September","Oktober","November","Desember"],
                datasets: JSON.parse(cdata)
            },
            options: {
                responsive: true,
                legend: false
            }
        }
    }else if(type=='pie'){
			rdata = JSON.parse(cdata);
			config = {
				type: 'pie',
				data: rdata,
				options: {
					responsive: true,
					legend: {show: true}
				}
			};

	}
    return config;
}
<?php
ob_end_flush();
?>