<?php
ob_start();
date_default_timezone_set('Asia/Bangkok');
error_reporting(E_ALL);
ini_set('display_errors',0);
session_start();
// FOR DEBUG ONLY
if (isset($_GET['php']) and $_GET['php'] == 'info') {
    die(phpinfo());
}

function recurse_copy($src,$dst) { 
    $dir = opendir($src); 
    @mkdir($dst); 
    while(false !== ( $file = readdir($dir)) ) { 
        if (( $file != '.' ) && ( $file != '..' )) { 
            if ( is_dir($src . '/' . $file) ) { 
                recurse_copy($src . '/' . $file,$dst . '/' . $file); 
            } 
            else { 
                copy($src . '/' . $file,$dst . '/' . $file); 
            } 
        } 
    } 
    closedir($dir); 
} 

// SEARCH HELPER FUNCTION
function contains(array $array, $string) {
    $count = 0;
    foreach ($array as $value) {
        if (false !== stripos($string, $value)) {
            ++$count;
        }
    }
    return $count == count((array)$array);
}
// START & CONFIG

require 'setup/config.php';
$LANG =  'cn';
// SET LANGUAGE
if (isset($_GET['lang'])){	
	$_SESSION['HTTP_ACCEPT_LANGUAGE'] = $_GET['lang'];
}
if (isset($_SESSION['HTTP_ACCEPT_LANGUAGE']) and file_exists('lang/' . $_SESSION['HTTP_ACCEPT_LANGUAGE'] . '.php')) {	
	if((@include 'lang/' . $_SESSION['HTTP_ACCEPT_LANGUAGE'] . '.php') === false){
		echo 'Caught exception: Translate file is wrong';
	}else{
		@include_once('lang/' . $_SESSION['HTTP_ACCEPT_LANGUAGE'] . '.php');
	}
} else {
	if((@include 'lang/' . $LANG . '.php') === false){
		echo 'Caught exception: Translate file is wrong';
	}else{
		@include_once('lang/' . $LANG . '.php');
	}
}
// INI VARs
$found = 0;                     	// MARKER HOW MANY HITS FOUND A SEARCH
$done = 0;                     		// MARKER HOW MANY ENTRYs ARE DONE
$msg = '';                    		// TOAST MESSAGE
$file = 'data/' . $TYPE . '.json';  // DATA FILE NAME

// LOGIN CHECK
$login = check_current_user_login($ARR_USERS, $SALT);
$currentuser = $login['user'];

$currencydate = date('Ymd');
if($_GET['currencydate'] != ''){
	$currencydate = $_GET['currencydate'];
}
$currency = json_decode(file_get_contents('data/Currency.json'), true);

if(!file_exists('currency/'.str_replace('-','',$currencydate) ) ){
	
	$superrich1965 =  json_decode(file_get_contents("https://superrichrate2.ztidev.com/sprrate/api/v1/rates/locations/33"));
	foreach ($superrich1965 as $r){
		if($r->currencyCode == 'CNY'){
			$rmbtobath =  $r->buy;
			break;
		}
	}
	$bankofchina = file_get_contents("http://srh.bankofchina.com/search/whpj/search.jsp?pjname=1316");
	$bankofchina = explode('<td>美元</td>',$bankofchina);
	$bankofchina = explode('</td>',$bankofchina[1]);
	$bankofchina = explode('<td>',$bankofchina[0]);
	$bankofchina = $bankofchina[1]/100;
	
	
	$hsbc = file_get_contents("https://www.hsbc.com.vn/foreign-exchange/rate/");
	$hsbc = explode('<td width="619">',$hsbc);
	$hsbc = explode('</td>',$hsbc[1]);
	$hsbc = str_replace(',','',$hsbc[0]); 
	
	$currencytoday = file_get_contents('http://www.floatrates.com/historical-exchange-rates.html?currency_date='.$currencydate.'&base_currency_code=CNY&format_type=html');
	$currencytoday = explode('bk-currency-rates',$currencytoday);
	$currencytoday = explode('</table>',$currencytoday[1]);
	$currencytoday =  $currencytoday[0];
	
	$currencytoday = explode('<tr>',$currencytoday);
	
	
	
	foreach ($currencytoday as $r){
		if(strpos($r,'USD') !==false  ){
			$r = explode('align="right">',$r);
			$r = explode('</td>',$r[2]);
			$r = $r[0]; 
			if($bankofchina > 0){
				$r = $bankofchina;
			}
			$ar['USD'] = $r;			
			foreach ($currency as $key => $ru){
				if('USD' == $ru['currency'] && $r > 0){
					$currency[$key]['exchangerate'] = round($r,4);
				}
			}
		}
		if(strpos($r,'VND') !==false ){
			$r = explode('align="right">',$r);
			$r = explode('</td>',$r[2]);
			$r = $r[0];
			$ar['VND'] = $r;
			foreach ($currency as $key => $ru){
				if('VND' == $ru['currency'] && $r > 0){
					//$currency[$key]['exchangerate'] = $r;
					$ar['VND'] = $currency[$key]['exchangerate'];
				}
			}
		}
		
		if(strpos($r,'THB') !==false ){
			$r = explode('align="right">',$r);
			$r = explode('</td>',$r[2]);
			$r = $r[0];
			if($rmbtobath > 0){
				$r = 1/$rmbtobath;
			}
			$ar['THB'] = $r;
			foreach ($currency as $key => $ru){
				if('Baht' == $ru['currency'] && $r > 0){					
					$currency[$key]['exchangerate'] = round($r,4);
				}
			}
		}
	}
	$ar['USDVND'] = $hsbc;
	foreach ($currency as $key => $ru){
		if('USDVND' == $ru['currency'] && $hsbc > 0){					
			$currency[$key]['exchangerate'] = $hsbc;
		}
	}
	
	file_put_contents('currency/'.str_replace('-','',$currencydate), json_encode($ar) );
	file_put_contents('data/Currency.json',json_encode(array_values($currency)));
	
}



if ($_GET['import'] != ''){
	$_SESSION['import'] = $_GET['import'];
}
if ($currencyUser == ''){
	$currencyUser = '1560829223';
}
if ($_GET['currency'] != ''){
	$currencyUser = $_GET['currency'];
	
	foreach ($currency as $r){
		if($currencyUser == $r['id']){
			$_SESSION['currencyUser'] = $r;
		}
	}
}
if($_SESSION['currencyUser'] == ''){
	foreach ($currency as $r){
		if($currencyUser == $r['id']){
			$_SESSION['currencyUser'] = $r;
		}
	}
}


if ($login['status'] == 200) {
    // make backup
    $backup = __DIR__."/backup/";
    if (!file_exists($backup)) {
        mkdir($backup, 0777);
    }// backup today
	
	// check file toan ven
	if(count(json_decode(file_get_contents('data/Noti.json'))) == 0){
		$folder = scandir(__DIR__."/backup/", SCANDIR_SORT_DESCENDING);	
		copy(__DIR__."/backup/".$folder[1].'/Noti.json', __DIR__."/data/Noti.json"  );  
	}
	if(count(json_decode(file_get_contents('data/mywork.json'))) == 0){
		$folder = scandir(__DIR__."/backup/", SCANDIR_SORT_DESCENDING);	
		copy(__DIR__."/backup/".$folder[1].'/mywork.json', __DIR__."/data/mywork.json"  );  
	}
	if(count(json_decode(file_get_contents('data/TabDoc.json'))) == 0){
		$folder = scandir(__DIR__."/backup/", SCANDIR_SORT_DESCENDING);	
		copy(__DIR__."/backup/".$folder[1].'/TabDoc.json', __DIR__."/data/TabDoc.json"  );  
	}
	if(count(json_decode(file_get_contents('data/Documents.json'))) == 0){
		$folder = scandir(__DIR__."/backup/", SCANDIR_SORT_DESCENDING);	
		copy(__DIR__."/backup/".$folder[1].'/Documents.json', __DIR__."/data/Documents.json"  );  
	}
	if(count(json_decode(file_get_contents('data/Tabs.json'))) == 0){
		$folder = scandir(__DIR__."/backup/", SCANDIR_SORT_DESCENDING);	
		copy(__DIR__."/backup/".$folder[1].'/Tabs.json', __DIR__."/data/Tabs.json"  );  
	}	
	if(count(json_decode(file_get_contents('data/Setting.json'))) == 0){
		$folder = scandir(__DIR__."/backup/", SCANDIR_SORT_DESCENDING);	
		copy(__DIR__."/backup/".$folder[1].'/Setting.json', __DIR__."/data/Setting.json"  );  
	}
	if(count(json_decode(file_get_contents('data/User.json'))) == 0){
		$folder = scandir(__DIR__."/backup/", SCANDIR_SORT_DESCENDING);	
		copy(__DIR__."/backup/".$folder[1].'/User.json', __DIR__."/data/User.json"  );  
	}
    $backuptoday = $backup.date('YmdH').'/';  
    if (!file_exists($backuptoday)) {
      recurse_copy(__DIR__."/data/",$backuptoday);  
    }
	
	
} else {
    header('location: login.php');
    exit;
}

$ip = getenv('HTTP_CLIENT_IP')?:
	getenv('HTTP_X_FORWARDED_FOR')?:
	getenv('HTTP_X_FORWARDED')?:
	getenv('HTTP_FORWARDED_FOR')?:
	getenv('HTTP_FORWARDED')?:
	getenv('REMOTE_ADDR'); 

//file_put_contents('ipdata',$ip);


$tabs = json_decode(file_get_contents('data/Tabs.json'));
foreach($tabs as $r){
	$tabsname[$r->id] = $r->name;
}
$user = json_decode(file_get_contents('data/User.json'));
$tabdocfull = $tabdoc = json_decode(file_get_contents('data/TabDoc.json'));
$tabfull = $tabs;
$Setting = json_decode(file_get_contents('data/Setting.json'));
$receiver_payer = json_decode(file_get_contents('data/receiver_payer.json'));
foreach ($receiver_payer as $r){
	$receiver_payer_name[$r->name] = $r;
	$receiver_payer_id[$r->id] = $r;
}

