<!---- 
Author 	: Herpan /  12-08-2014	
Revisi 	: Ferry / 12-01-2015
Revisi 	: Dhidhik / 30-01-2016
-->

	<?php
			//---------Untuk privellege jika dia ada tombol save----------
				if($group_user->SavePrivillage == 1){
					$cek_autority_save  = "";
				}
				else{
					$cek_autority_save 	= "disabled";
				}
				
				if($group_user->DeletePrivillage == 1){
					$cek_autority_delete  = "";
				}
				else{
					$cek_autority_delete  = "disabled";
				}
				//-------------end----------------------------
	?>
	
<div class="easyui-layout" data-options="fit:true,border:false">
    <!-- Top View-->
    <div id="form-header" data-options="region:'north',border:false" >
        <div id="form-header-wrapper">
            <table width="100%" cellpadding="0" cellspacing="0">
                <tr>
                    <td align="left" width="30%">                            
                        <input type="checkbox" class="<?php echo $lables['button']['suspend']['classKey'];?>" name="chk_suspended" id="chk_suspended" value="3" onClick="suspend(1);" style="margin-top:0px;margin-right:1px;" <?php if($detail->TransStatus == 3){ echo"checked"; } ?> <?=((!in_array($detail->TransStatus,array(0,6,4)))?"disabled":"")?> <?php echo $cek_autority_delete;?>/>
                    	<span style="display:inline-block;margin-top:2px;<?=(($detail->TransStatus==3)?'color:gray;':'color:black')?>"><?php echo $lables['button']['suspend']['lable'];?></span>
                        
                        <a href="#" class="easyui-linkbutton" plain="true" iconCls="icon-currency" onclick="to_transaction()" <?=(in_array($detail->TransStatus,array(1)))?'':'disabled'?>>To Purchase Order</a>
                        
                        <a href="#" class="easyui-linkbutton  <?php echo $lables['button']['refresh']['classKey'];?>" id="refresh-linkbutton" data-options="plain:true,iconCls:'icon-reload'" onclick="location.reload();"> <?php echo $lables['button']['refresh']['lable'];?></a>
                    </td>

                    <td align="center" width="40%">
                        <span id="approval_information">                
                            <?php if($detail->TransStatus==4){
                                if($this->session->userdata('jobtitle')=='MGR'){
                                    echo '<span style="color:#F00;font-size:14px;font-weight:bold;text-decoration:underline;">Need Your Approval</span>';
                                }
                                else{
                                    echo '<span style="color:#F00;font-size:14px;font-weight:bold;text-decoration:underline;">Need Manager Approval</span>';
                                }
                            } 
                            elseif($detail->TransStatus == 1) {
                                echo '<span style="color:#F00;font-size:14px;font-weight:bold;text-decoration:underline;">On Progress</span>';
                            }else{
                                echo '&nbsp;';
                            } ?>
                        </span>
                    </td>

                    <td align="right" width="30%">
                        <span class="form-title"><?=$menu_label?></span>							
                    </td>
                </tr>
            </table>		     	
        </div>			
    </div>
    <!-- End of Top View -->
    
    <!-- Center View -->
    <div id="form-body" data-options="region:'center',border:false">
        <div id="form-wrapper" class="easyui-panel" style="padding:5px;" fit="true">
            <?php if(in_array($detail->TransStatus,array(2,3,8,9))){ ?>
        	<div class="blanket"></div>
            <div class="status-box"><b><?php if($detail->TransStatus==2){ echo 'Finished'; }elseif($detail->TransStatus==3){ echo 'Suspended'; }elseif($detail->TransStatus==8){ echo 'Item Suspended'; }elseif($detail->TransStatus==9){ echo 'Canceled by Dir.'; }else{ echo 'Unknown'; } ?></b></div>
            <?php } ?>
       
            
            <form id="fm_purchase_requisition" name="fm_purchase_requisition" method="post">
                <input type="hidden" name="detail" id="detail"/>
				<input type="hidden" name="detail_id" id="detail_id">
                  
                <!-- Form Header -->
                <table width="100%" height="140" cellpadding="0" cellspacing="0">
                    <tr>
                        <td width="50%" valign="top">&nbsp;</td>
                        
                        <td width="50%" valign="top">
                            <table width="100%" cellpadding="0" cellspacing="1" style="margin-top:4px;">
                                <tr height="20">
                                    <td rowspan="7" valign="top">&nbsp;</td>
                                    <td width="190" style="background:#333399;text-align:center;color:#FFF;">PR. No.</td>
                                    <td width="122" style="background:#333399;text-align:center;color:#FFF;">PR. Date</td>
                                    <td width="122" style="background:#333399;text-align:center;color:#FFF;">Department</td>
                                </tr>
                                
                                <tr height="20">
                                    <td><input type="text" name="txt_preq_no" id="txt_preq_no" class="easyui-validatebox textbox" style="width:190px;height:18px;text-align:center;" value="<?=$detail->PReqNumber?>" required readonly /></td>
                                    <td><input type="text" name="txt_preq_date" id="txt_preq_date" class="easyui-datebox validBackward" style="width:122px;height:20px;" required editable="false" readonly/></td>
                                    
                                    <td>
                                        <select name="cbo_departement" id="cbo_departement" style="width:122px;height:20px;" class="easyui-combobox" editable="false" required readonly 
                                            data-options="
                                                valueField:'DepartmentCode', 
                                                textField:'DepartmentName', 
                                                url:'<?=base_url()?>custom/get_data/department'
                                            " />
                                        </select>
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                </table>
                <!-- End of form header -->
                
                <!-- Item Grid -->
                <div class="easyui-tabs" data-options="tabHeight:18" style="margin:5px 0px;">
                    <div title="Item">
                        <table toolbar="#tb_dtg_item" id="dtg_item" title="" idField="id" rownumbers="true" fitColumns="true" singleSelect="true" style="height:250px;"
                            url="<?=base_url() . $menu_link . "/ajax_item_for_edit/" . $detail->PReqNumber?>"
                        >
                            <thead>
                                <tr>
                                    <th field="ItemCategoryID" editor="{type:'text',options:{readonly:true}}" hidden>Item Category ID</th>
                                    <th field="ItemCode" width="50" editor="{type:'text',options:{required:true}}" data-options="align:'left',halign:'center'">Item Code</th>
                                    <th field="ItemDesc" width="170" editor="description" data-options="align:'left',halign:'center'">Description</th>
                                    <th field="ItemQty" width="30" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',groupSeparator:'.',min:0.01,required:true}}" formatter="formatRp" data-options="align:'center',halign:'center'">Qty</th>
                                    <th field="ItemQtyPO" width="30" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',groupSeparator:'.',required:true, disabled:true}}" formatter="formatRp" data-options="align:'left',halign:'center'">Qty PO</th>
                                    <th field="ItemQtyRI" width="30" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',groupSeparator:'.',required:true, disabled:true}}" formatter="formatRp" data-options="align:'left',halign:'center'">Qty RI</th>
                                    <th field="ItemUnit" width="30" editor="unit" data-options="align:'center',halign:'center'">Unit</th>
                                    <th field="RequiredDate" width="40" editor="{type:'datebox',options:{required:true,editable:false}}" data-options="align:'center',halign:'center'" formatter="formatDate" hidden>Required Date</th>
                                    <th field="Status" width="30" editor="{type:'checkbox',options:{on:'Yes',off:'No'}}" data-options="align:'center'">Close</th>
                                    <th field="ItemQtySpdInfo" width="70" editor="{type:'text', options:{readonly:true}}" data-options="align:'left',halign:'center'">Memo</th>
                                    
                                    <th field="ItemQtySpd" width="40" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',groupSeparator:'.',required:true, disabled:true}}" formatter="formatRp" data-options="align:'left'" hidden>Qty Suspend</th>
                                    <th field="PreqDetailID" width="20" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',groupSeparator:'.',required:true, disabled:true}}" formatter="formatRp" data-options="align:'center'" hidden>Preq Detail ID</th>
                                    <th field="ItemCategoryCode" width="30" editor="{type:'category_code',options:{readonly:true}}" hidden>Item Category Code</th>
                                    <th field="ItemQty_Old" width="30" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',groupSeparator:'.',required:true, disabled:true}}" formatter="formatRp" hidden>Qty Old</th>
                                    <th field="Modus_Type" width="30" editor="{type:'numberbox'}" data-options="align:'center',halign:'center'" hidden>Modus Type</th>
                                    <th field="ItemStatus"       width="30"  editor="{type:'item_status',options:{readonly:true}}" hidden>Item Status</th>
                                </tr>
                            </thead>
                        </table>
                        
                        <div id="tb_dtg_item">
                            <a href="#" class="easyui-linkbutton  <?php echo $lables['button']['delete']['classKey'];?>" id="btnDelete" iconCls="icon-remove" plain="true" onclick="remove_row();" <?= in_array($detail->TransStatus, array(1,3,9,2)) ? 'disabled' : '' ?>> <?php echo $lables['button']['delete']['lable'];?></a>
                            
