<link rel="stylesheet" href="css/new_mxerp.css">
<?php ob_start();
$PageSecurity = 4;
$PageName = 'Site to Site Transfer Issue';
include('includes/DefinePOClass.php');
date_default_timezone_set('Asia/Calcutta');
include('cocoon_config.php');
function getFieldvalue_cake($table, $condition, $val, $field)
{

  //echo "select ".$field." from ".$table." where ".$condition." ='".$val."'";
  $sql = mysqli_query($link1, "select " . $field . " from " . $table . " where " . $condition . " ='" . $val . "'");
  $r = mysqli_fetch_array($sql);
  //echo "select ".$field." from ".$table." where ".$condition." ='".$val."'"; 
  return ($r[$field]);
}

if (($_REQUEST['Save'])) {

  //****************  Start Code Generations **********************//  
  $prefixcode = "TFD";
  $siteCode = $_REQUEST['site'];
  $site_Code = substr($siteCode, 0, 3);
  $sql = "select * from transfer_issue where sitecode = '" . $_REQUEST['site'] . "'";
  $result = DB_query($sql, $db);
  $numrows = DB_num_rows($result);

  if ($numrows > 0) {
    $strChar = $site_Code . "/" . $prefixcode . "/" . $year . $Afteryear . "/";
    if ($numrows > 0) {
      $maxval = $numrows;
    } else {
      $maxval = 0;
    } {
      $strChar = $site_Code . "/" . $prefixcode . "/" . $year . $Afteryear . "/";
    }
  } else {
    $strChar = $site_Code . "/" . $prefixcode . "/" . $year . $Afteryear . "/";
  }

  $strFinal = $maxval + 1;
  $strBothFinal = $strChar . str_pad($strFinal, 6, "0", STR_PAD_LEFT);

  //****************  End Of Code Generations **********************// 
  $qty = $_REQUEST['itemcode'];
  $qty1 = count($qty);
  $status = 'N';
  $data_tranfer_issue['sitecode']           =  $_REQUEST['site'];
  $data_tranfer_issue['sitecode_to']        =  $_REQUEST['sitecode2'];
  $data_tranfer_issue['tostore']            =  $_REQUEST['storeTo'];
  $data_tranfer_issue['issuedate']          = FormatDateForSQL($_REQUEST['issuedate']);
  $data_tranfer_issue['issue_slipno']       = $strBothFinal;
  $data_tranfer_issue['transfer_type']      = $_REQUEST['trnsferType'];
  $data_tranfer_issue['remarks']            = $_REQUEST['remarks'];
  $data_tranfer_issue['from_company']       = $_REQUEST['companyid'];
  $data_tranfer_issue['to_company']         = $_REQUEST['companyid1'];
  $data_tranfer_issue['mrn_number']         = $_REQUEST['mrnno'];
  $data_tranfer_issue['transporter_name']   = $_REQUEST['transport'];
  $data_tranfer_issue['vehicle_no']         = $_REQUEST['vehicle_no'];
  $data_tranfer_issue['request_id']         = $_REQUEST['request_id'];
  $data_tranfer_issue['transaction_time']   = date("Y-m-d H:i:s");
  $data_tranfer_issue['createdby']          = $_SESSION['UserID'];
  $data_tranfer_issue['createddate']        = FormatDateForSQL(date('d/m/Y'));
  $s->RecordInsert('transfer_issue', $data_tranfer_issue);
  $Lastreq_id = DB_Last_Insert_ID($db, 'transfer_issue', 'id');
  if ($Lastreq_id != '') {

    for ($i = 0; $i < count($_REQUEST['itemdataid']); $i++) {
      if ($_REQUEST['itemdataid'][$i] != '' && $_REQUEST['stock'][$i] != '0') {

        $data_tranfer_issue_detail['transfer_issue_id']          =  $Lastreq_id;
        $data_tranfer_issue_detail['itemid']                     =  $_REQUEST['itemdataid'][$i];
        $data_tranfer_issue_detail['current_balance']            =  $_REQUEST['stock'][$i];
        $data_tranfer_issue_detail['issueqty']                   =  $_REQUEST['q1'][$i];
        $data_tranfer_issue_detail['issueqty1']                  =  $_REQUEST['q2'][$i];
        $data_tranfer_issue_detail['item_description']           =  $_REQUEST['desc'][$i];
        $data_tranfer_issue_detail['conv_fac']                   =  $_REQUEST['confac'][$i];
        $data_tranfer_issue_detail['uom']                        =  $_REQUEST['unitnamea'][$i];
        $data_tranfer_issue_detail['uom1']                       =  $_REQUEST['unitnamea2'][$i];
        $data_tranfer_issue_detail['batch_no']                   =  $_REQUEST['batchno'][$i];
        $data_tranfer_issue_detail['mfg']                        =  ConvertSQLDate($_REQUEST['dateofmfg'][$i]);
        $data_tranfer_issue_detail['expiry']                     =  ConvertSQLDate($_REQUEST['dateofexpiry'][$i]);


        $s->RecordInsert('transfer_issue_details', $data_tranfer_issue_detail);
        $dtls_Lastreq_id = DB_Last_Insert_ID($db, 'transfer_issue_details', 'id');


        /*************************   Stock Valution *******************************/


        /* $check_current_opening="Select * from stock_valuation_tbl where  site='".$_REQUEST['site']."'
                   and  store='".$_REQUEST['storeTo']."' and mst_itemid='".$_POST['itemdataid'][$i]."' 
                    and batch_no='".$_REQUEST['batchno'][$i]."'    and flag=0 order by id ASC "; */


        $primary_unit = $s->getField('item_master', 'id', $_REQUEST['itemdataid'][$i], 'mst_unitid');
        $secondary_unit = $s->getField('item_master', 'id', $_REQUEST['itemdataid'][$i], 'conv_unit');
        $confac = $s->getField('item_master', 'id', $_REQUEST['itemdataid'][$i], 'conv_factor');
        $data_stock['site']                     = $_REQUEST['site'];
        $data_stock['store']                    = $_REQUEST['storeTo'];
        $data_stock['mst_itemid']               = $_REQUEST['itemdataid'][$i];
        $data_stock['primary_unit']             = $primary_unit;
        $data_stock['secondary_unit']           = $secondary_unit;
        $data_stock['against_voucher_main_id']  = $Lastreq_id;
        $data_stock['against_voucher_dtls_id']  = $dtls_Lastreq_id;
        $data_stock['against_tra_id']           = $check_current_op_row['id'];
        $data_stock['type']                     = 'STI';
        if ($check_current_op_row['status'] == '1')
          $data_stock['status'] = 1;
        else
          $data_stock['status'] = 0;
        $data_stock['outwardqty_primary']       = $_REQUEST['q1'][$i];
        $data_stock['pending_qty']              = $_REQUEST['q1'][$i];
        $data_stock['outwardqty_secondary']     = $_REQUEST['q2'];
        $data_stock['inward_rate']              = $outward_rate;
        $data_stock['outward_value']            = $outwardamount;
        $data_stock['batch_no']                 = $_REQUEST['batchno'][$i];
        $data_stock['date_of_mfg']              = FormatDateForSQL($_REQUEST['dateofmfg'][$i]);
        $data_stock['date_of_expiry']           = FormatDateForSQL($_REQUEST['dateofexpiry'][$i]);
        $data_stock['trasaction']               = FormatDateForSQL($_REQUEST['issuedate']) . " " . date('H:i:s', time());
        $inserresult2 = $s->RecordInsert('stock_valuation_tbl', $data_stock);

        $pendingqty = $pendingqty - $outwards_qty;
        if ($inwardpenqty != 0)
          $status = 0;
        else
          $status = 1;
                          
            
                  /*$primary_unit=$s->getField('item_master','id',$_POST['itemdataid'][$i],'mst_unitid');
                  $secondary_unit=$s->getField('item_master','id',$_POST['itemdataid'][$i],'conv_unit');
                  $data_stock['site']                     =$_REQUEST['site'];
                  $data_stock['store']                    =$_REQUEST['storeTo'];
                  $data_stock['mst_itemid']               =$_POST['itemdataid'][$i];
                  $data_stock['primary_unit']             =$primary_unit;
                  $data_stock['secondary_unit']           =$secondary_unit;
                  $data_stock['against_voucher_main_id']  =$Lastreq_id;
                  $data_stock['against_voucher_dtls_id']  =$dtls_Lastreq_id;
                  $data_stock['type']                     ='STI';                       
                  $data_stock['outwardqty_primary']       =$_REQUEST['q1'][$i];
                  $data_stock['outwardqty_secondary']     =$_REQUEST['q2'][$i];
                  $data_stock['date_of_mfg']              =$_REQUEST['dateofmfg'][$i];
                  $data_stock['date_of_expiry']           =$_REQUEST['dateofexpiry'][$i];    
                  $data_stock['batch_no']                 =$_REQUEST['batchno'][$i];
                  $data_stock['pending_qty']              =$_REQUEST['q1'][$i];
      
                  $data_stock['trasaction']               =FormatDateForSQL($_REQUEST['issuedate'])." ".date('H:i:s', time());
                  $inserresult2=$s->RecordInsert('stock_valuation_tbl', $data_stock);*/


        /**********************************  Inserting Records in batch table (cake php)*****************************/
        //echo $_REQUEST['storecode'];
        $majorid = $s->getField('item_master', 'id', $_REQUEST['itemdataid'][$i], 'CategoryID');
        $majormainid = $s->getField('stockmaincategory', 'id', $majorid, 'ref_major_id');
        $storecode = $s->getField('storetype', 'id', $_REQUEST['storeTo'], 'StoreCode');
        $unitcode = $s->getField('unitsofmeasure', 'unitid', $primary_unit, 'unitname');
        $majorcode = getFieldvalue_cake('majors', 'id', $majormainid, 'major_code');


        $itemcode = $s->getField('item_master', 'id', $_REQUEST['itemdataid'][$i], 'StockID');
        $item_name = $s->getField('item_master', 'id', $_REQUEST['itemdataid'][$i], 'item_name');
        $batchno = $_REQUEST['batchno'][$i];




        $query_batch_item = mysqli_fetch_array(mysqli_query($link1, "select SUM(qty) as qty,id FROM batchdetails WHERE item_code='" . $itemcode . "' and store_code='" . $storecode . "' and batch_no='" . $batchno . "' GROUP BY item_code"));

        //$batch_qty=$query_batch_item['qty'];


        if ($_REQUEST['q1'][$i] <= $_REQUEST['stock'][$i]) {
          $stockbatchqty = $query_batch_item['qty'] - $_REQUEST['q1'][$i];
          $update_batch = mysqli_query($link1, "update batchdetails set qty ='" . $stockbatchqty . "' where item_code='" . $itemcode . "' and store_code='" . $storecode . "' and batch_no='" . $batchno . "'");
        }

        $query_item = mysqli_fetch_array(mysqli_query($link1, "select SUM(stock_level),id FROM storeitems WHERE item='" . $itemcode . "' and store_code='" . $storecode . "' GROUP BY item"));

        if ($_REQUEST['q1'][$i] <= $_REQUEST['stock'][$i]) {
          $stockqty = $query_item['SUM(stock_level)'] - $_REQUEST['q1'][$i];
          $update = mysqli_query($link1, "update storeitems set stock_level ='" . $stockqty . "' where item='" . $itemcode . "' and store_code='" . $storecode . "' and major_code='" . $majorcode . "'");
        }










        /******************************************************************************************************************/


        if ($_REQUEST['trnsferType'] == 'MRN') {
          $status_site = "1";
          DB_query("update addmrnqty set site_transfer_issue_status=1 where mst_itemid='" . $_POST['itemdataid'][$i] . "' 
                                and issue_id='" . $_REQUEST['mrnno'] . "'", $db);
        }
      }
    }
  }


  if ($_REQUEST['trnsferType'] == 'MRN') {
    $get_num_rows = DB_query("Select * from addmrnqty where issue_id='" . $_REQUEST['mrnno'] . "'", $db);
    $num_rows = DB_num_rows($get_num_rows);
    $check_item_stat = DB_query("Select * from addmrnqty where issue_id='" . $_REQUEST['mrnno'] . "' and site_transfer_issue_status='1'", $db);
    $received_num_rows = DB_num_rows($check_item_stat);
    if ($num_rows == $received_num_rows) {
      $updatePOStat = DB_query("Update addmrn set site_tranf_status='1' where id='" . $_REQUEST['mrnno'] . "'", $db);
    }
  }


  if ($inserresult2 == true) {
    $_SESSION['success_msg'] = "Saved Successfully";
    echo "<script>location.href='index.php?route=Inventory/transation/site_transfer_issue_index&modid=" . $_REQUEST['modid'] . "&frmid=" . $_REQUEST['frmid'] . "'</script>";
  }
}
?>
<div class="body_contain">
  <div class="tab_div">
    <h1><?php echo $s->getField('modules_form', 'id', $_REQUEST['frmid'], 'frm_name'); ?></h1>
    <form name="form1" onsubmit="return chkValidate();" method="post">
      <div align="center">
        <table width="100%" cellpadding="3" cellspacing="0" border="0">
          <tr class="row1">
            <td width="13%" align="right">From Branch</td>
            <td width="20%">
              <div id="companybranch1">
                <?php
                if ($_SESSION['AssignedBranch'] != '') {
                  $ss = "Select loccode, locationname from locations  where CompanyId='" . $_SESSION['ACGCompanyId'] . "' and loccode in('" . $_SESSION['AssignedBranch'] . "')";
                  $site_sql = DB_query($ss, $db);
                } else {
                  $ss = "Select loccode,locationname from locations where CompanyId='" . $_SESSION['ACGCompanyId'] . "'";
                  $site_sql = DB_query($ss, $db);
                }
                ?>
                <select name="site" onchange="get_store_by_site();" id="site">
                  <option value="0">---Select---</option>
                  <?php
                  while ($site_row = DB_fetch_array($site_sql)) {
                  ?>
                    <option value="<?php echo $site_row['loccode']; ?>" <?php echo ($sitecode == $site_row['loccode'] ? 'selected' : '') ?>><?php echo $site_row['locationname']; ?></option>
                  <?php } ?>
                </select>
              </div>
            </td>
            <td width="13%" align="right">Issue Slip No.</td>
            <td width="20%"><input name="issue_slipno" type="text" id="issue_slipno" readonly="readonly" value="Autogenerate"></td>
            <td width="13%" align="right">Date</td>
            <td><input name="issuedate" type="text" id="recieved_date" value="<?php echo date('d/m/Y'); ?>" size="15" class="datepicker" /></td>
          </tr>
          <tr class="row1">
            <td align="right">Store</td>
            <td>
              <?php
              $sql_main_store = "select id,StoreName from storetype";
              $result_main_store = DB_query($sql_main_store, $db);

              ?>
              <select name="sitecode2" id="sitecode2">
                <option value="0">---Select---</option>
                <?php
                while ($rs_main_store = DB_fetch_array($result_main_store)) {
                ?>
                  <option value="<?php echo $rs_main_store['id']; ?>"><?php echo $rs_main_store['StoreName']; ?></option>
                <?php } ?>
              </select>
            </td>
            <td align="right">Against</td>
            <td><select name="trnsferType" onchange="get_MRN_number(this)">
                <option value="">Select</option>
                <option value="Direct">Direct</option>
                <option value="Request">Request</option>
                <!--  <option value="MRN">MRN</option> -->
              </select></td>
            <!-- <td>MR Number</strong></td>
    <td id="tdShowMRN"> <select name="mrnno"><option>Select</option></select></td> -->


            <td align="right">Transport Name</td>
            <td><input type="text" name="transport" id="transport" /></td>
          </tr>
          <tr class="row1">
            <td align="right">Vehicle No.</td>
            <td><input type="text" name="vehicle_no" id="vehicle_no" /></td>
            <td align="right">From Store</td>
            <td><select name="storeTo" id="storeTo">
                <option value="0">---Select---</option>
              </select></td>
            <td align="right">Request No.</td>
            <td><select name="request_id" id="request_id" onchange="get_request_data(this)">
                <option value="0">---Select---</option>
              </select></td>
          </tr>
        </table>
      </div>

      <div id="divShowSiteTransfer" style="overflow:auto; width:100%; height:auto">
      </div><!--divShowSiteTransfer-->
    </form>
  </div>
</div>



<script type="text/javascript">
  function getdataforSearchItem() {
    //$('#ItemListDiv').html('<center><span style="font-size:20px;"><strong>Loading...</strong></span></center>');
    var mainCategoryId = $('#lightbox1').find('select[name=CategoryID]').val();
    var subCategoty_id = $('#lightbox1').find('select[name=subcategory]').val();
    var item_name = $('#lightbox1').find('input[id=StockID]').val();
    var item_short_code = $('#lightbox1').find('input[id=itemScode]').val();
    var store = document.getElementById("storeTo").value;

    $('#lightbox1').html('<center><span style="font-size:20px;"><strong>Loading...</strong></span></center>');

    $.ajax({
      url: "issu_searchpopupfinish.php",
      type: "POST",
      data: {
        site: $('#site').val(),
        mainCategoryid: mainCategoryId,
        subCategoryid: subCategoty_id,
        itemName: item_name,
        itemScode: item_short_code,
        store: store,
        forfilter: 10
      },
      success: function(data) { //alert(data);
        $('#lightbox1').html(data);
      }
    });

  }

  function getSubCategory(id) {

    $.post('getItemList.php', {
      "subgrp": id,
      "subdis": 'yes'
    }, function(data) {
      $('#subcategory').html(data);
    });
  }

  $(function() {
    $("#recieved_date").datepicker({
      dateFormat: 'dd/mm/yy',
      minDate: '0'
    });

    $(".datepicker").datepicker({
      dateFormat: 'dd/mm/yy',
      minDate: '0'
    });

  });
</script>
<script language="javascript" type="text/javascript">
  function showconvac(str, id) {

    var brk = id.split('_');

    if (str == '0') {

      if (brk[1] == undefined) {
        var conf = document.getElementById('confactor').value;
        document.getElementById("confac").value = conf;
        var id1 = "reciveqty";
        var hrdvalue = document.getElementById(id1).value;
        chk_recived_qty(hrdvalue, id1);
      } else {
        var conf = document.getElementById('confactor_' + brk[1]).value;

        document.getElementById("confac_" + brk[1]).value = conf;
        var id1 = "reciveqty_" + brk[1];
        var hrdvalue = document.getElementById(id1).value;
        chk_recived_qty(hrdvalue, id1);
      }


    } else {
      var brk = id.split('_');

      var xmlhttp;
      if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
      } else { // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
          if (brk[1] == undefined) {
            document.getElementById("confac").value = xmlhttp.responseText;
            var id1 = "reciveqty";
            var hrdvalue = document.getElementById(id1).value;
            chk_recived_qty(hrdvalue, id1);
          } else {
            document.getElementById("confac_" + brk[1]).value = xmlhttp.responseText;
            var id1 = "reciveqty_" + brk[1];
            var hrdvalue = document.getElementById(id1).value;
            chk_recived_qty(hrdvalue, id1);
          }
          //document.getElementById("empdta").innerHTML=data[1];
          //var id1="stock_qty_"+brk[1];
          //var hrdvalue=document.getElementById(id1).value;
          //calcValue1(hrdvalue,id1);

        }
      }

      if (brk[1] == undefined) {
        var str2 = document.getElementById("itemdataid").value;
      } else {
        var str2 = document.getElementById("itemdataid_" + brk[1]).value;
      }
      xmlhttp.open("GET", "convactor.php?site=" + str + "&itemid=" + str2, true);
      xmlhttp.send();

    }




  }

  function chk_recived_qty(val, id) {
    var id1 = id.split("_");
    var i = id1[1];
    //alert(id);
    if (id1[1] == undefined) {
      var stockBal = document.getElementById("stock").value;
      //var isuRate = document.getElementById("issuerate").value;
      var confac = document.getElementById("confac").value;
      if (confac == '') confac = 0;
      if (parseInt(val) > parseInt(stockBal)) {
        alert("Issued Quantity Cannot Be Greater Than Stock Balance");
        document.getElementById("reciveqty").value = '';
        document.getElementById("secondary").value = '';
        document.getElementById("reciveqty").focus();
        return false;
      } else {
        if (isuRate == '') {
          isuRate = 0
        }
        var totamt = parseFloat(isuRate) * val;
        document.getElementById("totalamt").value = totamt.toFixed(2);
        var secondaryqty = parseFloat(val) * parseFloat(confac);
        document.getElementById("secondary").value = secondaryqty.toFixed(2);
      }
    } else {
      var stockBal = document.getElementById("stock_" + i).value;
      //  var isuRate = document.getElementById("issuerate_"+i).value;
      var confac = document.getElementById("confac_" + i).value;
      if (confac == '') confac = 0;
      if (parseInt(val) > parseInt(stockBal)) {
        alert("Issued Quantity Cannot Be Greater Than Stock Balance");
        document.getElementById("reciveqty_" + i).value = '';
        document.getElementById("secondary_" + i).value = '';
        document.getElementById("reciveqty_" + i).focus();
        return false;
      } else {
        // if(isuRate==''){isuRate=0}
        //var totamt = parseFloat(isuRate)*val;
        // document.getElementById("totalamt_"+i).value=totamt.toFixed(2);
        var secondaryqty = parseFloat(val) * parseFloat(confac);
        document.getElementById("secondary_" + i).value = secondaryqty.toFixed(2);
      }
    }
  }



  /*function chk_recived_qty(obj)
  {
      var stockQty=$(obj).closest('tr').find('td:eq(7)').find('input[type="text"]').val();
        if(parseFloat(stockQty) < parseFloat($(obj).val()) )
        {
          alert(' Issue quantity should be less stock quantity');
          $(obj).val(stockQty);
        }
  }*/
  function get_MRN_number(obj) {

    if ($('#site').val() == '0') {
      alert('Please select from branch.');
      return false;
    }
    if ($('#sitecode2').val() == '0') {
      alert('Please select To branch.');
      return false;
    }


    /*if($(obj).val()=='MRN')
            {   $('#divShowSiteTransfer').html('');
            $.ajax({
            url : "get_mrn_by_site.php",
            type : "POST",
            data : {
            action:'getMRN',  
            store:$('#storeTo').val(),
            site:$('#site').val()
            },
            success : function(data) { //alert(data);
                        $('#tdShowMRN').html(data);
                         }
                 });
        }
        else
        {
           $('#tdShowMRN').html('<input name="mrnno" type="text" />');
           $.ajax({
            url : "get_struct_dirct_transfer.php",
            type : "POST",
            data : {
            },
            success : function(data) {//alert(data);
                    $('#divShowSiteTransfer').html(data);
                         }
                 });
        }*/
    $('#tdShowMRN').html('<input name="mrnno" type="text" />');
    $.ajax({
      url: "get_struct_dirct_transfer.php",
      type: "POST",
      data: {},
      success: function(data) { //alert(data);
        $('#divShowSiteTransfer').html(data);
      }
    });
    if ($(obj).val() == 'Request') {
      $.ajax({
        url: "common_ajax_json.php",
        type: "POST",
        data: {
          form_type: 'getRequest',
          to_store: $('#sitecode2').val()
        },
        success: function(data) {
          var dataArr = JSON.parse(data);
          $('#request_id').html('<option value="0">Select</option>');
          if (parseInt(dataArr.code) > 0) {
            $.each(dataArr.data.request_no, function(index, val) {
              $('#request_id').append('<option value="' + val.id + '">' + val.name + '</option>');
            });
          }
        }
      });
    } else {
      $('#request_id').html('<option value="0">Select</option>');
    }
  }

  function get_store_by_site() { //getStore
    if ($('#site').val() == '0') {
      alert('Please select site to.');
      return false;
    }
    /*if($('#sitecode2').val()=='0')
    {
      alert('Please select site to.');
      return false;
    }*/

    $.ajax({
      url: "get_mrn_by_site.php",
      type: "POST",
      data: {
        action: 'getStore1',
        site: $('#site').val()
      },
      success: function(data) { //alert(data);
        //var data2=data.split('/');
        $('#storeTo').html(data);
        // $('#storeTO').html()
      }
    });
  }

  function showsitename165(str) {
    var site = $('#site').val();
    if ($('#storeTo').val() == 0) {
      alert('Please select store.');
      return false;
    }

    var store1 = $('#storeTo').val();;
    var xmlhttp;
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("divShowSiteTransfer").innerHTML = xmlhttp.responseText;
      }
    }
    xmlhttp.open("GET", "get_mrnitemdata.php?id=" + str + "&site=" + site + "&store=" + store1, true);
    xmlhttp.send();
  }

  function issuedetails(str) {
    var branch = document.getElementById("site").value;
    var godown = document.getElementById("store").value;

    if (str.length == 0) {
      document.getElementById("ISSUE").innerHTML = "";
      return;
    }
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("ISSUE").innerHTML = xmlhttp.responseText;
      }
    }
    xmlhttp.open("GET", "JobWorkItems.php?q=" + str + "&site=" + branch + "&store=" + godown, true);
    xmlhttp.send();

  }

  function openPopupProfile(i) {
    window.open("issu_searchpopupfinish.php?rowcount=" + i, "profiles_popup_window", "height=425,width=640,toolbar=no,menubar=no,dependent=yes,resizable=yes");
  }
  var xmlHttp

  function GetXmlHttpObject() {
    var xmlHttp = null;
    try {
      // Firefox, Opera 8.0+, Safari
      xmlHttp = new XMLHttpRequest();
    } catch (e) {
      // Internet Explorer
      try {
        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
    }
    return xmlHttp;
  }


  function opendata() {

    var sitecode = document.getElementById("site").value;
    var date = document.getElementById("recieved_date").value;

    if (sitecode == '0') {
      alert("Must Select Site");
      document.getElementById("site").focus();
      return;
    } else if (date == '') {
      alert("Must Select Date");
      document.getElementById("recieved_date").focus();
      return;
    }
    if ($('#storeTo').val() == 0) {
      alert('Please select store.');
      return false;
    }

    var xmlhttp;
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

        $("#lightbox1").dialog({
          title: 'Item List',
          modal: true,
          resizable: false,
          width: 1000,
          height: 350,
          closeText: 'fechar',
          draggable: true,
          show: 'fade',
          hide: 'fade',
          dialogClass: 'main-dialog-class',
          buttons: {
            Exit: function() {
              $(this).dialog("close");
            }
          }
        });

        //alert(xmlhttp.responseText);
        document.getElementById("lightbox1").style.display = 'block';
        document.getElementById("lightbox1").innerHTML = xmlhttp.responseText;
        // document.getElementById("textitem").innerHTML=data[1];  
        // alert();
      }
    }
    var store = document.getElementById("storeTo").value;
    //alert(store);


    xmlhttp.open("GET", "issu_searchpopupfinish.php?store=" + store + "&site=" + sitecode, true);
    xmlhttp.send();

  }

  function callDate() {
    $('.datepicker').removeClass('hasDatepicker').datepicker({
      dateFormat: 'dd/mm/yy',
      changeMonth: true,
      changeYear: true,
      yearRange: '-80:+20'
    });
    $('.datepicker').datepicker();
  }


  function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode != 46 && charCode > 31 &&
      (charCode < 48 || charCode > 57))
      return false;

    return true;
  }


  function getSubGrp(id) {
    //alert();
    $.post('getItemList.php', {
      "subgrp": id,
      "subdis": 'yes'
    }, function(data) {

      $('#subgrp').html(data);
    });
  }



  function searchItems() {
    var maingrp = $('#maingrp').val();
    var subgrp = $('#subgrp').val();
    var itemcode = $('#icode').val();
    var itemname = $('#iname').val();
    var store = $('#store').val();
    //alert("maingrp = "+maingrp+" subgrp = "+subgrp+" itemcode = "+itemcode+" itemname = "+itemname);
    if (maingrp != '') {
      //alert("maingrp = "+maingrp+" subgrp = "+subgrp+" itemcode = "+itemcode+" itemname = "+itemname);
      $.post('getProductList.php', {
        "maingrp": maingrp,
        "subgrp": subgrp,
        "itemcode": itemcode,
        "itemname": itemname,
        "searchitembyissue": 'yes',
        "store": store
      }, function(data) {

        $('.itemlist').html(data);
      });
    } else
      alert('Please select maingroup');
  }



  function hidedata() {
    document.getElementById("lightbox1").style.display = 'none';
  }

  function getItemsList1(id, code, name, unitname, unitname1, unitname_value, unitname_value1, total_current, abc, confac, ctr) {


    var ctr = $('#dataTable').find('tr:last').find('td:eq(1)').find('input[type="text"]').attr('id');
    var rowCount = $('#dataTable').find('tr').length;
    var rowItem = $('#dataTable').find('tr').find('td:eq(2)').find('input[type="hidden"]').val();
    var ctr1 = parseInt(document.getElementById("rowcount1").value) + 1;
    var itemcount = parseInt(document.getElementById('hiditemcount').value) + 1;
    var edit_cnt = document.getElementById('edit_cnt').value;
    if (edit_cnt == '') {
      var counter = 1;
    } else if (edit_cnt > itemcount) {
      var counter = edit_cnt;
      var itemcount = parseFloat(counter) + parseFloat(itemcount);
    } else {
      var counter = edit_cnt;
    }

    if (rowCount == 1 && rowItem == '') {

      if (document.getElementById('itemdataid_1')) {
        document.getElementById('itemdataid_1').value = id;
        document.getElementById('itemcode_1').value = code;
        document.getElementById('itemname_1').value = name;
        document.getElementById('u1_1').value = unitname;
        document.getElementById('u2_1').value = unitname1;
        document.getElementById('ua1_1').value = unitname_value;
        document.getElementById('ua2_1').value = unitname_value1;
        document.getElementById('confac_1').value = confac;
        document.getElementById('total_current_1').value = total_current;
      }
    } else {
      var i = ctr1;
      addRow22('dataTable');
      if (document.getElementById('itemdataid_' + i)) {

        document.getElementById('itemdataid_' + i).value = id;
        document.getElementById('itemcode_' + i).value = code;
        document.getElementById('itemname_' + i).value = name;
        //document.getElementById('descriptions_'+i).value = name;
        document.getElementById('u1_' + i).value = unitname;
        document.getElementById('u2_' + i).value = unitname1;
        document.getElementById('ua1_' + i).value = unitname_value;
        document.getElementById('ua2_' + i).value = unitname_value1;
        document.getElementById('confac_' + i).value = confac;
        document.getElementById('total_current_' + i).value = total_current;

      }
    }


  }

  function displayBatch(value, id) {
    // alert("The paragraph was double-clicked."); 
    // alert(value+"  "+id);
    //alert(id);
    var itemcode = '';
    var itemname = '';
    var unit = '';
    var item_ids = '';

    if (id.indexOf('_') != '-1') {
      var ids = id.split('_');
      itemcode = document.getElementById('itemcode_' + ids[1]).value;
      itemname = document.getElementById('itemname_' + ids[1]).value;
      unit = document.getElementById('u1_' + ids[1]).value;
      item_ids = document.getElementById('itemdataid_' + ids[1]).value;
      //alert(item_ids);

    } else {
      itemcode = document.getElementById('itemcode').value;
      itemname = document.getElementById('itemname').value;
      unit = document.getElementById('u1_').value;
      item_ids = document.getElementById('itemids').value;
      //alert("asdas"+item_ids);

    }

    if (itemcode == '') {
      alert("Please select items");
    } else if (itemname == '') {
      alert("Please enter itemname");
    } else if (unit == '') {
      alert("Please enter unit");
    } else {
      //var LeaveType=document.getElementById("LeaveType_"+tt2).value;
      $("#lightbox1").dialog({
        title: 'Batch List',
        modal: true,
        resizable: false,
        width: 900,
        height: 400,
        closeText: 'fechar',
        draggable: true,
        show: 'fade',
        hide: 'fade',
        dialogClass: 'main-dialog-class',
        buttons: {
          Exit: function() {
            $(this).dialog("close");
          }
        }
      });

      var site = document.getElementById("site").value;
      var store = document.getElementById("storeTo").value;
      //var invoiceTime=$('#invoiceTime').val();
      //alert('Getstock_items_store.php?site='+site+'&invoicedate='+invoicedate+'&invoiceTime='+invoiceTime);
      $.ajax({
        url: 'getItemBatch.php?item_id=' + item_ids + '&batch_id=' + id + '&site=' + site + '&store=' + store,
        success: function(result) {
          $('#lightbox1').html(result);
        }
      });
    }
  }


  function addBatchData(id, value, unit, batch, mfg, expiry) {




    if (id.indexOf("_") != "-1") {
      var ids = id.split('_');
      if ($('#stock_' + ids[1]).val() != '') {


        var batch_no = new Array();
        jQuery('input[id^=batchno_]').each(function() {
          batch_no.push(parseInt(jQuery(this).val()));
          //alert(partic_pack);
        });

        for (var i = 0; i < batch_no.length; i++) {
          if (batch_no[i] == batch) {
            alert('Batch  Is All Ready Selected.');
            return false;

          }
        }

        //alert(a);

        var thisRow = $('#batchno_' + ids[1]).closest('tr')[0];
        $(thisRow).clone().insertAfter(thisRow).find('input:text');
        $('#stock_' + ids[1]).val(value);
        $('#batchno_' + ids[1]).val(batch);
        var dArr = mfg.split("-"); // ex input "2010-01-18"

        $('#dateofmfg_' + ids[1]).val(mfg);

        $('#dateofexpiry_' + ids[1]).val(expiry);

      } else {
        var dArr = mfg.split("-"); // ex input "2010-01-18"
        $('#stock_' + ids[1]).val(value);
        $('#batchno_' + ids[1]).val(batch);
        $('#dateofmfg_' + ids[1]).val(mfg);
        $('#dateofexpiry_' + ids[1]).val(expiry);

      }
    } else {
      if ($('#stock').val() != '') {
        var thisRow = $("#batchno").closest('tr')[0];
        $(thisRow).clone().insertAfter(thisRow).find('input:text');
        $('#stock').val(value);
        $('#batchno').val(batch);
        $('#dateofmfg').val(mfg);
        $('#dateofexpiry').val(expiry);
      } else {
        $('#stock').val(value);
        $('#batchno').val(batch);
        $('#dateofmfg').val(mfg);
        $('#dateofexpiry').val(expiry);
      }
    }

    $('.datepicker').removeClass('hasDatepicker').datepicker({
      dateFormat: 'dd/mm/yy',
      changeMonth: true,
      changeYear: true,
      yearRange: '-80:+20'
    });
  }



  function changeQty(value, obj, id) {
    var brk = id.split("_");

    if (brk[1] == undefined) {

    } else {
      if (value == '') {
        document.getElementById('q2_' + brk[1]).value = 0.00;
      } else {


        var stock = parseFloat($(obj).closest('tr').find('input[id=stock_' + brk[1] + ']').val());

        if (parseFloat(value) > stock) {
          alert('Quantity cannot be greater then stock');
          $(obj).closest('tr').find('input[id=q1_' + brk[1] + ']').val('');
          return false;
        }
        var conv = $(obj).closest('tr').find('input[id=confac_' + brk[1] + ']').val();
        var secqty = parseFloat(conv) * parseFloat(value);
        if (isNaN(secqty))
          secqty = 0;
        else
          document.getElementById('q2_' + brk[1]).value = secqty;
      }
    }
  }



  function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode != 46 && charCode > 31 &&
      (charCode < 48 || charCode > 57))
      return false;

    return true;
  }

  function addRow22(tableID) {
    if (document)
      var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    var rowCount = table.rows.length;
    if (document.getElementById("hiditemcount").value == '')
      r = rowCount + 1;
    else {
      var t = document.getElementById("edit_cnt").value;
      var t1 = document.getElementById("hiditemcount").value;
      r = parseInt(t1);
      r1 = parseInt(t1) + 1;
    }
    var row1 = document.getElementById("rowcount1").value;
    var rr = parseInt(row1) + 1;
    document.getElementById("rowcount1").value = rr;
    var row = table.insertRow(rowCount);
    document.getElementById("hiditemcount").value = rr;
    document.getElementById("edit_cnt").value = rr;
    var colCount = table.rows[0].cells.length;
    for (var i = 0; i < colCount; i++) {
      var newcell = row.insertCell(i);
      //newcell.className='tabledata';
      newcell.style.background = '#ffffff';

      $('.datepicker').removeClass('hasDatepicker').datepicker({
        dateFormat: 'dd/mm/yy',
        changeMonth: true,
        changeYear: true,
        yearRange: '-80:+20'
      });

      newcell.innerHTML = table.rows[0].cells[i].innerHTML;


      //newcell.innerHTML = table.rows[0].cells[i].innerHTML;


      //alert(newcell.childNodes[0].type);
      switch (newcell.childNodes[0].type) {
        case "text":
          newcell.childNodes[0].value = "";
          var nod_id = newcell.childNodes[0].id.split("_");
          if (!isNaN(nod_id[1]))
            newcell.childNodes[0].id = nod_id[0] + '_' + rr;
          else
            newcell.childNodes[0].id = nod_id[0] + '_' + nod_id[1] + '_' + rr;
          break;
        case "hidden":
          newcell.childNodes[0].value = "";
          var nod_id = newcell.childNodes[0].id.split("_");
          if (!isNaN(nod_id[1]))
            newcell.childNodes[0].id = nod_id[0] + '_' + rr;
          else
            newcell.childNodes[0].id = nod_id[0] + '_' + nod_id[1] + '_' + rr;
          break;
        case "button":
          var nod_id = newcell.childNodes[0].id.split("_");
          if (!isNaN(nod_id[1]))
            newcell.childNodes[0].id = nod_id[0] + '_' + rr;
          else
            newcell.childNodes[0].id = nod_id[0] + '_' + nod_id[1] + '_' + rr;
          break;
        case "checkbox":
          newcell.childNodes[0].checked = false;
          var nod_id = newcell.childNodes[0].id.split("_");
          if (!isNaN(nod_id[1]))
            newcell.childNodes[0].id = nod_id[0] + '_' + rr;
          else
            newcell.childNodes[0].id = nod_id[0] + '_' + nod_id[1] + '_' + rr;
          break;
        case "select-one":
          newcell.childNodes[0].selectedIndex = 0;
          var nod_id = newcell.childNodes[0].id.split("_");
          if (!isNaN(nod_id[1]))
            newcell.childNodes[0].id = nod_id[0] + '_' + rr;
          else
            newcell.childNodes[0].id = nod_id[0] + '_' + nod_id[1] + '_' + rr;
          break;
      }
      //document.getElementById("stock_perunit_"+rowCount).value=1;
    }
    //document.getElementById(countid).innerHTML=rowCount;

  }


  function deleteRow_return(tableID) {

    if ($('#dataTable').find('input[type="checkbox"][name="delitem[]"]:checked').length > 0) {
      try {
        var table = document.getElementById(tableID);
        //alert(table);
        var rowCount = table.rows.length;

        for (var i = 0; i < rowCount; i++) {
          var row = table.rows[i];

          var chkbox = row.cells[0].childNodes[0];

          if (null != chkbox && true == chkbox.checked) {
            if (rowCount <= 1) {
              alert("Cannot delete all the rows.");
              break;
            }

            table.deleteRow(i);
            rowCount--;
            i--;
          }
        }

      } catch (e) {
        alert(e);
      }
    } else
      alert('Please select at least one row for delete.');
  }

  function showsitename158(str) {

    var xmlhttp;
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var data = xmlhttp.responseText.split("__");

        document.getElementById("hid-Godown-div").innerHTML = data[0];
        document.getElementById("workorder").innerHTML = data[1];

      }
    }
    xmlhttp.open("GET", "GoDownIssueSlip10.php?site=" + str, true);
    xmlhttp.send();

    //xmlhttp.open("GET","getSort.php?s="+str+"&cat="+cat,true);


  }


  function Get_oderdata(str) {


    if (str == "") {
      document.getElementById("dept").innerHTML = "";
      return;
    }
    var xmlhttp;
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var data = xmlhttp.responseText.split("__");
        if ($('#against').val() == 'Direct') {
          $('#jobcarddata').html('<input name="job_card_no" type="text" id="job_card_no"  style="width:100%;"  size="15" />');


        } else
          document.getElementById("jobcarddata").innerHTML = data[0];
        document.getElementById("work_order_date").value = data[1];

      }
    }

    xmlhttp.open("GET", "get_orderdata9.php?salid=" + str, true);
    xmlhttp.send();

  }







  function Get_oderdata1(str) {


    if (str == "") {
      document.getElementById("dept").innerHTML = "";
      return;
    }
    var xmlhttp;
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var data = xmlhttp.responseText.split("__");
        //alert(data[0]);
        //document.getElementById("oderitem").innerHTML=data[0];
        document.getElementById("jobcarddate1").innerHTML = data[1];

      }
    }

    xmlhttp.open("GET", "get_joborderdata.php?salid=" + str, true);
    xmlhttp.send();

  }

  function calamt(str, str1) {
    var k = str.split("_");
    if (k[1] == undefined) {
      if (parseFloat(document.getElementById("reciveqty").value) > parseFloat(document.getElementById("stock").value)) {
        alert("Receive Qty Should Be less then Stock Qty");
        document.getElementById("reciveqty").value = '';
      }

    } else {
      var i = k[1];
      if (parseFloat(document.getElementById("reciveqty_" + i).value) > parseFloat(document.getElementById("stock_" + i).value)) {
        alert("Receive Qty Should Be less then Stock Qty");
        document.getElementById("reciveqty_" + i).value = '';

      }
    }


  }

  function chkValidate() {
    var chkflag = false;
    if ($('#site').val() == 0) {
      alert('Please select branch.');
      return false;
    }
    if ($('#sitecode2').val() == 0) {
      alert('Please select to branch.');
      return false;
    }

    if ($('#recieved_date').val() == '') {
      alert('Please Enter Receipt date.');
      return false;
    }
    if ($('#store').val() == 0) {
      alert('Please select stote.');
      return false;
    }

    if ($('#work_order_no').val() == 0) {
      alert('Please select work order number.');
      return false;
    }

    if ($('#work_order_date').val() == '') {
      alert('Please Enter work order date.');
      return false;
    }
    if ($('#job_card_no').val() == 0 || $('#job_card_no').val() == 0) {
      alert('Please Enter job card number.');
      return false;
    }

    $('#dataTable').find('tr').each(function() {

      /*if($(this).find('td:eq(5)').find('select').val() == 0)
       {chkflag=true;
        alert('Please select size.');
        return false;
       }
      if($(this).find('td:eq(6)').find('select').val() == 0)
       { chkflag=true;
        alert('Please select Grade.');
        return false;
       }*/
      if ($(this).find('td:eq(8)').find('input').val() == '') {
        chkflag = true;
        alert('Please enter batch no.');
        return false;
      }
      if ($(this).find('td:eq(9)').find('input').val() == '') {
        chkflag = true;
        alert('Please enter issue quantity  .');
        return false;
      }
      if ($(this).find('td:eq(10)').find('select').val() == 0) {
        chkflag = true;
        alert('Please select process.');
        return false;
      }

    });
    if (chkflag) {
      return false;
    }



    return true;
  }

  function get_request_data(ths) {
    if (parseInt($(ths).val()) > 0) {
      var store = document.getElementById("storeTo").value;
      var sitecode = document.getElementById("site").value;
      var url = "common_ajax_json.php";
      var params = {};
      params['form_type'] = 'getRequestData';
      params['request_id'] = $(ths).val();
      params['store'] = store;
      params['sitecode'] = sitecode;
      jQuery.ajax({
        url: url,
        type: "POST",
        data: params,
        async: false,
        success: function(data) {
          var dataArr = JSON.parse(data);
          if (parseInt(dataArr.code) > 0) {
            var i = 0;
            $.each(dataArr.data.item_data, function(index, val) {
              getItemsList1(val.item_id, val.StockID, val.item_name, val.unitname, val.unitname1, val.mst_unitid, val.conv_unit, val.total_current, i, val.conv_factor);
              $('#dataTable tr:last input[id^="req_"]').val(val.primary_qty);
            });
            i++;
          }
        }
      });
    }
  }
</script>
<style type="text/css">
  .body_lightbox1 {
    width: 100%;
    background-color: #e7e7e7;
    position: absolute;
    /*left:280px;*/
    left: 4px;
    /*top:95px;*/
    top: 5px;
    padding-left: 5px;
    padding-right: 5px;
    border: #666666 solid 3px;
  }
</style>