if($currentuser->role == 'Operator' || ( $currentuser->role == 'Manager' && $currentuser->gm != 1 )  ){	
	if($currentuser->location == '总公司' && !in_array( $ip , explode(',',$Setting->ipmain)) && $Setting->ipmain != ''  ){
		if($currentuser->cherry != 1){header('location: login.php');exit;} $cannotedit = 1;
	}
	if($currentuser->location == '越南' && !in_array( $ip , explode(',',$Setting->ipvn)) && $Setting->ipvn != '' ){
		if($currentuser->cherry != 1){header('location: login.php');exit;} $cannotedit = 1;
	}	
	if($currentuser->location == '中国' && !in_array( $ip , explode(',',$Setting->ipcn)) && $Setting->ipcn != '' ){
		if($currentuser->cherry != 1){header('location: login.php');exit;} $cannotedit = 1;
	}		
	if($currentuser->location == '泰国'  && !in_array( $ip , explode(',',$Setting->iptha)) && $Setting->iptha != '' ){
		if($currentuser->cherry != 1){header('location: login.php');exit;} $cannotedit = 1;
	}		
}
if($currentuser->role == 'Finance' && $Setting->ipcontroller != '' && !in_array( $ip , explode(',',$Setting->ipcontroller)) ){	
	header('location: login.php');exit;
}

// READ DATA
$newdata = array();
$data = json_decode(file_get_contents($file), true);
// HEADER


include 'tpl/header.php';