<!--                            <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="javascript:$('#dtg_item').edatagrid('addRow');" <?=(($detail->AppLevel1Status!=4)?"disabled":"")?>>New</a>
                            <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" plain="true" onclick="javascript:$('#dtg_item').edatagrid('cancelRow');" <?=(($detail->AppLevel1Status!=4)?"disabled":"")?>>Cancel</a>								-->
                        </div>
                    </div>
                </div>
                <!-- End of item grid -->
                
                <table width="100%" cellpadding="0" cellspacing="0">
                <tr>
                	<td width="50%" valign="top">
                        <table width="100%" cellpadding="0" cellspacing="1">
                        <tr>
                            <td width="120" valign="top" style="padding-top:4px;"><b>Description</b></td>
                            <td width="10" valign="top" style="padding-top:4px;"><b>:</b></td>
                            <td>
                                <textarea name="txa_preq_desc" id="txa_preq_desc" rows="4" style="width:335px;resize:none;" <?=($detail->TransStatus!=4)?'readonly':''?>><?=$detail->PReqDesc?></textarea>
                            </td>
                        </tr>
                        </table>
                    </td>
                    <td width="50%" valign="top">&nbsp;</td>
                </tr>
                </table>
            </form>
        </div>
    </div>
    
    <div id="form-footer" data-options="region:'south',border:false">
    	<table width="100%" cellpadding="0" cellspacing="0">
            <tr>
                <td align="right">
                	<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-document" onclick="show_legend();" plain="true">Legend</a>
                    <a href="javascript:void(0)" class="easyui-linkbutton  <?php echo $lables['button']['help']['classKey'];?>" id="btnHelp" iconCls="icon-help" onclick="" plain="true"><?php echo $lables['button']['help']['lable'];?></a>
                    <a href="javascript:void(0)" class="easyui-linkbutton form-button app-button" iconCls="icon-ok" onclick="approval_mgr();" <?=(($this->session->userdata("jobtitle_status") == 1 && $detail->TransStatus == 4) and (date('Y-m-d') >= date('Y-m-d', strtotime($detail->PReqDate))))? '':'disabled'?>>App. Mgr</a>
                    <?php
					if($group_user->ReversePrivillage == 1){
					?>
                    <a href="javascript:void(0)" class="easyui-linkbutton form-button app-button" iconCls="icon-reload" onclick="app_reverse()" <?=(($this->session->userdata("jobtitle_status") == 0) && (in_array($detail->TransStatus,array(1,2))))?'':'disabled'?>>Reverse</a>  
                    <?php
					}
					?>
                    <a href="javascript:void(0)" class="easyui-linkbutton form-button save-button  <?php echo $lables['button']['save']['classKey'];?>" id="btnSave" iconCls="icon-save" onclick="update_data();" <?=($detail->TransStatus!=4)?'disabled':''?> <?php echo $cek_autority_save;?>><?php echo $lables['button']['save']['lable'];?></a>
                    <!-- <a href="javascript:void(0)" class="easyui-linkbutton form-button" iconCls="icon-print" onclick="link_print('<?=$menu_link?>/to_print_detail/<?=$detail->PReqNumber?>');" <?=(in_array($detail->TransStatus,array(3,9)))?'disabled':''?>>Preview & Print</a> -->
                    <a href="javascript:void(0)" class="easyui-linkbutton form-button  <?php echo $lables['button']['preview']['classKey'];?>" id="btnPrint" iconCls="icon-print" onclick="parent.tab_add('Form <?=$menu_label?>', '<?=$menu_link?>', 'icon-print', 'to_print_detail/<?=$detail->PReqNumber?>');" <?=(in_array($detail->TransStatus,array(4,5,6,1,3,9,2)))?'':'disabled'?>><?php echo $lables['button']['preview']['lable'];?></a>
                    <a href="javascript:void(0)" class="easyui-linkbutton form-button 
                            <?php if($this->session->userdata('jobtitle_status')==0){echo $lables['button']['cancel']['classKey'];}else{echo $lables['button']['close']['classKey'];}?>" 
                       id="btnCancel" iconCls="icon-cancel" onclick="<?=($this->session->userdata('jobtitle_status')==0)?'suspend(2)':'parent.tab_close(\'tt\')'?>" 
                            <?=(in_array($detail->TransStatus,array(3,9)) || $detail->AppLevel1Status==1)?'disabled':''?>><?php if($this->session->userdata('jobtitle_status')==0){echo $lables['button']['cancel']['lable'];}else{echo $lables['button']['close']['lable'];}?></a>
                          
                </td>
            </tr>
        </table>
    </div>
</div>

<div id="vendor_dialog" class="easyui-dialog" title="My Dialog" style="width:330px;height:170px;" closed="true" data-options="iconCls:'icon-save',resizable:true,modal:true">
    <table width="100%" cellpadding="0" cellspacing="5">
        <tr height="20">
            <td width="168" colspan="2"><b>Vendor Name</b></td>
        </tr>
        <tr>
            <td colspan="2" width="300">
                <select name="cbg_vendor" class="combo-grid" id="cbg_vendor" style="width:300px;height:20px" required 
                    data-options="
                        panelWidth: 445,
                        idField: 'VendorCode',
                        textField: 'VendorName',
                        url: '<?php echo base_url(); ?>custom/get_data/vendor',
                        method: 'post',
                        columns: [[
                            {field:'VendorCode', title:'Vendor No', halign:'center', align:'center', width:110},
                            {field:'VendorName',title:'Vendor Name', halign:'center', width:250}
                        ]],
                        fitColumns: true
                    ">
                </select>
            </td>
        </tr>
        <tr><td height="20"></td></tr>
        <tr>
            <td colspan="2" align="right" width="300"> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onClick="to_transaction();">&nbsp; OK &nbsp; &nbsp;</a> &nbsp;<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onClick="modal_close('vendor_dialog');">Cancel</a></td>
        </tr>
    </table>