?>
<style>
.navbar-fixed {
	display:none;
}
</style>
<script src="tpl/js/jquery-ui.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<style>  
.nofulltext p {		padding: 0px;		margin: 0px;	}.tab-content { min-width: 100%; } .section.no-pad-bot { padding-bottom: 0; padding-top: 0; } tfoot td { padding: 7px 0px; } table.tablesorter tbody td, table.tablesorter thead tr th { border: 1px solid #ccc; } table.tablesorter thead tr th { background-color: #1b278a; color: #fff; } table.striped tr { cursor: pointer; } table.tablesorter tbody td { vertical-align: middle; } table.tablesorter tbody td { padding: 0px; } .helper-text { display:none!important; } .input-field { position: relative;  margin-bottom: 5px; } #modal5 { min-width: 1150px; } .ui-resizable-se { display:none!important; } .ui-resizable-s { height: 10px; bottom: -5px; } li.disabled{ display:none; } #tabnameSave { position: relative; margin-right: 24px; transform: none; } .modal-fixed { width: 600px !important; } .nofulltext { display:block!important; height: 19px; overflow: hidden; width: calc(100% - 20px); float: left; word-break: break-all; } .fa-sort-down { width: 17px; float: left; } i.fas.fa-sort-down.active { transform: rotateX(180deg); margin-top: 8px; } .responsive-table .btn { line-height: 26px; height: 26px; } .JCLRgrips { display:none!important; } #toast-container{  position: fixed; z-index: 1000; } .filtervendor .select-wrapper { position: absolute; top: 0px; } .filtervendor input { border: none!important; opacity: 0; } .filtervendor svg{ color:#ffffff!important; fill: rgba(255, 255, 255, 0.87)!important; } .filtervendor ul{ min-width: 250px; max-height: 350px; overflow: auto; } } .bsdbk ul li:first-child input , .bsdbk ul li:last-child input , .filtervendor ul li:first-child input { display:none; } .bsdbk ul li:first-child span:before , .bsdbk ul li:last-child span:before , .filtervendor ul li:first-child span:before { display:none; } .bsdbk ul li:first-child ,.bsdbk ul li:last-child , .filtervendor ul li:first-child { text-decoration: none; background-color: #26a69a!important; text-align: center; letter-spacing: .5px; -webkit-transition: background-color .2s ease-out; transition: background-color .2s ease-out; cursor: pointer; } .bsdbk ul li:first-child:hover , .bsdbk ul li:last-child:hover ,.filtervendor ul li:first-child:hover { background-color: #117d73!important; } .bsdbk ul li:first-child [type="checkbox"]+span:not(.lever) , .bsdbk ul li:last-child [type="checkbox"]+span:not(.lever) , .filtervendor ul li:first-child [type="checkbox"]+span:not(.lever) { color: #fff!important;padding-left:0px; } textarea.nofulltext{ border: none; resize: none; line-height: 21px; } table.tablesorter tbody tr:hover td { background: #fffadc; } thead .tr_total td { padding-top:3px; padding-bottom:3px; } th .dropdown-content li>a, .dropdown-content li>span { padding: 4px 10px; } th .dropdown-content li { min-height: 34px; line-height: 16px; } th.filtervendor ul { min-width: 315px; top: 53px!important; } .bsdbk { position: relative; } .bsdbk .select-wrapper { position: absolute; left: -30px; top: 10px; z-index: 1000; } .bsdbk .caret {     margin-top: 7px; width: 36px; height: 36px; fill: rgb(38, 166, 154); box-shadow: 0px 0px 3px #545454a6; } .bsdbk .select-wrapper input.select-dropdown { width: 30px; border: none; color: transparent; } .bsdbk .dropdown-content { min-width:250px; top: 45px!important; } .bsdbk .dropdown-content li { min-height: 20px; } /*PRELOADING------------ */ #overlayer { width:100%; height:100%; position:fixed; z-index:10000; background:rgba(0, 0, 0, 0.97); left:0px; filter:blur(4px); -o-filter:blur(4px); -ms-filter:blur(4px); -moz-filter:blur(4px); -webkit-filter:blur(4px); } .loader { display: inline-block; width: 30px; height: 30px; position: fixed; z-index:30000; border: 4px solid #Fff; top: 50%; animation: loader 2s infinite ease; left: 50%; top: 50%; transform: translate(-50%, -50%); } .loader-inner { vertical-align: top; display: inline-block; width: 100%; background-color: #fff; animation: loader-inner 2s infinite ease-in; } @keyframes loader { 0% { transform: rotate(0deg); } 25% { transform: rotate(180deg); } 50% { transform: rotate(180deg); } 75% { transform: rotate(360deg); } 100% { transform: rotate(360deg); } } @keyframes loader-inner { 0% { height: 0%; } 25% { height: 0%; } 50% { height: 100%; } 75% { height: 100%; } 100% { height: 0%; } } .some-css-class { left: 50%!important; transform: translateX(-50%); } table { /* Not required only for visualizing */ border-collapse: collapse; width: 100%; } table thead tr:nth-child(1) th { /* Important background-color: red; */ position: sticky; z-index: 100; top: 0; } .makesimilarlabel .caret{ margin-top: -25px;    right: -55px; } .isleft{ width: 50px; height: 50px; position: fixed; left: 15px; top: 45%; z-index: 1000000; font-size: 54px; opacity: 0.2;cursor: pointer; } .isright{ width: 50px; height: 50px; position: fixed; right: 15px; top: 45%; z-index: 1000000; font-size: 54px; opacity: 0.2;cursor: pointer; } .isleft:hover , .isright:hover{ opacity: 0.5; } .isleft i , .isright i { } #toast-container { top: 10px; max-width: 100%; } .toast.rounded { border-radius: 24px; height: 30px; } .collapsible-body{ background: rgb(218, 219, 219); position: absolute; padding: 0px 15px 0px 5px!important; min-width: 300px; margin-top: 6px; } .ui-autocomplete { top: 134px!important; margin-left: -6px!important; max-height:500px; overflow:auto; } .ui-autocomplete li { border-bottom: 1px solid; cursor:pointer; padding-left: 10px!important; } .ui-autocomplete li:nth-child(even) { background: #f0f0f0; } .ui-autocomplete li:nth-child(even) { background: #eee; } #project::placeholder { /* Firefox, Chrome, Opera */ color: #000; } #project:-ms-input-placeholder { /* Internet Explorer 10-11 */ color:#000; } #project::-ms-input-placeholder { /* Microsoft Edge */ color:#000; } .classdash1:after { content:'-1'; }
.filtervendor svg { display:none; }
.dnoon { color:#fff; }
.iopd::after {
    display:none!important;
}
.ishighlight{
	border:3px solid #9e9b0a !important;
}
.ishighlight img{
filter: none!important;
display:block!important;
}
.navbar-fixed nav {
    overflow: unset;
}
</style>

<div id="overlayer" style="display:none;" ></div>
<span class="loader" style="display:none;" >
  <span class="loader-inner"></span>
</span>
<?php if($_SESSION['import'] != 1 && 0 == 1){ ?>
<?php } if($_GET['onlyform'] == 1) { ?>
<style>  
	.navbar-fixed {
		display:none;
	}
	body{
		overflow: hidden;
		background: transparent;
	}
	html{
		background: transparent;
	}
	.row {   
		margin-bottom: 0px;
	}
	
</style>  
<?php } ?>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">

    
	
    <?php
	
  $table = '<table style="    position: relative;width: 100%!important;'.$isdho2.' margin-top: 40px;" class="striped responsive-table tablesorter "    >
  <thead>
  <tr>';
  if ($currentuser->role == 'Manager' ) {
  $table .= '<th style="text-align:center;width:140px;"></th>';
  }elseif ( $currentuser->role == 'Operator') {
  $table .= '<th style="text-align:center;width:140px;"></th>';
  }
  $table .= '<th style="text-align:center;width:0px;"></th>';
  $table .= '<th style="width:65px;    background-image: none;" >'.$i18n['日期'].'</th>
  <th style="width:65px;" >'.$i18n['Modified'].'</th> 	
  <th style="width:70px;" class="filtervendor" >'.$i18n['收/付'].'   </th> 
  <th style="width:100px; background-image: none;    z-index: 100;"  class="filtervendor"  >'.$i18n['费用归类'].' </th>
  <th style="width:100px; background-image: none;    z-index: 100;"  class="filtervendor"  >'.$i18n['费用明细'].'  
  </th>
  <th class="havepecial" style="display:none;width:50px;" ><input class="" type="text" placeholder="搜: '.$i18n['部门'].'" /></th>
  <th class="havepecial2" style="display:none;" >'.$i18n['Bill No.'].'</th>
  <th class="havepecial2" style="display:none;" >'.$i18n['Bill to'].'</th>
  <th class="havepecial2" style="display:none;" >'.$i18n['增值税'].'</th>
  <th class="havepecial2" style="display:none;" >'.$i18n['预扣税'].'</th>
  <th style="width:150px;padding: 0 10px;" ><input class="dnoon" ref="1" type="text" placeholder="搜: '.$i18n['摘要'].'" /></th>
  <th style="width:105px;" class="dbjiie"  >'.$i18n['收入金额'].' <span  class="havepecial3" style="display:none;" >USD</span></th>
  <th style="width:105px;" class="dbjiie" >'.$i18n['支出金额'].' <span  class="havepecial3" style="display:none;" >USD</span></th>
  <th class="havepecial3" style="display:none;width: 125px;" >汇率 USD-VND</th>
  <th class="havepecial3" style="display:none;" >折VND</th>
  <th class="havepecial3" style="display:none;" >支出VND</th>  
  <th style="width:105px;"  >'.$i18n['余额'].'</th>
  <th style="width:106px;     background-image: none;    z-index: 100;" class="filtervendor" >'.$i18n['收付款人'].'</th>
  <th style="width:140px;padding: 0 10px;" ><input class="dnoon" ref="2" type="text" placeholder="搜: '.$i18n['催/请款单号'].'" /></th>
  <th style="width:115px;padding: 0 10px;"  ><input class="dnoon" ref="3" type="text" placeholder="搜: '.$i18n['凭证号'].'" /></th>
  <th style="width:85px;" >'.$i18n['是否核销'].'</th>
  <th style="min-width:55px;" >'.$i18n['文件'].'</th>
  <th style="min-width:55px;" >'.$i18n['备注'].'</th>';
  $table .= '<th style="text-align:center;width:119px;">'.$i18n['审核'].'</th>';
  $table .= '</tr>
  <tr class="treopit modal-trigger" data-target="showmoreinfo"   style="    position: absolute;    top: -40px;    width: 100%;    text-align: center;" >
	<td  colspan="14" style="display: block; text-align: center;   width: 100%;  padding: 5px;    font-weight: bold;    font-size: 18px;"  >'.$tab->info.'<span class="tabdescription" style="display:none;" >'.$tab->tabdescription.'</span></td>
  </tr>
  ';
  
  if ($currentuser->role == 'Manager' || $currentuser->role == 'Operator') {
  $table .='<tr class="tr_total"><td colspan="8" >'.$i18n["From"].':All - '.$i18n["To"].':All</td><td class="havepecial" style="display:none;"  >&nbsp;</td><td class="havepecial3" colspan="3" style="display:none;"  >&nbsp;</td><td class="havepecial2" colspan="4" style="display:none;"  >&nbsp;</td><td  colspan="2" style="padding-left:6px!important;text-align:right;" >'.$i18n["Balance Left"].' ('.$currencyname.')</td><td  style="    font-weight: normal;padding-left:6px!important;" >N/A</td><td>&nbsp;</td><td colspan="6"  style="text-align:right;" >汇买价 N/A</td></tr>';
  }else{
  $table .='<tr class="tr_total"><td colspan="8" >'.$i18n["From"].':All - '.$i18n["To"].':All</td><td class="havepecial" style="display:none;"  >&nbsp;</td><td class="havepecial3" colspan="3" style="display:none;"  >&nbsp;</td><td class="havepecial2" colspan="4" style="display:none;"  >&nbsp;</td><td  colspan="1" style="padding-left:6px!important;text-align:right;" >'.$i18n["Balance Left"].' ('.$currencyname.')</td><td  style="    font-weight: normal;padding-left:6px!important;" >N/A</td><td>&nbsp;</td><td  colspan="6"   style="text-align:right;" >汇买价 N/A</td></tr>';
    
  }
  $table .='</thead>
  <tbody>';
 
  foreach ($data as $key => $values) {
		if(!is_array($values['payer'])){
				$values['payer'] = array($values['payer']);
		}
			
		if( !in_array($_GET['id'],$values['payer']) && !in_array($_GET['name'],$values['payer']) ){
			continue;
		}
			
		if($values['status'] == ''){
			$table .= '<tr class="'.$rowclass.'" style="'.$baddebt.'" >';
		}elseif($values['status'] == 'pending'){
			$table .= '<tr class="'.$rowclass.'" style="background-color: #dddddd;'.$baddebt.'" >';
		}elseif($values['status'] == 'approval'){
			$table .= '<tr class="'.$rowclass.'" style="background-color: #d1f9a9;'.$baddebt.'"  >';
		}elseif($values['status'] == 'notapproval'){
			$table .= '<tr class="'.$rowclass.'" style="background-color: #ffe5e5;'.$baddebt.'" >';
		}
		
        if ($currentuser->role == 'Manager' ) {
            $table .= '<td style="text-align:left;">
			<b>'.$tabsname[$values['tabs']].'</b>
			<a style="display:none;" href="#" data-target="modal5" class="modal-trigger editmode" ref="edit.php?id=' . $values['id']  . '" ><i class="grey-text small ' .
                    'material-icons">mode_edit</i></a>';
            $table .= '';
        }
		
		$file = ''; 
		
		
		if(  $cannotedit == 1 || ($currentuser->role == 'Operator' && !in_array($tab->id,$currentuser->account) && in_array($tab->id,$currentuser->accountreadonly))){
					$table .= '<td style="text-align:center"><b>'.$tabsname[$values['tabs']].'</b></td>';
		}else{
			if ($currentuser->role == 'Operator' && ( $values['status'] == '' ) ){
					$table .= '<td style="text-align:center"><b>'.$tabsname[$values['tabs']].'</b></td>';
			}elseif ($currentuser->role == 'Operator') {
					$table .= '<td style="text-align:center"><b>'.$tabsname[$values['tabs']].'</b></td>';
			}	
		}
		if( $currentuser->role == 'Operator' && !in_array($tab->id,$currentuser->account) && in_array($tab->id,$currentuser->accountreadonly)){
				$editmode = '';
		}else{
			if( $currentuser->role == 'Finance' ){
				$editmode = '<a style="display:none;" href="#" data-target="modal5" class="modal-trigger editmode" ref="edit.php?id=' . $values['id']  . '" ><i class="grey-text small ' .
			'material-icons">mode_edit</i></a>';
			}elseif ( ($currentuser->role == 'Operator' ) && ( $values['status'] == '' ||  $values['status'] == 'notapproval' )) {
				$editmode = '<a style="display:none;" href="#" data-target="modal5" class="modal-trigger editmode" ref="edit.php?id=' . $values['id']  . '" ><i class="grey-text small ' .
			'material-icons">mode_edit</i></a>';
			}else{
				$editmode = '';
			}	
		}
		
		$decimal = 2;
		if($currencyname == 'VND'){
			$decimal = 0;
		}
		if( $cannotedit == 1 || ( $currentuser->role == 'Operator' && !in_array($tab->id,$currentuser->account) && in_array($tab->id,$currentuser->accountreadonly))) {
			$table .= '<td style="text-align:center"></td>';
		}else{
			$table .= '<td  style="padding-left:6px!important;"></td>';
        }
		$moreinfo = $classdash1 = '';
		if(strpos($values['documentnumber'],'-') === false){
			if(in_array($values['documentnumber'].'-2',$groupdocumentnumber) && !in_array($values['documentnumber'].'-1',$groupdocumentnumber)){
				$strdocumentnumber = $values['documentnumber'].'-1';
				$classdash1 = 'classdash1';
				$moreinfo = '-1';
			}
		}
		if( $erjkik[$values['charge']] == '' && ( $values['classification'] == '管理费用' || $values['classification'] == '财务费用' ) ){
			$notinlist = 'color:red;';	
		}else{
			$notinlist = '';
		}
		
		$tablocation = $tab->location;
		
			if($tab->special == 1){
				if(strpos($values['documentnumber'],'VN') !== false ){
					$tablocation = '越南';
				}
				if(strpos($values['documentnumber'],'CN') !== false ){
					$tablocation = '中国';
				}
				if(strpos($values['documentnumber'],'TH') !== false ){
					$tablocation = '泰国';
				}
			}
			
			
		if($cannotedit == 1){ $editmode = ''; } 
		$table .= '<td  style="padding-left:6px!important;"><span style="display:none;" >'.$values['id'].'</span><a href="#"  title="'.date('Y.m.d H:i:s',$values['id']).' '.$values['createbyname'].'" >' . date('y.m.d',$values['id']) .
	    '</a>'.$editmode.
		'</td><td style="padding-left:6px!important;" ><a href="#"  title="'.date('Y.m.d H:i:s',$values['timemodify']).'" >' . $values['modifybyname']  .'</a>'.
		'</td><td style="padding-left:6px!important;">'.(($i18n[$values['payment']] != '')?$i18n[$values['payment']]:$values['payment']).
	    '</td><td style="padding-left:6px!important;">' .(($i18n[$values['classification']] != '')?$i18n[$values['classification']]:$values['classification']).
		'</td><td style="padding-left:6px!important;'.$notinlist.'">' .$erjkik[$values['charge']].(($i18n[$values['charge']] != '')?$i18n[$values['charge']]:$values['charge']).
		'</td><td class="havepecial" style="padding-left:6px!important;display:none;">' . $values['department'].
		'</td><td class="havepecial2" style="padding-left:6px!important;display:none;">' . $values['billno'].
		'</td><td class="havepecial2" style="padding-left:6px!important;display:none;">' . $values['billto'].
		'</td><td class="havepecial2" style="padding-left:6px!important;display:none;">' . $values['vat'].
		'</td><td class="havepecial2" style="padding-left:6px!important;display:none;">' . $values['wht'].
		'</td><td style="padding-left:6px!important;"><div class="nofulltext" >' . $values['summary'].
		'</div><i class="fas fa-sort-down" style="color: #000;    font-size: 17px;"></i></td>'.
		'<td style="padding-left:6px!important;">' . (($tab->special3 == 1)?(($values['amountincomeusd'] > 0)?number_format((float)$values['amountincomeusd'],2):""):number_format((float)$values['amountincome'],$decimal)).
		'</td><td style="padding-left:6px!important;">' .(($tab->special3 == 1)?(($values['amountpayoutusd'] > 0)?number_format((float)$values['amountpayoutusd'],2):""):number_format((float)$values['amountpayout'],$decimal)).
		'</td><td class="havepecial3" style="padding-left:6px!important;display:none;">' . (($values['exchangeusdtovnd'] != '')?number_format((float)$values['exchangeusdtovnd'],0):'').
		'</td><td class="havepecial3" style="padding-left:6px!important;display:none;">' . (($values['exchangeusdtovnd'] != '')?number_format(($values['amountpayoutusd']*$values['exchangeusdtovnd']),$decimal):'') .
		'</td><td class="havepecial3" style="padding-left:6px!important;display:none;">' . number_format((float)$values['amountpayout'],$decimal) .
		'</td><td style="padding-left:6px!important;">' .(( $vendor  == '' ||  $_POST['acctiveaccount'] != $values['tabs']  )?number_format((float)$balance[$rt],$decimal):"") .
		'</td><td style="padding-left:6px!important;"><div class="nofulltext" >';
		foreach ($values['payer'] as $rpayer){
			if(isset($receiver_payer_id[$rpayer])){
				$table .= '<a data-target="modal8" class="modal-trigger payerdetail" ref="'.$rpayer.'" title="编号 Numbering：'.$receiver_payer_id[$rpayer]->name.'&#010;收付款人简称 Abbreviation：'.$receiver_payer_id[$rpayer]->abbreviation.'&#010;详细信息 Details:：'.$receiver_payer_id[$rpayer]->description.' " >'.$receiver_payer_id[$rpayer]->name.'</a>';
			}elseif(isset($receiver_payer_name[$rpayer])){
				$table .= '<a data-target="modal8" class="modal-trigger payerdetail" ref="'.$rpayer.'" title="编号 Numbering：'.$receiver_payer_name[$rpayer]->name.'&#010;收付款人简称 Abbreviation：'.$receiver_payer_name[$rpayer]->abbreviation.'&#010;详细信息 Details:：'.$receiver_payer_name[$rpayer]->description.' " >'.$receiver_payer_name[$rpayer]->name.'</a>';
			}else{
				$table .= $rpayer;
			}
			if(count((array)$values['payer']) > 1){
				$table .= ' | ';
			}
		}
		$table .= '</div><i class="fas fa-sort-down" style="color: #000;    font-size: 17px;"></i></td>'.
		'<td style="padding-left:6px!important;"><div class="nofulltext" >' . $values['requestnumber'].	
		'</div><i class="fas fa-sort-down" style="color: #000;    font-size: 17px;"></i></td>'.
		//'<td style="padding-left:6px!important;"><div class="nofulltext" >' . $values['jobnumber'].'</div><i class="fas fa-sort-down" style="color: #000;    font-size: 17px;"></i></td>'.
		'<td style="padding-left:6px!important;" class="'.$classdash1.' tddocumentnumber'.$values['classification'].$tablocation.' '.$values['documentnumber'].'" >' . $values['documentnumber'] .
		'</td>'.
		'<td style="padding-left:6px!important;">' .(($i18n[$values['writtenoff']] != '')?$i18n[$values['writtenoff']]:$values['writtenoff']).
		'<td style="padding-left:6px!important;">' . $file.
		'</td><td style="padding-left:6px!important;" class="qwsda" ref="'.$values['id'].'" ><div class="nofulltext" ><p>' .str_replace(PHP_EOL,'</p><p>',str_replace(array('  ','/n','/r','/t'),'',trim($values['remarks']))). '</p></div><i class="fas fa-sort-down" style="color: #000;    font-size: 17px;"></i></td>';
		
					if($values['status'] == ''){
						$table .= '<td style="padding-left:6px!important;" >等待财务完成</td>';
					}elseif($values['status'] == 'pending'){
						$table .= '<td style="padding-left:6px!important;" ><a href="#" title="'.$values['financeclicktoapproval'].' - '.date('Y.m.d H:i',$values['financeclicktoapprovaltime']).'" >待审核...</a></td>';
					}elseif($values['status'] == 'approval'){
						$table .= '<td style="padding-left:6px!important;" ><a href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">已审核 by '.$values['controlerapproval'].'</a></td>';
					}elseif($values['status'] == 'notapproval'){
						$table .= '<td style="padding-left:6px!important;" ><a style="color:red;" href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">未通过 by '.$values['controlerapproval'].'</a></td>';
					}
			
        $table .= '</tr>';
		
    }
	
	
    echo $table . '</tbody></table>';

?>

		

<div id="modal5" class="modal">

  <iframe class="frameedit" src="" width="100%" style="height:auto;    min-height: 321px;" ></iframe>
</div>


<?php  
		$now = strtotime(date('Y-m-d 00:00:00')); // or your date as well
		//echo $datestart.'-'.$dateto;
		$your_date = strtotime(str_replace('.','-',$datestart).' 00:00:00'); 
		$datediff = round(($now - $your_date)/84600);
		if($datediff <= 0){
			$numdatstart = $datediff;
		}else{
			$numdatstart = $datediff-1;
		}
		
		$your_date = strtotime(str_replace('.','-',$dateto).' 00:00:00');
		$datediff = round(($now - $your_date)/84600); 
		if($datediff <= 0){
			$numdatto = $datediff;
		}else{
			$numdatto = $datediff-1;
		}
		if($_SESSION['HTTP_ACCEPT_LANGUAGE'] == 'cn' || $_SESSION['HTTP_ACCEPT_LANGUAGE'] == '' ){
			$monthchinatext = array('一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月');
		}elseif($_SESSION['HTTP_ACCEPT_LANGUAGE'] == 'tha'){
			$monthchinatext = array('มกราคม ',' กุมภาพันธ์ ',' มีนาคม ',' เมษายน ',' พฤษภาคม ',' มิถุนายน ',' กรกฎาคม ',' สิงหาคม ',' กันยายน ',' ตุลาคม ',' ตุลาคม ',' พฤศจิกายน ',' ธันวาคม');
		}else{
			$monthchinatext = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
		}
		
		
?>
	
<script type="text/javascript">

$(window).load(function() {
$(".loader").delay(1000).fadeOut("slow");
$("#overlayer").delay(1000).fadeOut("slow");

$("#idpayment").change(function(){
	if($(this).val() == '收'){
		$('.divpayin').show();
		$('.divpayout').hide();
		$('#amountpayout').val('');
		$('#currencyisspeci3 option[value="1560829223"]').prop('disabled',true);
		$('#currencyisspeci3').val('1560829162');
		$('#currencyisspeci3').formSelect();
	}
	if($(this).val() == '付'){
		$('.divpayout').show();
		$('.divpayin').hide();
		$('#amountincome').val('');
		$('#currencyisspeci3 option').prop('disabled',false);
		$('#currencyisspeci3').formSelect();
	}
}); 
$("#classification option").each(function(){
			if($(this).attr('color') != ''){
				var adf = $(this).text();var color = $(this).attr('color');
				$(this).parents().eq(1).find('li').each(function(){
					if($(this).find('span').text() == adf){
						$(this).find('span').css('color',color);$(this).find('span').css('font-weight','bold');
					}
				});
			}
});

	var start = moment().subtract(<?php echo $numdatstart; ?>, 'days');
    var end = moment().subtract(<?php echo $numdatto; ?>, 'days');

    function cb(start, end , sub) {		
		jQuery('#datestart').val(start.format('YYYY.MM.DD')); 
		jQuery('#dateto').val(end.format('YYYY.MM.DD')); 
		if(sub != 1){
			jQuery("#formfilter").submit();
		}
    }
	
	function cb2(start, end , sub) {
		jQuery('#datestart2').val(start.format('YYYY.MM.DD')); 
		jQuery('#dateto2').val(end.format('YYYY.MM.DD')); 
		jQuery('.bsdbk .select-dropdown').trigger('click');
		jQuery('.bsdbk ul li:first-child label span').text(start.format('YYYY.MM.DD')+' to '+end.format('YYYY.MM.DD')+' ?');
    }	

    $('.reportrange').daterangepicker({
        startDate: start,
        endDate: end,
		linkedCalendars: false,
        ranges: {
           '<?php echo $i18n['今天']; ?>': [moment(), moment()],
           '<?php echo $i18n['昨天']; ?>': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
           '<?php echo $i18n['七天内']; ?>': [moment().subtract(6, 'days'), moment()],
           '<?php echo $i18n['三十天内']; ?>': [moment().subtract(29, 'days'), moment()],
           '<?php echo $monthchinatext[(date('n')-1)].' '.date('Y'); ?>': [moment().startOf('month'), moment().endOf('month')],
           '<?php echo $monthchinatext[(date('n', strtotime('first day of last month')) - 1 )].' '.date('Y',strtotime('first day of last month')); ?>': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -2 month')) - 1 )].' '.date('Y',strtotime('first day of -2 month')); ?>': [moment().subtract(2, 'month').startOf('month'), moment().subtract(2, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -3 month')) - 1 )].' '.date('Y',strtotime('first day of -3 month')); ?>': [moment().subtract(3, 'month').startOf('month'), moment().subtract(3, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -4 month')) - 1 )].' '.date('Y',strtotime('first day of -4 month')); ?>': [moment().subtract(4, 'month').startOf('month'), moment().subtract(4, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -5 month')) - 1 )].' '.date('Y',strtotime('first day of -5 month')); ?>': [moment().subtract(5, 'month').startOf('month'), moment().subtract(5, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -6 month')) - 1 )].' '.date('Y',strtotime('first day of -6 month')); ?>': [moment().subtract(6, 'month').startOf('month'), moment().subtract(6, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -7 month')) - 1 )].' '.date('Y',strtotime('first day of -7 month')); ?>': [moment().subtract(7, 'month').startOf('month'), moment().subtract(7, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -8 month')) - 1 )].' '.date('Y',strtotime('first day of -8 month')); ?>': [moment().subtract(8, 'month').startOf('month'), moment().subtract(8, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -9 month')) - 1 )].' '.date('Y',strtotime('first day of -9 month')); ?>': [moment().subtract(9, 'month').startOf('month'), moment().subtract(9, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -10 month')) - 1 )].' '.date('Y',strtotime('first day of -10 month')); ?>': [moment().subtract(10, 'month').startOf('month'), moment().subtract(10, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -11 month')) - 1 )].' '.date('Y',strtotime('first day of -11 month')); ?>': [moment().subtract(11, 'month').startOf('month'), moment().subtract(11, 'month').endOf('month')]
        
        }
    }, cb);
	
	$('.reportrange2').daterangepicker({
        startDate: start,
        endDate: end,
		linkedCalendars: false,
		customClass: 'some-css-class',
		locale: { direction: 'some-css-class' } ,
        ranges: {
           '<?php echo $i18n['今天']; ?>': [moment(), moment()],
           '<?php echo $i18n['昨天']; ?>': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
           '<?php echo $i18n['七天内']; ?>': [moment().subtract(6, 'days'), moment()],
           '<?php echo $i18n['三十天内']; ?>': [moment().subtract(29, 'days'), moment()],
           '<?php echo $monthchinatext[(date('n')-1)].' '.date('Y'); ?>': [moment().startOf('month'), moment().endOf('month')],
           '<?php echo $monthchinatext[(date('n', strtotime('first day of last month')) - 1 )].' '.date('Y'); ?>': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -2 month')) - 1 )].' '.date('Y'); ?>': [moment().subtract(2, 'month').startOf('month'), moment().subtract(2, 'month').endOf('month')],
			'<?php echo $monthchinatext[(date('n', strtotime('first day of -3 month')) - 1 )].' '.date('Y',strtotime('first day of -3 month')); ?>': [moment().subtract(3, 'month').startOf('month'), moment().subtract(3, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -4 month')) - 1 )].' '.date('Y',strtotime('first day of -4 month')); ?>': [moment().subtract(4, 'month').startOf('month'), moment().subtract(4, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -5 month')) - 1 )].' '.date('Y',strtotime('first day of -5 month')); ?>': [moment().subtract(5, 'month').startOf('month'), moment().subtract(5, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -6 month')) - 1 )].' '.date('Y',strtotime('first day of -6 month')); ?>': [moment().subtract(6, 'month').startOf('month'), moment().subtract(6, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -7 month')) - 1 )].' '.date('Y',strtotime('first day of -7 month')); ?>': [moment().subtract(7, 'month').startOf('month'), moment().subtract(7, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -8 month')) - 1 )].' '.date('Y',strtotime('first day of -8 month')); ?>': [moment().subtract(8, 'month').startOf('month'), moment().subtract(8, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -9 month')) - 1 )].' '.date('Y',strtotime('first day of -9 month')); ?>': [moment().subtract(9, 'month').startOf('month'), moment().subtract(9, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -10 month')) - 1 )].' '.date('Y',strtotime('first day of -10 month')); ?>': [moment().subtract(10, 'month').startOf('month'), moment().subtract(10, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -11 month')) - 1 )].' '.date('Y',strtotime('first day of -11 month')); ?>': [moment().subtract(11, 'month').startOf('month'), moment().subtract(11, 'month').endOf('month')]
        
		}
    }, cb2);
    cb(start, end , 1);
});
</script>
<?php if($_GET['showsearch'] == 1){ ?>
<script>
    var projects = [
		<?php echo $datasreach; ?>
    ];
  
    jQuery( "#project" ).autocomplete({
      minLength: 0,
      source: projects,
      focus: function( event, ui ) {
        jQuery( "#project" ).val( ui.item.label );
        return false;
      },
      select: function( event, ui ) {
		 
        //$( "#project" ).val( ui.item.label );
        //$( "#project-id" ).val( ui.item.value );
        //$( "#project-description" ).html( ui.item.desc );
        //$( "#project-icon" ).attr( "src", "images/" + ui.item.icon );
 
        return false;
      }
    })
    .data( "ui-autocomplete" )._renderItem = function( ul, item ) {
      return jQuery( "<li class='searchresult' tab='" + item.tab + "' row='" + item.id + "'  >" )
        .append( "<div>" + item.label + "<br>" + item.desc + "</div>" )
        .appendTo( ul );
    };
//  });
</script>
<?php } ?>
<script type="text/javascript">
 var d = new Date(); var days = (Date.parse(jQuery(this).text()) - Date.parse(d)) / 86400000;  if(days < 30){ jQuery(this).css("color","#f48024");}  if(days < 0){ jQuery(this).css("color","red"); }
$(function() {  	
	jQuery('.editmode').click(function(){
		jQuery('.frameedit').attr( 'src',jQuery(this).attr('ref'));
	});	
	jQuery('.payerdetail').click(function(){
		jQuery('.receiverpayer').attr( 'src','/expense/receiver_payer.php?payer='+jQuery(this).attr('ref'));
	});	
});

function closeiframe(){
	$('.modal-overlay').trigger('click');
}
function closeiframereload(){
	$('.modal-overlay').trigger('click');
	location.reload();
}
function changewidthframe(){
	$('.frameedit').css('height','510px');
}

$(document).ready(function () {
	 $("#payer").change(function(){
		  if($(this).val() == 'addmore'){
			  $(this).next('.select2').hide();
			  $('#payer_more').show();
		  }
	 });
	<?php if($currentuser->role == 'Finance'  ){ ?>
		$('.qwsda').dblclick(function() {			
			$(this).append('<form method="POST" enctype="multipart/form-data"  ><input type="hidden" name="editremark" value="1"  /><input type="hidden" name="idorder" value="'+$(this).attr('ref')+'"  /><textarea style="width:100%; height:50px;" name="controlerremark" >'+$(this).find('.nofulltext').text()+'</textarea>  <button class="colortoptran btn waves-effect waves-light" style="float: right;    padding: 0px 4px;" type="submit" name="action"><?php echo $i18n['Save New Issue']; ?></button></form>');
			$(this).find('.nofulltext , i').remove();
		});
	<?php } ?>
	$(".asbdkbas").text('<?php if($totalrevision <= 0){ $totalrevision = 0; } echo $totalrevision; ?>');
	$(".asbdkbas").show();
	$(this).bind("contextmenu", function(e) {
		e.preventDefault();
	});
	$( "body" ).delegate( '.searchresult' , "click", function() {
		var row = $(this).attr('row');
		$('.tab'+$(this).attr('tab')).trigger('click');
		$($(this).attr('row')).css('background','#c5d9ff');
		$([document.documentElement, document.body]).animate({
			scrollTop: $($(this).attr('row')).offset().top - 100
		}, 2000);
		setTimeout(function(){
			$(row).removeAttr('style');
		}, 7000);
		
	});
	<?php if($_POST['rowclick'] != '' || $_POST['tabclick'] != ''){ ?>
		setTimeout(function(){
			$('.tab<?php echo $_POST['tabclick']; ?>').trigger('click');
			$('.<?php echo $_POST['rowclick']; ?>').css('background','#c5d9ff');
			$([document.documentElement, document.body]).animate({
				scrollTop: $('.<?php echo $_POST['rowclick']; ?>').offset().top - 100
			}, 2000);
			setTimeout(function(){
				$('.<?php echo $_POST['rowclick']; ?>').removeAttr('style');
			}, 7000);
		}, 1000);
	<?php } ?>
	
	$('.collapsible').collapsible();
	$('.isleft').click(function(){
		if($('.isreadder'+$(this).attr('nextread')).prev().hasClass('modal-trigger')){
			$('.isreadder'+$(this).attr('nextread')).prev().trigger('click');
		}
	});
	$('.isright').click(function(){
		if($('.isreadder'+$(this).attr('nextread')).next().hasClass('modal-trigger')){
			$('.isreadder'+$(this).attr('nextread')).next().trigger('click');
		}
	});
	$('.ranges li:last-child').text('搜寻');
	
    $('.timepicker').timepicker({   twelveHour: false });
	
  
	$("#bifdnino").submit(function(e){	
		
		if($( ".sandjnas option:selected" ).hasClass('isspeci3') && $('#idpayment').val() == '付'){
			var amountpayout = parseFloat($("#amountpayout").val().replace(/\,/g, ''));
			if($("#currencyisspeci3").val() == '1560829162'){
				// usd
				if( amountpayout > parseFloat($('#tab-'+$(".sandjnas").val()).find('.totalamountpayoutusd').text())){
						$("#amountpayout").val('');
						alert('USD payments cannot exceed balance/美元付款不得超过余额');
						e.preventDefault();
						return;
				}
			}
			if($("#currencyisspeci3").val() == '1560829223'){
				// vnd
				if( amountpayout > parseFloat($('#tab-'+$(".sandjnas").val()).find('.totalamountpayoutvnd').text())){
						$("#amountpayout").val('');
						alert('VND payments cannot exceed balance/美元付款不得超过余额');
						e.preventDefault();
						return;
				}
			}
			
		}
		
	
		var issubmit = 1 ;
		$('#overlayer,.loader').show();
		$('.ismoreadd').each(function(index){
			if(jQuery(this).hasClass('act')){ 
				var self = this;
				//setTimeout(function () {
				$(self).find("iframe").contents().find("#bifdnino").submit();
				$(self).hide();$(self).removeClass('act');
				//}, index*1500);
				issubmit = 0;
			}
		});
		if(issubmit == 0){
			e.preventDefault();
			setTimeout(function () { $("#bifdnino").submit(); }, 5000);
		}
	});
	
	$("#dsjdbksa").submit(function(e){
		if( $("#tabexport").val() == null ) {
			$('.bsdbk .select-dropdown').trigger('click');
			e.preventDefault();
		}
	});
	
	$("#tabexport").change(function(){
		var string = $(this).val();
		if(string.indexOf("clicktosearch") !== -1 ){
			jQuery(".reportrange2").trigger('click');
			$(this).prop('selected',false);
			$(this).val('[]');
			$("#tabexport").formSelect();
			
		}
		if(string.indexOf("-1") !== -1 ){
			$("#dsjdbksa").submit();
			setTimeout(function(){
				$("#tabexport").val('[]');
				$("#tabexport").formSelect();
			}, 2000);
		}
	});
	
	$(".inorout").change(function(){
		var string = $(this).val()+'';
		
		if(string.indexOf("in") !== -1 ){
			$(this).parents('table').find('tr.rowin').show();
		}else{
			$(this).parents('table').find('tr.rowin').hide();
		}
		
		if(string.indexOf("out") !== -1 ){
			$(this).parents('table').find('tr.rowout').show();
		}else{
			$(this).parents('table').find('tr.rowout').hide();
		}
		
	});
	
	$(".shkabkasb").change(function(){
		if($(this).attr('id') == 'category'){
			jQuery('#categoryf').val($(this).val()); 
		}else if($(this).attr('id') == 'subcategory'){
			jQuery('#subcategoryf').val($(this).val()); 
		}else{
			jQuery('#vendor').val($(this).val()); 
		}
		
		var string = $(this).val();
		if(string.indexOf("clicktosearch") !== -1 ){
			jQuery("#formfilter").submit();
		}
	});

	$(".nofulltext").each(function(){
		if($(this).text().length < 9 && $(window).width() >= 1400){
			$(this).next().hide();
		}		
		if($(this).text().length < 9 && $(window).width() < 1400){
			$(this).next().hide();
		}
	});
	$('.fa-sort-down').click(function(){
		if($(this).hasClass('active')){
			$(this).parents().eq(1).find('.nofulltext').removeAttr('style');
			$(this).parents().eq(1).find('.fa-sort-down').removeClass('active');
		}else{
			$(this).parents().eq(1).find('.nofulltext').css('height','auto');
			$(this).parents().eq(1).find('.fa-sort-down').addClass('active');
		}
	});
	
	$(".sandjnas").change(function(){
		if($( ".sandjnas option:selected" ).hasClass('isspeci')){
			$(".isdepartmentform").show();
		}else{
			$(".isdepartmentform").hide();
		}
		
		if($( ".sandjnas option:selected" ).hasClass('isspeci2')){
			$(".inputisspeci2").show();
		}else{
			$(".inputisspeci2").hide();
		}
		
		if($( ".sandjnas option:selected" ).hasClass('isspeci3')){
			$(".tygiausdtovnd").val('<?php echo $tygiausdtovnd; ?>');
			$(".inputisspeci3").show();
		}else{
			$(".inputisspeci3").hide();
			$(".tygiausdtovnd").val('');
		}
		
	});
	$(".sandjnas").change();

	
	$('.tab-link').on('click',function(){
 
		 $("#documentnumber").val('');$("#classification").val('');
         $(".sandjnas").val($(this).attr("data-id")).change();
		 $("#acctiveaccount").val($(this).attr("data-id"));
		 $(".sandjnas").formSelect();
		 $("#classification").formSelect();
		 $(".formchiem").empty();
		 var date = new Date();
		 var minutes = 1440;
		 date.setTime(date.getTime() + (minutes * 60 * 1000));
		 $.cookie("tabremenber", $(this).attr("data-id") , { expires: date });
	});
	$('.treopit').on('click',function(){
		$(".snmnln").text($(this).find('.tabdescription').text());
	});
	$(".exchangemoney3").click(function(){
		$(".exchangemoney3").removeClass('dnainpo');
		$("#monneyexchangerate").val($(this).attr('curexchange'));
		$("#amountexchange").val($(this).attr('maxmonney'));
		$("#idaccount").val($(this).attr('ref'));
		$(this).addClass('dnainpo');
	});
	$("#monneyexchangerate").blur(function(){
		if( parseFloat($(this).val()) <= 0  ){
			$(this).val('');
			alert("Exchange rate/汇率 > 0");
		}
	});
	$("#amountexchange").blur(function(){
		if( parseFloat($(this).val()) <= 0 || parseFloat($(this).val()) > parseFloat($('.dnainpo').attr('maxmonney'))){
			$(this).val('');
			alert("Amount/量 <= "+$('.dnainpo').attr('maxmonney') );
		}
	});
	
	
	$(".tabnameSave").click(function(){		
		$(".sdastr").trigger("click");
		$("#addNewTab #currency").val($(this).prev().attr('currency'));
		$('#addNewTab #currency').formSelect();
		$("#addNewTab #id_tabname").val($(this).prev().attr('data-id'));
		$("#addNewTab #tab").val($(this).prev().attr('name'));
		$("#addNewTab #Balance").val($(this).prev().attr('balance'));
		$("#addNewTab #tabinfo").val($(this).prev().attr('info'));
		$("#addNewTab #tabdescription").val($(this).prev().find('.tabdescription').text());
		$("#addNewTab #aclocation").val($(this).prev().attr('location'));		
		$('#aclocation').formSelect();
		if($(this).prev().attr('special') == 1){
			$("#addNewTab #special").prop('checked',true);
		}else{
			$("#addNewTab #special").prop('checked',false);
		}
		
		if($(this).prev().attr('special2') == 1){
			$("#addNewTab #special2").prop('checked',true);
		}else{
			$("#addNewTab #special2").prop('checked',false);
		}
		
		if($(this).prev().attr('special3') == 1){
			$("#addNewTab #special3").prop('checked',true);
		}else{
			$("#addNewTab #special3").prop('checked',false);
		}
	});
	function pad (str, max) {
	  str = str.toString();
	  return str.length < max ? pad("0" + str, max) : str;
	}
	$(".makesimilar").change(function(){
		var str = $(this).val();
		/*
		if( str.indexOf('-') !== -1 ){
			var res = str.split("-");
			var sotang = res[1].match(/\d+/); 
			var main = res[1].replace(sotang, '');
			if(res[1].length > 3){
				$("#documentnumber").val(res[0]+'-'+main+(pad(parseInt(sotang)+1, 3)));
			}else{
				for ( var i = 3; i < 999; i++){
					if( arrlist2.indexOf(res[0]+'-'+i) == -1 ){
						$("#documentnumber").val(res[0]+'-'+i);
						break;
					}
				}
			}
		}else{
			$("#documentnumber").val($(this).val()+'-2');
		}*/
		//arrlist2.indexOf(res[0]+'-'+i) == -1
		var res = str.split("-");
		for ( var i = 2; i <= 999; i++){			
			if(!$('.'+res[0]+'-'+i<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> ).length ){
					$("#documentnumber").val(res[0]+'-'+i);
					$( $('.formchiem'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>)).append( '<td class="'+res[0]+'-'+i+'" >'+res[0]+'-'+i+'</td> ' );
					break;
			}
		}
		$("#documentnumber").attr('readonly','');
	});
	
	function pad (str, max) {
	  str = str.toString();
	  return str.length < max ? pad("0" + str, max) : str;
	}


	$("#classification").change(function(){
		$('#charge').val('');$("#documentnumber").val('');$('.iopd').html("");
		jQuery('.makesimilar').empty();
		jQuery('.makesimilar').select2({width: "100%"});
		jQuery('#iscontinue').prop('checked',false);
		$("#documentnumber").removeAttr('readonly');
		if($(this).val() != ''){
			$('#charge').prop('disabled',false);
			$('#charge option').prop('disabled',true);
			if( $("#classification option:selected").attr('freetext') == 'freetext' ){
				$('.charge').hide();
				$('#chargefreetext,.chargefreetext').show();
				$('#chargefreetext').val('');
				$('#chargefreetext').prop('disabled',false);
			}else{
				$('.charge').show();
				$('#chargefreetext,.chargefreetext').hide();
				$('#chargefreetext').val('');
				$('#chargefreetext').prop('disabled',true);
				if( $('.'+$(this).val()).length ){
					$('.'+$(this).val()).prop('disabled',false);
				}else{
					$('.novalue').prop('disabled',false);
					$('.novalue').attr('value',$(this).val());
					$('.novalue').text($(this).val());
				}
				
			}
		}else{
			$('#charge').prop('disabled',true);
		}
		$('#charge').formSelect();
		
		var location = $( ".sandjnas option:selected" ).attr('location');
		if( $( ".sandjnas option:selected" ).hasClass('isspeci') && $("#department").val() != '' ){
			location = $("#department").val();
		}
		
		var tabvalue = $( ".sandjnas" ).val();
		var date = "<?php echo date("ym"); ?>"+'';		
		
		if($(this).val() == "管理费用"){			
			if(location == '越南'){
				var num = $( ".nextvalue1越南" ).val();
				var miss = $( ".nextvalue1越南" ).attr('miss');
				var miss2 = $( ".nextvalue1越南" ).attr('miss2');
				if(num != miss && !$('.'+'VNG'+date+pad(miss, 3)).length && miss != 000 ){
					$('.iopd').html("<a href='#' onclick=\"$('#documentnumber').val('VNG"+date+pad(miss, 3)+"');\" >"+'VNG'+date+pad(miss, 3)+" is Missing. Click to use ?</a>");
					if(num != miss2 && !$('.'+'VNG'+date+pad(miss2, 3)).length && miss2 != 000 ){
						$('.iopd').append("<br><a href='#' onclick=\"$('#documentnumber').val('VNG"+date+pad(miss2, 3)+"');\" >"+'VNG'+date+pad(miss2, 3)+" is Missing. Click to use ?</a>");
					}
				}else{
					$('.iopd').html("");
				}
				num = parseInt(num);				
				for ( ; num <= 999; num++){
					if( !$('.'+'VNG'+date+pad(num, 3)<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> ).length ){
						break;
					}
				}				
				$("#documentnumber").val('VNG'+date+pad(num, 3));				
				$( $('.formchiem'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>)).append( '<td class="tddocumentnumber管理费用越南 '+'VNG'+date+pad(num, 3)+'" >'+'VNG'+date+pad(num, 3)+'</td> ' );
				
			}
			if(location == '中国'){
				var num = $( ".nextvalue1中国" ).val();
				var miss = $( ".nextvalue1中国" ).attr('miss');
				var miss2 = $( ".nextvalue1中国" ).attr('miss2');
				if(num != miss && !$('.'+'CNG'+date+pad(miss, 3)).length && miss != 000){
					$('.iopd').html("<a href='#' onclick=\"$('#documentnumber').val('CNG"+date+pad(miss, 3)+"');\" >"+'CNG'+date+pad(miss, 3)+" is Missing. Click to use ?</a>");
					if(num != miss2 && !$('.'+'CNG'+date+pad(miss2, 3)).length && miss2 != 000 ){
						$('.iopd').append("<br><a href='#' onclick=\"$('#documentnumber').val('CNG"+date+pad(miss2, 3)+"');\" >"+'CNG'+date+pad(miss2, 3)+" is Missing. Click to use ?</a>");
					}
				}else{
					$('.iopd').html("");
				}
				num = parseInt(num);		
				for ( ; num <= 999; num++){
					if( !$('.'+'CNG'+date+pad(num, 3)<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>).length ){
						break;
					}
				}				
				$("#documentnumber").val('CNG'+date+pad(num, 3));
				
				$( $('.formchiem'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>)).append( '<td class="tddocumentnumber管理费用中国 '+'CNG'+date+pad(num, 3)+'" >'+'CNG'+date+pad(num, 3)+'</td> ' );
			}
			if(location == '泰国'){
				var num = $( ".nextvalue1泰国" ).val();
				var miss = $( ".nextvalue1泰国" ).attr('miss');
				var miss2 = $( ".nextvalue1泰国" ).attr('miss2');
				if(num != miss && !$('.'+'THG'+date+pad(miss, 3)).length && miss != 000){
					$('.iopd').html("<a href='#' onclick=\"$('#documentnumber').val('THG"+date+pad(miss, 3)+"');\" >"+'THG'+date+pad(miss, 3)+" is Missing. Click to use ?</a>");
					if(num != miss2 && !$('.'+'THG'+date+pad(miss2, 3)).length && miss2 != 000){
						$('.iopd').append("<br><a href='#' onclick=\"$('#documentnumber').val('THG"+date+pad(miss2, 3)+"');\" >"+'THG'+date+pad(miss2, 3)+" is Missing. Click to use ?</a>");
					}
				}else{
					$('.iopd').html("");
				}
				num = parseInt(num);
				for ( ; num <= 999; num++){
					if( !$('.'+'THG'+date+pad(num, 3)<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>).length ){
						break;
					}
				}				
				$("#documentnumber").val('THG'+date+pad(num, 3));				
				$( $('.formchiem'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>) ).append( '<td class="tddocumentnumber管理费用泰国 '+'THG'+date+pad(num, 3)+'" >'+'THG'+date+pad(num, 3)+'</td> ' );
			}
			$("#documentnumber").attr('readonly','');
		}
		if($(this).val() == "应收账款"){ 
			if(location == '越南'){
				var num = $( ".nextvalue2越南" ).val();
				var miss = $( ".nextvalue2越南" ).attr('miss');
				var miss2 = $( ".nextvalue2越南" ).attr('miss2');
				if(num != miss  && !$('.'+'VNS'+date+pad(miss, 3)).length && miss != 000){
					$('.iopd').html("<a href='#' onclick=\"$('#documentnumber').val('VNS"+date+pad(miss, 3)+"');\" >"+'VNS'+date+pad(miss, 3)+" is Missing. Click to use ?</a>");
					if(num != miss2  && !$('.'+'VNS'+date+pad(miss2, 3)).length && miss2 != 000){
						$('.iopd').append("<br><a href='#' onclick=\"$('#documentnumber').val('VNS"+date+pad(miss2, 3)+"');\" >"+'VNS'+date+pad(miss2, 3)+" is Missing. Click to use ?</a>");
					}
				}else{
					$('.iopd').html("");
				}
				num = parseInt(num);				
				for ( ; num <= 999; num++){
					if( !$('.'+'VNS'+date+pad(num, 3)<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> ).length ){
						break;
					}
				}				
				$("#documentnumber").val('VNS'+date+pad(num, 3));
				$( $('.formchiem'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>)).append( '<td class="tddocumentnumber应收账款越南 '+'VNS'+date+pad(num, 3)+'" >'+'VNS'+date+pad(num, 3)+'</td> ' );
				
			}
			if(location == '中国'){
				var num = $( ".nextvalue2中国" ).val();
				var miss = $( ".nextvalue2中国" ).attr('miss');
				var miss2 = $( ".nextvalue2中国" ).attr('miss2');
				if(num != miss  && !$('.'+'CNS'+date+pad(miss, 3)).length && miss != 000){
					$('.iopd').html("<a href='#' onclick=\"$('#documentnumber').val('CNS"+date+pad(miss, 3)+"');\" >"+'CNS'+date+pad(miss, 3)+" is Missing. Click to use ?</a>");
					if(num != miss2  && !$('.'+'CNS'+date+pad(miss2, 3)).length && miss2 != 000){
						$('.iopd').append("<br><a href='#' onclick=\"$('#documentnumber').val('CNS"+date+pad(miss2, 3)+"');\" >"+'CNS'+date+pad(miss2, 3)+" is Missing. Click to use ?</a>");
					}
				}else{
					$('.iopd').html("");
				}
				num = parseInt(num);				
				for ( ; num <= 999; num++){
					if( !$('.'+'CNS'+date+pad(num, 3)<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> ).length ){
						break;
					}
				}		
				$("#documentnumber").val('CNS'+date+pad(num, 3));
				$( $('.formchiem'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>)).append( '<td class="tddocumentnumber应收账款中国 '+'CNS'+date+pad(num, 3)+'" >'+'CNS'+date+pad(num, 3)+'</td> ' );
				
			}
			if(location == '泰国'){
				var num = $( ".nextvalue2泰国" ).val();
				var miss = $( ".nextvalue2泰国" ).attr('miss');
				var miss2 = $( ".nextvalue2泰国" ).attr('miss2');
				if(num != miss && !$('.'+'THS'+date+pad(miss, 3)).length && miss != 000){
					$('.iopd').html("<a href='#' onclick=\"$('#documentnumber').val('THS"+date+pad(miss, 3)+"');\" >"+'THS'+date+pad(miss, 3)+" is Missing. Click to use ?</a>");
					if(num != miss2 && !$('.'+'THS'+date+pad(miss2, 3)).length && miss2 != 000){
						$('.iopd').append("<br><a href='#' onclick=\"$('#documentnumber').val('THS"+date+pad(miss2, 3)+"');\" >"+'THS'+date+pad(miss2, 3)+" is Missing. Click to use ?</a>");
					}
				}else{
					$('.iopd').html("");
				}
				num = parseInt(num);				
				for ( ; num <= 999; num++){
					if( !$('.'+'THS'+date+pad(num, 3)<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> ).length ){
						break;
					}
				}		
				$("#documentnumber").val('THS'+date+pad(num, 3));
				$( $('.formchiem'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>)).append( '<td class="tddocumentnumber应收账款泰国 '+'THS'+date+pad(num, 3)+'" >'+'THS'+date+pad(num, 3)+'</td> ' );
				
			}
			$("#documentnumber").attr('readonly','');
		}		
		if($(this).val() == "应付账款"){			
			
			if(location == '越南'){
				var num = $( ".nextvalue3越南" ).val();
				var miss = $( ".nextvalue3越南" ).attr('miss');
				var miss2 = $( ".nextvalue3越南" ).attr('miss2');
				if(num != miss && !$('.'+'VNF'+date+pad(miss, 3)).length && miss != 000){
					$('.iopd').html("<a href='#' onclick=\"$('#documentnumber').val('VNF"+date+pad(miss, 3)+"');\" >"+'VNF'+date+pad(miss, 3)+" is Missing. Click to use ?</a>");
					if(num != miss2 && !$('.'+'VNF'+date+pad(miss2, 3)).length && miss2 != 000){
						$('.iopd').append("<br><a href='#' onclick=\"$('#documentnumber').val('VNF"+date+pad(miss2, 3)+"');\" >"+'VNF'+date+pad(miss2, 3)+" is Missing. Click to use ?</a>");
					}
				}else{
					$('.iopd').html("");
				}
				num = parseInt(num);				
				for ( ; num <= 999; num++){
					if( !$('.'+'VNF'+date+pad(num, 3)<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> ).length ){
						break;
					}
				}		
				$("#documentnumber").val('VNF'+date+pad(num, 3));
				$( $('.formchiem'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>)).append( '<td class="tddocumentnumber应付账款越南 '+'VNF'+date+pad(num, 3)+'" >'+'VNF'+date+pad(num, 3)+'</td> ' );
				
			}
			if(location == '中国'){
				var num = $( ".nextvalue3中国" ).val();
				var miss = $( ".nextvalue3中国" ).attr('miss');
				var miss2 = $( ".nextvalue3中国" ).attr('miss2');
				if(num != miss && !$('.'+'CNF'+date+pad(miss, 3)).length && miss != 000){
					$('.iopd').html("<a href='#' onclick=\"$('#documentnumber').val('CNF"+date+pad(miss, 3)+"');\" >"+'CNF'+date+pad(miss, 3)+" is Missing. Click to use ?</a>");
					if(num != miss2 && !$('.'+'CNF'+date+pad(miss2, 3)).length && miss2 != 000){
						$('.iopd').append("<br><a href='#' onclick=\"$('#documentnumber').val('CNF"+date+pad(miss2, 3)+"');\" >"+'CNF'+date+pad(miss2, 3)+" is Missing. Click to use ?</a>");
					}
				}else{
					$('.iopd').html("");
				}
				num = parseInt(num);				
				for ( ; num <= 999; num++){
					if( !$('.'+'CNF'+date+pad(num, 3)<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> ).length ){
						break;
					}
				}		
				$("#documentnumber").val('CNF'+date+pad(num, 3));
				$( $('.formchiem'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>)).append( '<td class="tddocumentnumber应付账款中国 '+'CNF'+date+pad(num, 3)+'" >'+'CNF'+date+pad(num, 3)+'</td> ' );
				
			}
			if(location == '泰国'){
				var num = $( ".nextvalue3泰国" ).val();
				var miss = $( ".nextvalue3泰国" ).attr('miss');
				var miss2 = $( ".nextvalue3泰国" ).attr('miss2');
				if(num != miss && !$('.'+'THF'+date+pad(miss, 3)).length && miss != 000){
					$('.iopd').html("<a href='#' onclick=\"$('#documentnumber').val('THF"+date+pad(miss, 3)+"');\" >"+'THF'+date+pad(miss, 3)+" is Missing. Click to use ?</a>");
					if(num != miss2 && !$('.'+'THF'+date+pad(miss2, 3)).length && miss2 != 000){
						$('.iopd').html("<br><a href='#' onclick=\"$('#documentnumber').val('THF"+date+pad(miss2, 3)+"');\" >"+'THF'+date+pad(miss2, 3)+" is Missing. Click to use ?</a>");
					}
				}else{
					$('.iopd').html("");
				}
				num = parseInt(num);				
				for ( ; num <= 999; num++){
					if( !$('.'+'THF'+date+pad(num, 3)<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> ).length ){
						break;
					}
				}	
				$("#documentnumber").val('THF'+date+pad(num, 3));
				$( $('.formchiem'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>)).append( '<td class="tddocumentnumber应付账款泰国 '+'THF'+date+pad(num, 3)+'" >'+'THF'+date+pad(num, 3)+'</td> ' );
				
			}
			$("#documentnumber").attr('readonly','');
		}		
	});	
	<?php 	if ($currentuser->role == 'Finance' || $currentuser->gm == 1 ) { ?>
		jQuery(".bskue").each(function(){
			if( jQuery(this).attr('status') != 'pending' ){		
				jQuery(this).hide();
			}	
		});
	<?php }elseif ($currentuser->role == 'Manager'){ ?>
		jQuery(".bskue").each(function(){
			jQuery(this).hide();	
		});
	<?php }elseif ($currentuser->role == 'Operator'){ ?>
		jQuery(".bskue").each(function(){
			if( jQuery(this).attr('status') != '' ){		
				jQuery(this).hide();
			}		
		});
	<?php }	?>
	jQuery(".bskue").click(function(){
		if(jQuery(this).is(':checked')){	
			<?php 	if ($currentuser->role == 'Finance' || $currentuser->gm == 1 ) { ?>
				M.Toast.dismissAll();
				if( jQuery(this).attr('status') == 'pending' ){					
					M.toast({displayLength: 12000,html: "<button style='margin-right: 10px;' class='btn waves-effect waves-light mapproval'>Yes</button><button class='btn red waves-effect waves-light mdeny'>No</button>" });
				}else{
					jQuery(this).prop('checked',false);
					jQuery(this).prop('disabled',true);
				}
			<?php }elseif ($currentuser->role == 'Operator'){ ?>
				M.Toast.dismissAll();
				if( jQuery(this).attr('status') == '' ){					
					M.toast({displayLength: 12000,html: "<button style='width:100%;' class='btn waves-effect waves-light msendtoaproval '>发送</button>" });
				}else{
					jQuery(this).prop('checked',false);
					jQuery(this).prop('disabled',true);
				}
			<?php }	?>
		}
	});
	
	jQuery(".tablesorter tbody tr").dblclick(function() {
		$('.modal-overlay').trigger("click");
		if($(this).find('.editmode').length){
			$('.frameedit').css('height','auto');
			$(this).find('.editmode').trigger('click').click();
			$('#modal5').modal('open'); 
		}else{
			alert("This order can\'t edit.");
		}	
	});
	
	<?php if ($currentuser->gm == "1"  ){ ?>	
	$(".cllogcontent").click(function(){
		$(".logcontent").html($(this).find('span').html());
	});	
	<?php } ?>
	$('.sendtoaproval').click(function(){ 
			//if (confirm('Are you sure send to approval, can\'t modify after approval  ?')) {
				$("#fromsendtoaproval .iddoc").val($(this).attr('id'));
				$("#fromsendtoaproval").submit();
			//}
	});
	<?php if ($currentuser->role == "Operator"  ){ ?>	
	
		
		$( "body" ).delegate( ".msendtoaproval", "click", function() {
			var mapproval = '';
			$(".bskue").each(function(){
				if(jQuery(this).is(':checked')){
					if(mapproval == ''){
					mapproval += jQuery(this).val();
					}else{	
					mapproval += ','+jQuery(this).val();
					}
				}	
			});
			$("#fromsendtoaproval .iddoc").val(mapproval);
			$("#fromsendtoaproval").submit();
		});		
	<?php } ?>
	<?php if ($currentuser->role == "Manager"  || $currentuser->role == "Finance"  ){ ?>
		$('.approval').click(function(){
			if (confirm('Are you sure set to approval ?')) {
				$("#fromapproval .type").val('approval');
				$("#fromapproval .iddoc").val($(this).attr('id'));
				$("#fromapproval").submit();
			}
		});	
		$('.deny').click(function(){
			var newnote = window.prompt("Are you sure set to deny ?", "Reason Why");
			if ( newnote != '' ) {
				$("#fromapproval .note").val(newnote);
				$("#fromapproval .type").val('notapproval');
				$("#fromapproval .iddoc").val($(this).attr('id'));
				$("#fromapproval").submit();
			}
		});
		$( "body" ).delegate( ".mapproval", "click", function() {
				$("#fromapproval .type").val('approval');
				var mapproval = '';
				$(".bskue").each(function(){
					if(jQuery(this).is(':checked')){
						if(mapproval == ''){
						mapproval += jQuery(this).val();	
						}else{
						mapproval += ','+jQuery(this).val();
						}
					}	
				});
				$("#fromapproval .iddoc").val(mapproval);
				$("#fromapproval").submit();
		});
		$( "body" ).delegate( ".mdeny", "click", function() {	
				$("#fromapproval .type").val('notapproval');
				var mapproval = '';
				$(".bskue").each(function(){
					if(jQuery(this).is(':checked')){
						if(mapproval == ''){
						mapproval += jQuery(this).val();
						}else{	
						mapproval += ','+jQuery(this).val();
						}
					}	
				});
				$("#fromapproval .iddoc").val(mapproval);
				$("#fromapproval").submit();
		});	
	<?php } ?>	
	 <?php if ( $currentuser->gm == 1 || $currentuser->role == 'Finance' ) {  ?>   
		$('.tab-link').on('click',function(){
          //  $('.tabs button:not(.sdastr),.tabs a').hide();
		});
        $('.tab-link').on('dblclick',function(){
            var tab_id = $(this).attr('data-tab');
            $('.' + tab_id).css({"display":"block"});
           // $(this).css({"display":"none"});
        });
    <?php } ?>
	var arrlist2 = [];
	$("#iscontinue").change(function(){
		if($("#classification").val() == ''){
			alert('select <?php echo $i18n['费用归类']; ?> first ');
			jQuery('.makesimilar').empty();
			jQuery('.makesimilar').select2({width: "100%"});
			jQuery('#iscontinue').prop('checked',false);
			return;
		}
		if(jQuery(this).is(':checked')){
			var location = $( ".sandjnas option:selected" ).attr('location');
			if( $( ".sandjnas option:selected" ).hasClass('isspeci') && $("#department").val() != '' ){
				location = $("#department").val();
			}
			var classification = $("#classification").val();
			if( classification == "管理费用"){			
				if(location == '越南'){
					var arr =  $('.tddocumentnumber管理费用越南'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> );
				}
				if(location == '中国'){
					var arr =  $('.tddocumentnumber管理费用中国'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> );
				}
				if(location == '泰国'){
					var arr =  $('.tddocumentnumber管理费用泰国'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> );
				}
			}
			if( classification == "应收账款"){ 
				if(location == '越南'){
					var arr =  $('.tddocumentnumber应收账款越南'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> );
				}
				if(location == '中国'){
					var arr =  $('.tddocumentnumber应收账款中国'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> );
				}
				if(location == '泰国'){
					var arr =  $('.tddocumentnumber应收账款泰国'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> );
				}
			}		
			if( classification == "应付账款"){			
				
				if(location == '越南'){
					var arr =  $('.tddocumentnumber应付账款越南'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> );
				}
				if(location == '中国'){
					var arr =  $('.tddocumentnumber应付账款中国'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> );
				}
				if(location == '泰国'){
					var arr =  $('.tddocumentnumber应付账款泰国'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>);
				}
			}
			jQuery('.makesimilar').empty();
			$('.asbkdbsak').empty();
			var arrlist = [];			
			jQuery(arr).each(function( index ) {
				//if(jQuery(this).text() != '' && arrlist.indexOf(jQuery(this).text()) == -1 ){
				jQuery(this).text($.trim(jQuery(this).text()));	
				var str = jQuery(this).text();
				if(jQuery(this).text() != ''){
					arrlist2.push(jQuery(this).text());
				}
				if(jQuery(this).text() != '' && arrlist.indexOf(jQuery(this).text()) == -1 && str.indexOf('-') == -1 ){
					var text = jQuery(this).parents().eq(0).html();
					text = text.replace(/td/g,'div');
					text = text.replace(/div>/g,'div>  ');
					jQuery('.asbkdbsak').append('<div class="is'+jQuery(this).text()+'" ><div style="width:300px;" >'+jQuery(this).parents().eq(2).find('.treopit td').html()+'</div><br>'+text+'</div>');
					var str = jQuery(this).text();
					
					var totalnum = 1;
					for ( var i = 2; i <= 999; i++){
						if( $('.'+jQuery(this).text()+'-'+i).length ){
							totalnum++;
						}else{
							break;
						}
					}
					var str = '('+totalnum+')';
					if(str == '(1)'){
						str = '';
					}
					jQuery('.makesimilar').append("<option  value='"+jQuery(this).text()+"' >"+jQuery(this).text()+" "+str+"</option>");
					arrlist.push(jQuery(this).text());
				}
			});
			
			var options = $('.makesimilar option');
			var arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();
			arr.sort(function(o1, o2) { return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0; });
			options.each(function(i, o) {
			  o.value = arr[i].v;
			  $(o).text(arr[i].t);
			});
			
			jQuery('.makesimilar').select2({width: "100%"});
			
			jQuery('.asbkdbsak button , .asbkdbsak select , .asbkdbsak i  , .asbkdbsak input , .asbkdbsak .modal-trigger').remove();
			jQuery('.asbkdbsak .nofulltext').removeClass('nofulltext');
			
			jQuery('.asbkdbsak a').attr('onclick','');
			jQuery('.makesimilarlabel .dropdown-trigger').css('opacity',1); 
			
			
	
		}else{
			jQuery('.makesimilarlabel .dropdown-trigger').css('opacity',0.4);
			jQuery('.makesimilar').empty();
			jQuery('.makesimilar').select2({width: "100%"});
		}
	});
	
	
	$( "body" ).delegate( '.makesimilarlabel .select-dropdown.dropdown-content li' , "mouseover", function() {	
				 $('.toast.rounded').hide();
				 //M.Toast.dismissAll();
				 var isclass =  $(this).text();
				 isclass = isclass.split(" ");
				 M.toast({html: jQuery('.is'+isclass[0]).html(),  classes: 'rounded' , displayLength: 6000 , inDuration: 50 , outDuration: 50 });
			});

	$( "body" ).delegate( '.makesimilarlabel .select-dropdown.dropdown-content li' , "mouseout", function() {
				 $('.toast.rounded').hide();
				 //M.Toast.dismissAll();
			});

	$('.tab-link').each(function(){
		if( $.cookie("tabremenber") == $(this).attr('data-id') ){
			$(this).trigger("click");
		}
	});
							
		$("input[data-type='currency']").each(function(){
			formatCurrency($(this)); 
		});
		$("input[data-type='currency']").on({
            keyup: function() {
            formatCurrency($(this));
        },
			blur: function() { 
			formatCurrency($(this), "blur");
        }
        });
        function formatNumber(n) {
            return n.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")
        }
		function formatCurrency(input, blur) {                             
			var input_val = input.val(); 
			if (input_val === "" || input_val == "0.00") { return; }
				var original_len = input_val.length;
				var caret_pos = input.prop("selectionStart");
			if (input_val.indexOf(".") >= 0) {
				var decimal_pos = input_val.indexOf(".");
				var left_side = input_val.substring(0, decimal_pos);
				var right_side = input_val.substring(decimal_pos);
				left_side = formatNumber(left_side);
				right_side = formatNumber(right_side);
				if (blur === "blur") {
					// right_side += "00";
				}
				right_side = right_side.substring(0, 2);
				input_val =  left_side + "." + right_side;
			} else {
				input_val = formatNumber(input_val);
				input_val =  input_val;
				// final formatting
				if (blur === "blur") {
				//input_val += ".00";
				}
			}
			input.val(input_val);
			var updated_len = input_val.length;
			caret_pos = updated_len - original_len + caret_pos;
			input[0].setSelectionRange(caret_pos, caret_pos);
			}
	<?php 	if ($currentuser->gm == 1 ) { ?>
		$(".tab-link").each(function(){
			if ( $('#tab-'+$(this).attr('data-id')+' .revision').length > 0){
				$(this).append('<span style="    background: #ffd600;    Color: #000;    padding: 0px 6px;       margin-left: 5px; border-radius: 50%;" >'+$('#tab-'+$(this).attr('data-id')+' .revision').length+'</span>');
			}
		});	
	<?php } ?>	

	$(".dnoon").on('keyup change',function(){
		  var input, filter, table, tr, td, i, txtValue;
		  input = $(this).val();
		  filter = input.toUpperCase();
		  table = $(this).parents('table');
		  tr = table.find('tbody tr');
		  for (i = 0; i < tr.length; i++) {
				if($(this).attr('ref') == 1){
					td = tr[i].getElementsByTagName("td")[12];
				}
				if($(this).attr('ref') == 2){
					td = tr[i].getElementsByTagName("td")[17];
				}
				if($(this).attr('ref') == 3){
					td = tr[i].getElementsByTagName("td")[18];
				}
			   
			   if (td) {
				  txtValue = td.textContent || td.innerText;
				  if (txtValue.toUpperCase().indexOf(filter) > -1) {
					tr[i].style.display = "";
				  } else {
					tr[i].style.display = "none";
				  }
				}
		  }
	});	
});
</script>
<div style="display:none" class="asbkdbsak" ></div>
<?php if($_GET['onlyform'] != 1) { ?>
<table style="display:none" ><tr class="formchiem" > <tr><table>
<br>
<?php } ?>
	
<?php    
// FOOTER
include 'tpl/footer.php'; ?>