</div>
<?php $this->load->view('v_custom_pop_up');?>
<script type="text/javascript">
	/*========================deklar variabel array for remove===================*/
	var array_item 			= [];
	/*==============================end=========================================*/
	var SavePrivillage 	= '<?php echo $group_user->SavePrivillage;?>';
	
//>>>>>>>>>>>>>>>>>>> TAMBAHAN DHIDHIK 30/01/2016 <<<<<<<<<<<<<<<<<<<<<<<<<<<//
    var tempStatusEditRow= 0; // Nama variable Local, biarken nama variablenya spt ini, n ni value adlh value default,jd jgn dirubah ye... :D
    var tempIndexEditRow = -1;// Nama variable Local, biarken nama variablenya spt ini, n ni value adlh value default,jd jgn dirubah ye... :D
    function setArrayPageStart(){ // nama function biar tetap seperti ini    , isi VALUE nya aja yang disesuaikan page masing-masing   
        //====== reset keytab ================//
        isArrayTabIndex     = -1;//default, jgn diganti valuenya ye,,
        isFormIdDatagrid    = "fm_purchase_requisition"; //nama id tag form yg ngapit grid yg mana grid-nya ada action editable,diisi khusus grid yg ada editablenya
        isIdNameDatagrid    = "dtg_item"; //nama id grid
        isFirstFieldName    = "Status"; //nama field pertama yg ga hidden pada grid, di isi jika grid editable
        isArrayTab          = ["refresh-linkbutton","btnCancel"]; // urutan destiny tab, isinya value menunjukkan [idAwal, idAkhir]
        //======END reset keytab ==============//
    }
//>>>>>>>>>>>>>>>>>>>END TAMBAHAN DHIDHIK 30/01/2016 <<<<<<<<<<<<<<<<<<<<<<<<<<<//

    $(document).ready(function(){
        setArrayPageStart();//tambahan dhidhik 30/01/2016 <<<<<<<<<<<<<<<<<<<<<<<<<<<//
        
	$('#cbo_departement').combobox('select','<?=$detail->DepartmentCode?>');		 
	$('#txt_preq_date').datebox('setValue', '<?=date("d-m-Y", strtotime($detail->PReqDate))?>');
	
	$('#dtg_item').edatagrid({
			onBeginEdit:function(rowIndex){
                editors = $('#dtg_item').datagrid('getEditors',rowIndex);
				
                var n1	= $(editors[1].target);     //Item Code
                var n2  = $(editors[3].target);     //Item Qty
                var n3  = $(editors[7].target);     //Required Date
                var n4  = $(editors[8].target);     //Checkbox Suspend
                var n5  = $(editors[9].target);     //Item Qty Suspend Info
                var n6	= $(editors[10].target);     //Item Qty Suspend
                var n7  = $(editors[4].target);     //Item Qty PO
                var n8  = $(editors[14].target);    //Modus Type
				var n9  = $(editors[15].target);    //Item Status
				
				if('<?= in_array($detail->TransStatus,array(4))?>'){
					/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
					$('.save-button').linkbutton('disable');
					/*=================================end============================================================*/
				}
					
                $(n1).prop('readonly',true);
                $(n5).prop('readonly',true);
				$(n4).prop('disabled',true);
				
                if('<?= in_array($detail->TransStatus, array(0,1)) ?>'){
                    $(n2).prop('readonly', true);
                    $(n3).datebox('disable',true);
					$(n4).prop('disabled',false);
                }
                
				n2.numberbox({
                    onChange:function(){
                        item_status     = n9.text('getData').val();
                        item_qty        = n2.numberbox('getValue');
                       
                        if((item_status == 3) && (item_qty > 1)){
                            messageAlertBiasa('Warning', "Quantity untuk 'Advance Payment' tidak boleh lebih dari satu (1)",'error');
                            n2.numberbox('setValue', 1);
                        }
                    }
                });
				
                $(n4).click(function(){
                    if($(this).is(':checked')){
                        var itemqty     = n2.numberbox('getValue');
                        var itemqtypo   = n7.numberbox('getValue');
                                                
                        var suspend_qty = parseFloat(itemqty) - parseFloat(itemqtypo);
						
                        n6.numberbox('setValue', suspend_qty);
						n8.numberbox('setValue', 2);
						save_suspend_item(1);                       
                    }
                    else{
                        n6.numberbox('setValue', 0);
                        n8.numberbox('setValue', 2);
                        save_suspend_item(0);
                    }
                });
                
                //======== dhidhik, 28/01/2016 ===========//           Ni tinggal copypaste aja     
                if(tempIndexEditRow == -1){//-1 berarti row belum ada yg diedit
                    tempStatusEditRow   = 1;// set klo edit row open editable nya
                    tempIndexEditRow    = rowIndex;//simpan row indexnya
                }else{
                    $('#'+isIdNameDatagrid).datagrid('endEdit', rowIndex);//endEdit saat row lain dalam keadaan terbuka Editablenya
                    $("#"+isIdNameDatagrid).datagrid('selectRow', tempIndexEditRow); //biarken seperti ini ye
                }              
                //========end dhidhik, 28/01/2016 ===========//
                
            },
            onEndEdit: function(rowIndex){
                    if('<?= in_array($detail->TransStatus,array(4))?>'){
                            /*====================on beg in edit saat grid di klik maka tombol save disable===================*/
                            save_button_endedit(SavePrivillage);
                            /*=================================end============================================================*/
                    }
                    
                
                //======== dhidhik, 28/01/2016 ===========// Ni tinggal Copy paste aja
                if(tempIndexEditRow == rowIndex){ // kalo index row sama dengan index yg terimpan pada variable local maka set nilai variable ke nilai default
                    tempStatusEditRow   = 0;// set variable ke nilai default
                    tempIndexEditRow    = -1;// set variable ke nilai default
                }
                //========end dhidhik, 28/01/2016 ===========//
            },
                    
            //======== dhidhik, 28/01/2016 ===========// Ni tinggal Copy paste aja
            onSelect:function(rowIndex){//ini event untuk mengatasi menutup di row lain yg diedit(tidak ada kosong), saat diselect di row lain, isinya event biarkan spt ini
                if(tempIndexEditRow>-1&&tempIndexEditRow!=rowIndex){//yang ini biarkan tetap seperti ini, copy paste aje ye
                    $('#'+isIdNameDatagrid).datagrid('endEdit', rowIndex);
                    $("#"+isIdNameDatagrid).datagrid('selectRow', tempIndexEditRow); //biarken seperti ini ye
                    checkValidDatagrid(isFormIdDatagrid); //biarken seperti ini ye
                }
            }
            //========end tambahan Dhidhik , 28/01/2016
	});
	
	$("#fm_purchase_requisition").click(function() {
            //save_row();
            //========tambahan Dhidhik , 28/01/2016
            var rstValid = checkValidDatagrid(isFormIdDatagrid); //biarken seperti ini ye
            if(rstValid){ //biarken seperti ini ye
                if(tempIndexEditRow>-1){ //biarken seperti ini ye
                    $('#'+isIdNameDatagrid).datagrid('endEdit', tempIndexEditRow); //biarken seperti ini ye
                }                    
            }else{ //biarken seperti ini ye
                $("#"+isIdNameDatagrid).datagrid('selectRow', tempIndexEditRow); //biarken seperti ini ye
            }
            //========end tambahan Dhidhik , 28/01/2016
	});
        datagrid_item_type("dtg_item");//untuk warna grid
    });

    function save_row(){
	$('#dtg_item').edatagrid('saveRow');
    }

    function save_suspend_item(status) {  
		save_row();
		url                 = base_url + 'list/purchases_requisition/suspend_item';

		var message_text    = '';
		var PReqNumber      = $("#txt_preq_no").val();
		var detail          = JSON.stringify($('#dtg_item').datagrid('getRows'));
	
		if(status == 0) {
				message_text    = 'Anda yakin, ingin melakukan UnSuspend item?';
		}
		else{
				message_text    = 'Anda yakin, ingin melakukan Suspend item?';            
		}
                isStatusShortKey = false;
		$.messager.confirm('Warning :', message_text,  
				function(r){
					if (r){
						$.post(url, {PReqNumber:PReqNumber, detail:detail, status:status}, function(result){
							if (result.status == true){
								$.messager.alert('Success',result.message,'info',function(){
                                                                    isStatusShortKey = true;
									location.reload();						                    
								});				
							} 
							else {
								$.messager.alert('Failed',result.message,'error',function(){
                                                                    isStatusShortKey = true;
									location.reload();
								});				
							}
						},'json');
					}
					else {
                                            isStatusShortKey = true;
						location.reload();						                    
					}
				}
		);
    }

    function update_data(){
		var cretated_by 		= '<?php echo $detail->CreatedBy;?>';
		var login_as 			= '<?php echo $this->session->userdata('username');?>';
		var job_title 			= '<?php echo $this->session->userdata('jobtitle_status');?>'; 
		var department_session 	= '<?php echo $this->session->userdata("department");?>';
		var department_code 	= '<?=$detail->DepartmentCode?>';
		
		var url             	= '<?= base_url();?>custom/custom/checking_update';
		var no_transaksi    	= $('#txt_preq_no').val();
		var trans_status 		= '<?=$detail->TransStatus?>';
		flag 					= true;
		
		item 					= $('#dtg_item').datagrid('getRows');
		$.each(item, function(index,value){
			if(value.ItemStatus == 3){
				if(value.ItemQty != 1){
					flag = false;
				}
			}
		});
		
		if(flag == false){
			$.messager.alert('Unseccessfull','Maaf Item Qty Tidak Boleh Lebih/Kurang Dari (1) Satu, Untuk Adv. Payment','error',function(){	
				$('#dtg_item').datagrid('reload'); 	
			});
		}
		else if(job_title == 0){
			$('#dtg_item').edatagrid('saveRow');
	
			var i       = $('#dtg_item').datagrid('getRows');
			var detail  = JSON.stringify(i);	
	
			$("#detail").val(detail);
			edit_transaction('<?php echo $menu_link?>','#fm_purchase_requisition', no_transaksi, url, trans_status);	
		}
		else if((job_title == 1) && (department_code == department_session)){
			$('#dtg_item').edatagrid('saveRow');
	
			var i       = $('#dtg_item').datagrid('getRows');
			var detail  = JSON.stringify(i);	
	
			$("#detail").val(detail);
			edit_transaction('<?php echo $menu_link?>','#fm_purchase_requisition', no_transaksi, url, trans_status);	
		}
		else if(cretated_by == login_as){
			$('#dtg_item').edatagrid('saveRow');
	
			var i       = $('#dtg_item').datagrid('getRows');
			var detail  = JSON.stringify(i);	
	
			$("#detail").val(detail);
			edit_transaction('<?php echo $menu_link?>','#fm_purchase_requisition', no_transaksi, url, trans_status);	
		}
		else{
                    isStatusShortKey = false;
			$.messager.alert('Warning','Maaf anda tidak berhak merubah transaksi ini, silahkan cek hak akses anda','warning',function(){
                            isStatusShortKey = true;
				$('#dtg_item').edatagrid('reload');
			});
		}
    }
    
	function suspend(type){
		var created_by 		= '<?php echo $detail->CreatedBy;?>';
		var login_as 		= '<?php echo$this->session->userdata('username');?>';
		var job_title 		= '<?php echo $this->session->userdata('jobtitle_status');?>';
		var url             = '<?= base_url();?>custom/custom/checking_suspend';
		
		suspend_check_trans('F', type, '<?=$menu_link?>', $('#txt_preq_no').val(), 'Purchase Requisition', url, created_by, login_as, job_title);
	}
	
	function approval_mgr(){
		
		var job_title_status 	= '<?php echo $this->session->userdata("jobtitle_status");?>';
		var department_session 	= '<?php echo $this->session->userdata("department");?>';
		var department_code 	= '<?=$detail->DepartmentCode?>';
		var url             	= '<?= base_url();?>custom/custom/checking_approval';
		var no_transaksi    	= $('#txt_preq_no').val();
		
		if((department_code == department_session) && (job_title_status == 1)){
			app_custom('<?=$menu_link?>/approval','#fm_purchase_requisition', no_transaksi, url);
		}
		else{
			messageAlertBiasa('Info','Approv gagal, Anda bukan Manager dengan Department yang bersangkutan','info');
		}
		//
	}
	
	function app_reverse(){
		var no_transaksi    = $('#txt_preq_no').val();
	
		checking_reverse(no_transaksi,function(check){
			
			if(check.status == true){
				reversed_data('F','<?=$menu_link?>', no_transaksi, 'Purchase Requisition');
			}else{
			   $.messager.alert('Unseccessfull',check.message,'error',function(){
					location.reload();
				});
			}
		});
	}

	function remove_row(){
            if(mustBeChooseRowDatagrid('dtg_item')){
                var item = $('#dtg_item').datagrid('getData').total;
	
		if(item <= 1){
			messageAlertBiasa('Warning','Anda tidak dapat menghapus list item, minimum list item adalah satu (1)','error');
		}
		else {
			var selectedrow     = $('#dtg_item').datagrid('getSelected');
			var row_index       = $('#dtg_item').datagrid('getRowIndex', selectedrow);
                        isStatusShortKey = false;
			$.messager.confirm('Confirmation :', 'Anda yakin, Anda ingin menghapus item "' + selectedrow.ItemCode + '"',  
				function(r){
					if (r){
						array_item.push(selectedrow.PreqDetailID);
						
						$("#detail_id").val(JSON.stringify(array_item));
                                                
						//$('#dtg_item').datagrid('deleteRow', row_index);
                                                
                    //==== tambah dhidhik,05/02/2016 
                    deleteRowDatagrid(tempIndexEditRow,isIdNameDatagrid);//parameter pertama adalah index yang teredit row nya, parameter kedua adalah id table datagrid                 
                    //====end tambah dhidhik,05/02/2016
						/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
						save_button_endedit(SavePrivillage);
						/*=================================end============================================================*/
						
						/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
						$('.app-button').linkbutton('disable');
						/*=================================end============================================================*/
					}
                                        isStatusShortKey = true;
				}
			);        
						
		} 
            }
		           
	}

    function to_transaction(){

        var appfinished     = '<?=$detail->TransStatus;?>';
        var no_transaksi    = $('#txt_preq_no').val();
        var vendor_code     = $('#cbg_vendor').combogrid('getValue');
        var no_trans        = no_transaksi.replace(/\//g,"__");
        var vendor_code     = vendor_code.replace(/\//g,"__");


        if(appfinished == 1){
           if(vendor_code == ''){
                modal_open('Select Vendor', 'vendor_dialog');
           }else{ 
                modal_close('vendor_dialog');
                parent.tab_add('New Purchases Order','list/purchases_order','icon-add','add/'+no_trans+'/'+vendor_code);
            }
        }else{
            $.messager.alert('Unseccessfull','TransStatus Finished. Transaksi selesai.','error',function(){
                //location.reload();
            });
        }
        
    }
</script>