<?php
include('cocoon_config.php');
$table = 'opening_stockitemwise';
$action = $_REQUEST['action'];
$daction = $_REQUEST['daction'];
$msgErr = '';
$status = true;

function renderAddStockResults($request, $main_store, $get_store_id, $db)
{
  global $s;

  $searchPerformed = !empty($request['search']) || !empty($request['ajax_search']);
  $result = false;
  $searchMessage = 'Search by Item Name, Item Code, Category or Sub Category to load items.';
  $rowsPerPage = 20;
  $currentPage = isset($request['page']) ? max(1, (int) $request['page']) : 1;
  $offset = ($currentPage - 1) * $rowsPerPage;
  $companyId = $_SESSION['ACGCompanyId'];
  $totalRecords = 0;
  $totalPages = 0;

  if ($searchPerformed) {
    $filter = array();
    $category = isset($request['category']) ? trim($request['category']) : '0';
    $subcategory = isset($request['subcategory']) ? trim($request['subcategory']) : '0';
    $partname = isset($request['part_name']) ? trim($request['part_name']) : '';
    $partcode = isset($request['part_code']) ? trim($request['part_code']) : '';
    $storeId = isset($request['store']) ? trim($request['store']) : '';

    $filter[] = "item_master.CompanyId='" . $companyId . "'";
    if ($partname != '') {
      $filter[] = "item_master.item_name like '%" . addslashes($partname) . "%'";
    }
    if ($partcode != '') {
      $filter[] = "item_master.StockID like '%" . addslashes($partcode) . "%'";
    }
    if ($category != '' && $category != '0') {
      $filter[] = "item_master.CategoryID='" . addslashes($category) . "'";
    }
    if ($subcategory != '' && $subcategory != '0') {
      $filter[] = "item_master.SubCategoryID='" . addslashes($subcategory) . "'";
    }

    $filter[] = "item_master.batch_item='Y'";

    if (count($filter) <= 3) {
      $searchMessage = 'Enter at least one search filter to load items.';
    } else {
      $whereClause = implode(' and ', $filter);
      $fromClause = " from item_master
        left join unitsofmeasure on unitsofmeasure.unitid=item_master.mst_unitid ";
      $countSql = "select count(distinct item_master.id) as total_records " . $fromClause . " where " . $whereClause;
      $countResult = DB_query($countSql, $db);
      $countRow = DB_fetch_array($countResult);
      $totalRecords = (int) $countRow['total_records'];
      if ($totalRecords <= 0) {
        $searchMessage = 'No matching items found.';
      } else {
        $totalPages = max(1, (int) ceil($totalRecords / $rowsPerPage));
        if ($currentPage > $totalPages) {
          $currentPage = $totalPages;
          $offset = ($currentPage - 1) * $rowsPerPage;
        }
        $sql = "select distinct item_master.*, unitsofmeasure.unitname as unit_name " . $fromClause . " where " . $whereClause . " order by item_master.item_name asc LIMIT " . $offset . "," . $rowsPerPage;
        $result = DB_query($sql, $db);
      }
    }
  }

  ob_start();
  ?>
  <table width="100%" border="0" cellspacing="0" cellpadding="3" align="center" class="thborder">
    <tr>
      <th width="18%">Item Code</th>
      <th>Item Name</th>
      <th width="6%">Unit</th>
      <th width="9%">Batch</th>
      <th width="9%">Date of Mfg.</th>
      <th width="9%">Date of Expiry</th>
      <th width="9%">Stock Qty.</th>
      <th width="9%">Rate</th>
      <th width="9%">Amount</th>
    </tr>
    <?php
    $i = 0;
    if ($result && DB_num_rows($result) > 0) {
      while ($myrow = DB_fetch_array($result)) {
        $parameter = $myrow['id'];
        $unit = $myrow['unit_name'];
        ?>
        <tr>
          <td><input type="checkbox" name="rowid" id="rowid_<?php echo $i; ?>" value="<?php echo $parameter; ?>" /> <input type="button" onclick="javascript:addRow(this,this.id);" id="add_<?php echo $i; ?>" value="+"><input type="button" value="-" id="del_<?php echo $i; ?>" onclick="delete_row($(this).closest('tr').remove());"> <?php echo $myrow['StockID']; ?> <input type="hidden" id="rowid_<?php echo $i; ?>" name="rowid_<?php echo $i; ?>" value="<?php echo $myrow['id']; ?>" /></td>
          <td><?php echo $myrow['item_name']; ?></td>
          <td><input type="text" name="unit[<?php echo $i; ?>]" value="<?php echo $unit; ?>" readonly="readonly" id="unit_<?php echo $i; ?>"></td>
          <td><input type="text" name="batch[<?php echo $i; ?>]" style="width:100px;" id="batch_<?php echo $i; ?>" onkeyup="javascript:checkBatch(this.value,this.id)" placeholder="N/A" data-batch="<?php if ($myrow['batch_no'] == 'Y') {
                                                                                                                                                                                          echo 'Y';
                                                                                                                                                                                        } else {
                                                                                                                                                                                          echo 'N';
                                                                                                                                                                                        } ?>" /></td>
          <td style='display:None;'><input type="text" id='data-batch_<?php echo $i; ?>' name='data-batch' value='<?php if ($myrow['batch_no'] == 'Y') {
                                                                                                                      echo 'Y';
                                                                                                                    } else {
                                                                                                                      echo 'N';
                                                                                                                    } ?>'></td>
          <td><input type="text" name="mfg[<?php echo $i; ?>]" id="mfg_<?php echo $i; ?>" class="datepicker" value="<?php echo $_POST['todate']; ?>" placeholder="dd/mm/yyyy" onchange="checkfuturedate(this.value)" /></td>
          <td><input type="text" name="expiry[<?php echo $i; ?>]" id="expiry_<?php echo $i; ?>" class="datepicker" value="<?php echo $_POST['todate']; ?>" placeholder="dd/mm/yyyy" onchange="checkitemdate(this)" /></td>
          <td><input type="text" name="stock[<?php echo $i; ?>]" onclick="return checkstock(this.value,this.id)" onkeypress="return isNumberKey(event)" id="stock_<?php echo $i; ?>" /></td>
          <td><input type="text" name="rate[<?php echo $i; ?>]" onkeypress="return isNumberKey(event)" id="rate_<?php echo $i; ?>" onkeyup="javascript:changeAmount(this.value,'rate',this.id)" /></td>
          <td><input type="text" name="amount[<?php echo $i; ?>]" onkeypress="return isNumberKey(event)" id="amount_<?php echo $i; ?>" onfocus="calAmt(<?php echo $i; ?>);" readonly="" /></td>
        </tr>
        <?php
        $i++;
      }
    } else {
      ?>
      <tr>
        <td colspan="9" align="center"><?php echo $searchMessage; ?></td>
      </tr>
      <?php
    }
    ?>
  </table>
  <input type="hidden" name="row_count" id="row_count" value="<?php echo $i; ?>">
  <input type="hidden" name="res" id="res" value="">
  <?php
  if (!empty($totalRecords) && $totalRecords > 0) {
    $startRecord = $offset + 1;
    $endRecord = min($offset + $rowsPerPage, $totalRecords);
    ?>
    <div style="margin-top:10px; text-align:center;">Showing <?php echo $startRecord; ?> to <?php echo $endRecord; ?> of <?php echo $totalRecords; ?> items</div>
    <?php
    if ($totalPages > 1) {
      $pageWindowStart = max(1, $currentPage - 2);
      $pageWindowEnd = min($totalPages, $currentPage + 2);
      ?>
      <div style="margin-top:10px; text-align:center;">
        <?php if ($currentPage > 1) { ?>
          <button type="button" class="search" onclick="loadStockPage(1)">First</button>
          <button type="button" class="search" onclick="loadStockPage(<?php echo $currentPage - 1; ?>)">Previous</button>
        <?php } ?>
        <?php
        for ($pageNo = $pageWindowStart; $pageNo <= $pageWindowEnd; $pageNo++) {
          if ($pageNo == $currentPage) {
            echo '<strong style="padding:4px 8px;">' . $pageNo . '</strong>';
          } else {
            echo '<button type="button" class="search" onclick="loadStockPage(' . $pageNo . ')">' . $pageNo . '</button>';
          }
        }
        ?>
        <?php if ($currentPage < $totalPages) { ?>
          <button type="button" class="search" onclick="loadStockPage(<?php echo $currentPage + 1; ?>)">Next</button>
          <button type="button" class="search" onclick="loadStockPage(<?php echo $totalPages; ?>)">Last</button>
        <?php } ?>
      </div>
      <?php
    }
  }

  return ob_get_clean();
}


$sql_user_store = "select hmis_storeid,StoreCode from www_users left join storetype on storetype.id=www_users.hmis_storeid where www_users.id='" . $_SESSION['UserID'] . "'";
$result_user_store = DB_query($sql_user_store, $db);
$rs_user_store = DB_fetch_array($result_user_store);
$main_store = $rs_user_store[1];


$sql_other_store = "select store_id,StoreCode from www_users_dtls left join storetype on storetype.id=www_users_dtls.store_id where user_id='" . $_SESSION['UserID'] . "'";
$result_other_store = DB_query($sql_other_store, $db);
while ($rs_other_store = DB_fetch_array($result_other_store)) {
  $store[] = $rs_other_store['StoreCode'];
}
if (!empty($store)) {
  $get_store_id = implode(",", $store);
}

if (!empty($_REQUEST['ajax_search'])) {
  echo renderAddStockResults($_REQUEST, $main_store, isset($get_store_id) ? $get_store_id : '', $db);
  exit;
}

?>
<script src="js/function-ajax.js"></script>
<script language="javascript">
  function calAmt() {
    var a = document.getElementById('stock').value;
    var b = document.getElementById('rate').value;
    document.getElementById('amount').value = a * b;

  }

  var addStockSearchTimer = null;

  function buildAddStockSearchParams(page) {
    return "ajax_search=1"
      + "&search=Search"
      + "&page=" + encodeURIComponent(page || 1)
      + "&site=" + encodeURIComponent(document.getElementById('site').value)
      + "&store=" + encodeURIComponent(document.getElementById('store').value)
      + "&category=" + encodeURIComponent(document.getElementById('category').value)
      + "&subcategory=" + encodeURIComponent(document.getElementById('subcategory').value)
      + "&part_name=" + encodeURIComponent(document.getElementById('part_name').value)
      + "&part_code=" + encodeURIComponent(document.getElementById('part_code').value);
  }

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

  function loadAddStockResults(page) {
    var xmlhttp;
    if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest();
    } else {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("addStockResults").innerHTML = xmlhttp.responseText;
        refreshDatePickers();
      }
    }
    xmlhttp.open("POST", window.location.href, true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send(buildAddStockSearchParams(page));
    return false;
  }

  function queueAddStockSearch() {
    clearTimeout(addStockSearchTimer);
    addStockSearchTimer = setTimeout(function() {
      loadAddStockResults(1);
    }, 300);
  }

  function runAddStockSearch() {
    clearTimeout(addStockSearchTimer);
    return loadAddStockResults(1);
  }

  function loadStockPage(page) {
    return loadAddStockResults(page);
  }

  document.addEventListener('change', function(e) {
    if (e.target && (e.target.id === 'store' || e.target.id === 'subcategory')) {
      queueAddStockSearch();
    }
  });
</script>
<style>
  #slidingDiv {
    /*display: none;*/
    height: 100px;
    background-color: #D9D6DA;
    padding: 20px;
  }
</style>
<link rel="stylesheet" href="css/new_mxerp.css">
<div class="body_contain">
  <div class="tab_div">
    <div id="container">
      <h1>Opening Stock Item Wise</h1>
      <form method="post" id="addStockSearchForm" onsubmit="return runAddStockSearch();">
        <table width="100%" border="0" cellspacing="3" cellpadding="3">
          <tr class="row1">
            <td width="13%" align="right">Branch</td>
            <td width="20%">
              <?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" id="site" onchange="showStore(this.value);">
                <option value="">---Select---</option>
                <?php
                while ($site_row = DB_fetch_array($site_sql)) {
                ?>
                  <option value="<?php echo $site_row['loccode']; ?>" <?php echo ($_REQUEST['site'] == $site_row['loccode'] ? 'selected' : '') ?>><?php echo $site_row['locationname']; ?></option>
                <?php } ?>
              </select>
            </td>
            <td width="13%" align="right">Store</td>
            <td width="20%">
              <div id='hid-Godown-div'><?php

                                        $sql_store = "select id, StoreCode, StoreName from storetype  where Store_Site='" . $_REQUEST['site'] . "'and (id IN(SELECT hmis_storeid FROM www_users WHERE id='" . $_SESSION['UserID'] . "') or id IN(SELECT store_id FROM www_users_dtls WHERE user_id='" . $_SESSION['UserID'] . "'))";
                                        $resultStkLocs = DB_query($sql_store, $db);
                                        ?>
                <select name="store" id="store" onchange="queueAddStockSearch();">
                  <option value="0">Select</option>
                  <?php
                  while ($myrow = DB_fetch_array($resultStkLocs)) {
                    $p = '';
                    if ($myrow['id'] == $_REQUEST['store'])
                      $p = "selected";
                  ?>
                    <option value="<?php echo $myrow['id']; ?>" <?php echo $p; ?>><?php echo $myrow['StoreName']; ?></option>
                  <?php
                  }
                  ?>
                </select>
              </div>
            </td>
            <td width="13%" align="right">Received Date</td>
            <td>
              <input type="text" name="reveive_date" id="reveive_date" value="<?php echo date('d/m/Y'); ?>" class="datepicker" placeholder="dd/mm/yyyy" onchange="chkdteformat(this)" />
            </td>
          </tr>
          <tr class="row1">
            <td align="right">Stock Category</td>
            <td><select name="category" id="category" onchange="getdata1(this.value); queueAddStockSearch();">
                <option value="0">Select Group</option>
                <?php
                $store_sql = "SELECT * FROM stockmaincategory  where CompanyId='" . $_SESSION['ACGCompanyId'] . "' ";
                $store_result = DB_query($store_sql, $db);
                while ($store_row = DB_fetch_array($store_result)) {
                  $p = '';
                  if ($store_row['id'] == $_REQUEST['category'])
                    $p = "selected";

                ?>
                  <option value="<?php echo $store_row['id']; ?>" <?php echo $p; ?>><?php echo $store_row['stockmaincategoryname']; ?></option>
                <?php } ?>
              </select></td>
            <td align="right">Stock Sub Category</td>
            <td id="hiddiv">
              <select name="subcategory" id="subcategory" onchange="queueAddStockSearch();">
                <option value="0">Select Sub Group</option>
                <?php $store_sql = "SELECT * FROM stockcategory  where stockmaincategory='" . $_REQUEST['category'] . "'";
                $store_result = DB_query($store_sql, $db);
                while ($store_row = DB_fetch_array($store_result)) {
                  $p1 = '';
                  if ($store_row['id'] == $_REQUEST['subcategory']) {
                    $p1 = "selected";
                  }
                ?>
                  <option value="<?php echo $store_row['id'] ?>" <?php echo $p1 ?>><?php echo $store_row['categorydescription']; ?></option>
                <?php  } ?>
              </select>
            </td>
            <td align="right">Item Name</td>
            <td><input type="text" name="part_name" id="part_name" value="<?php echo $_REQUEST['part_name']; ?>" onkeyup="queueAddStockSearch();" /></td>
          </tr>
          <tr class="row1">
            <td align="right">Item Code</td>
            <td><input type="text" name="part_code" id="part_code" value="<?php echo $_REQUEST['part_code']; ?>" onkeyup="queueAddStockSearch();" /></td>
            <td colspan="4"></td>
          </tr>
          <tr class="row1">
            <td style="text-align:center;" colspan="6"><input name="search" class="search" value="Search" type="submit" />
              <input class="search" type="button" value="Save" id="save" onclick="return check_selectedItem();">
            </td>
          </tr>
        </table>
      </form>


      <?php
      ?>
      <br>
      <div id="addStockResults"><?php echo renderAddStockResults($_REQUEST, $main_store, isset($get_store_id) ? $get_store_id : '', $db); ?></div>
    </div>
  </div>
</div>
<script>
  function chkdteformat(obj, id) {
    var pattern = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
    var currID = obj.id;
    var data = currID.split('_');
    if (document.getElementById("mfg_" + data[1]).value > document.getElementById("expiry_" + data[1]).value && document.getElementById("expiry_" + data[1]).value !== '') {
      alert("Expiry Date cannot less than Manufacturing Date");
      document.getElementById("expiry_" + data[1]).value = "";
    }
    // var input=document.getElementById(currID).value;
    // alert(input);
    if (!pattern.test(input)) {

      alert("Date should be in dd/mm/yyyy Format");
      document.getElementById(currID).value = "";
    }

  }

  function addRow(obj, id) {

    //var table = document.getElementById('tableDataProduction');
    var rowCount = parseInt(document.getElementById('row_count').value) + 1;
    /*var rowCount = table.rows.length;    
    if(rowCount == 1)
    {
    	count = 1
    }
    else {
    	count = rowCount;
    }*/
    var data = id.split('_');
    var thisRow = $(obj).closest('tr')[0];
    var cloneData = $(thisRow).clone().insertAfter(thisRow);

    cloneData.find('td').each(function() {
      var el = $(this).children();
      //console.log(el);
      var id = el.attr('id') || null;
      if (id) {
        var idArr = id.split("_");
        //var k=$(obj).closest('table').find('tr');
        //k=k.length;
        var newId = '';
        if (idArr.length > 2) {

          newId = idArr[0] + '_' + idArr[1];
        } else {
          newId = idArr[0];
        }


        el.attr('id', newId + ('_' + rowCount));
        if ($('#' + newId + ('_' + rowCount)).attr('type') == 'text') {

          if (newId == 'unit') {

          } else {
            el.attr('value', '');
          }
        }
        //cloneData.find('td').eq(2).html("");
        //console.log($('#'+idArr[0]+('_'+rowCount)).attr('type'));
        $('.datepicker').removeClass('hasDatepicker').datepicker({
          dateFormat: 'dd/mm/yy',
          changeMonth: true,
          changeYear: true,
          yearRange: '-80:+20'
        });
      }
    });
    document.getElementById('row_count').value = rowCount;





  }
  // function addBatch(obj,id)
  // {

  // 	var data1=id.split("_");
  //     var thisRow = $(obj).closest( 'tr' )[0];
  //     $( thisRow ).clone().insertBefore( thisRow ).find( 'input:text' );

  //     // var qty=$(obj).closest('tr').find('input[id=qtyasperbill_'+data1[1]+']').val();

  //     //  var pen=$(obj).closest('tr').find('input[id=pending1_'+data1[1]+']').val();


  //       /* -------------- Code for add button to remove duplicacy of po Quantity Starts here-------------------------------------------------------  */
  //       var j=parseInt(data1[1]+1);

  //      $(obj).closest('tr').find('input[id=add_'+data1[1]+']').hide();
  //      //$(obj).closest('tr').find('input[id=itemcode_'+data1[1]+']').hide();
  //      $(obj).closest('tr').find('input[id=itemname_'+data1[1]+']').hide('');
  //      $(obj).closest('tr').find('input[id=batch_'+data1[1]+']').val('');


  //      //$(obj).closest('tr').find('input[id=pending_'+data1[1]+']').hide();

  //      $(obj).closest('tr').find('input[id=mfg_'+data1[1]+']').val('').addClass("datepicker");
  //      $(obj).closest('tr').find('input[id=expiry_'+data1[1]+']').val('').addClass("datepicker");
  //      $(obj).closest('tr').find('input[id=stock_'+data1[1]+']').val('');
  //      $(obj).closest('tr').find('input[id=rate_'+data1[1]+']').val('');
  //      $(obj).closest('tr').find('input[id=amount_'+data1[1]+']').attr('id','amount_'+j).val('');
  //      // $(obj).closest('tr').find('input[id=reciveqty2_'+data1[1]+']').val('');
  //      // $(obj).closest('tr').find('input[id=minSign_'+data1[1]+']').val('');
  //      // $(obj).closest('tr').find('input[id=shortaccessid_'+data1[1]+']').val('');

  //   /* -------------- Code for add button to remove duplicacy of po Quantity Ends here -------------------------------------------------------  */


  //     //var countqty=countPendingQty();
  //     //alert(pen);
  //     // if(countqty>parseFloat(pen))
  //     // {

  //     //     $(obj).closest('tr').find('input[id=qtyasperbill_'+data1[1]+']').val(0);
  //     //     qty=0;
  //     //      //var countqty=countPendingQty();
  //     // }


  //     //var shortDirect=document.getElementById('shortDirect').value;
  //     //alert(qty+" "+shortDirect);
  //     // if(qty=="")
  //     //     qty=0;
  //     // if(shortDirect=="")
  //     //     shortDirect=0;
  //     // var total=parseFloat(qty)+parseFloat(shortDirect);
  //     // document.getElementById('shortDirect').value=total.toFixed();
  //     //  var secqty=$(obj).closest('tr').find('input[id=reciveqty2_'+data1[1]+']').val();
  //     // var shortDirect1=document.getElementById('short1Direct').value;

  //     //  if(secqty=="")
  //     //     secqty=0;
  //     // if(shortDirect1=="")
  //     //     shortDirect1=0;
  //     // var total1=parseFloat(secqty)+parseFloat(shortDirect1);

  //     // document.getElementById('short1Direct').value=parseFloat(total1.toFixed(2));
  // 	var i=parseInt(data1[1]+1);
  //     $(obj).closest('tr').find('input[id=mfg_'+data1[1]+']').attr('id','mfg_'+i);
  //     $(obj).closest('tr').find('input[id=expiry_'+data1[1]+']').attr('id','expiry_'+i);
  //     $('.datepicker').removeClass('hasDatepicker').datepicker({ 

  //     	dateFormat: 'dd/mm/yy',changeMonth: true, changeYear: true,yearRange: '-80:+20'});
  // }

  function checkitemdate(str) {

    var id = str.id.split("_");
    var val = str.value.split("/");
    var req_date1 = document.getElementById("mfg_" + id[1]).value.split("/");
    var val1 = val[2] + "-" + val[1] + "-" + val[0];
    var req_date = req_date1[2] + "-" + req_date1[1] + "-" + req_date1[0];
    if (Date.parse(val1) < Date.parse(req_date) || req_date == "undefined-undefined-") {
      if (id[1] == undefined) {
        alert("Material Required Date must be greater or equal to Requisition Date");
        document.getElementById(id[0]).value = "";
        var exp = document.getElementById(id[0]).focus();
        alert(exp.innerHTML);
      } else {
        alert("Expiry Date must be greater  than Manufacturing Date");
        document.getElementById(id[0] + "_" + id[1]).value = "";
        var ex = document.getElementById(id[0] + "_" + id[1]).focus();
        alert(ex.innerHTML);
      }
    }
  }

  function checkfuturedate(dt) {

    var d = new Date();
    var day = d.getDate();
    if (day < 9 && day > 0) {
      day = "0" + day;
    }
    var mon = d.getMonth();
    var month = mon + 1;
    var year = d.getFullYear();
    var dateformat = year + "-" + month + "-" + day;
    var get = dt.split("/");
    var get1 = get[2] + "-" + get[1] + "-" + get[0];


    if (Date.parse(get1) > Date.parse(dateformat) || get1 == "undefined-undefined-") {
      alert("Manufacturing Date should not be future date.");
      mfg = document.getElementById("mfg_" + i).value = "";

      var mf = document.getElementById("mfg_" + i).focus();

      alert(mf.innerHTML);
    }
  }

  function delete_row() {
    //var result = confirm("Are you sure? Delete row?");
    //if (result = true) {
    $(this).closest('tr').remove();
    // }
    // else
    // {
    // result="cancel";	
    // }
  }


  function checkBatch(batch, id) {
    if (batch == "") {
      var batch = "N/A";
    }
    var idk = id.split('_');
    var i = idk[1];
    if ($('#site').val() == "") {
      alert("Please Select Branch First");
      document.getElementById("site").focus();
      document.getElementById("batch_" + i).value = "";
      return false;
    }
    var site = $('#site').val();
    if ($('#store').val() == "") {
      alert("Please Select Store First");
      document.getElementById("store").focus();
      document.getElementById("batch_" + i).value = "";
      return false;
    }
    if (document.getElementById("rowid_" + i).checked == true) {

      var store = $('#store').val();
      var item_id = document.getElementById("rowid_" + i).value;
      if (item_id != '') {
        $.post("GoDownByBranch.php", {
          "checkbatch": 'yes',
          'site': site,
          'store': store,
          'item': item_id,
          "batch": batch
        }, function(data) {
          if (data == 0) {
            alert('Duplicate Value!');
            $('#batch_' + i).val('');
            $('#batch_' + i).focus();

          }

        });

      }
    } else {
      alert('Please select an Item Code');
      document.getElementById("batch_" + i).value = "";
      return false;
    }
  }

  function checkstock(obj, id) {

    var rowcount = document.getElementById("row_count").value;
    var rowid = rowcount++;
    var idk = id.split('_');
    if (idk[1] == rowid) {
      var i = idk[1];
      var flag = 1;
    } else {
      var i = idk[1];
      var flag = 1;
    }
    if (flag) {
      if ($('#site').val() == "") {
        alert("Please Select Branch First");
        document.getElementById("site").focus();
        document.getElementById("batch_" + i).value = "";
        return false;
      }
      var site = $('#site').val();
      if ($('#store').val() == "") {
        alert("Please Select Store First");
        document.getElementById("store").focus();
        document.getElementById("batch_" + i).value = "";
        return false;
      }
      if (document.getElementById("rowid_" + i).checked == true) {
        var store = $('#store').val();
        var row_id = document.getElementById("rowid_" + i).value;
        if (row_id != '') {
          $.post("GoDownByBranch.php", {
            "checkstock": 'yes',
            'site': site,
            'store': store,
            'item': row_id
          }, function(data) {

            if (data == 0) {

              alert('Opening Stock has been Already Added!');
              $('#stock_' + i).prop("disabled", true);
              $('#stock_' + i).val('');
              $('#stock_' + i).focus();
              $('#rowid_' + i).prop("checked", false);

              // document.getElementById('stock_'+i).disabled = true;
              // var vq = document.getElementById("stock_'+i").value="";
              // var vq = document.getElementById("stock_'+i").focus();
              // //alert(vq.innerHTML);
              return false;
            } else {

            }
          });
        }
      }
    } else {
      alert('Please select an Item Code');
      document.getElementById("batch_" + i).value = "";
      return false;
    }
  }

  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 changeAmount(val, op, id) {

    var ids = id.split("_");

    //alert(val+" "+op+"  "+ids[1]);

    if (op == 'qty') {

      var rate = document.getElementById('rate_' + ids[1]).value;
      var total = parseFloat(rate) * parseFloat(val);
      if (!isNaN(total))
        document.getElementById('amount_' + ids[1]).value = total;
    }
    if (op == 'rate') {

      var qty = document.getElementById('stock_' + ids[1]).value;
      var total = parseFloat(qty) * parseFloat(val);
      if (!isNaN(total))
        document.getElementById('amount_' + ids[1]).value = total;
    }
  }

  function validate() {
    if (document.getElementById("site").value == '0') {
      alert("Must Select Branch Name");
      document.getElementById("site").focus();
      return false;
    }
    if (document.getElementById("itemcode").value == '') {
      alert("Must Select Item Name");
      document.getElementById("itemcode").focus();
      return false;
    }
    if (document.getElementById("stock").value == '') {
      alert("Must Enter Opening Qty");
      document.getElementById("stock").focus();
      return false;
    }
    if (document.getElementById("rate").value == '') {
      document.getElementById("rate").focus();
      alert("Must Enter Item Rate");
      return false;
    }
    return true;
  }

  function open_items() {
    /*window.open('opening_items.php','targetWindow','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes, width=1000,height=500');*/
    $('#opening_stock').fadeIn('slow');

    /*$.post('opening_items.php',{},function(data){

    	$('.opening_items').html(data);
    	
    	$('.opening_items').fadeIn('slow');
    });*/
  }

  function showStore(id) {
    $.post('GoDownByBranch.php', {
      'site': id
    }, function(data) {
      $('#hid-Godown-div').html(data);
    });
  }

  function searchItems() {
    var category = $('#category').val();
    var subcategory = $('#subcategory').val();
    var part_name = $('#part_name').val();
    var part_code = $('#part_code').val();

    /*alert("category = "+category+" subcategory = "+subcategory+" part_name = "+part_name+" part_code = "+part_code);
    return false;*/
    if (category == '0') {
      alert('Please select Stock Category');
      return false;
    } else {
      $.post('getItemsBycategory.php', {
        'category': category,
        'subcategory': subcategory,
        'part_name': part_name,
        'part_code': part_code,
        'searchItems': 'yes'
      }, function(data) {
        $('#ItemListDiv').html(data);
      });
    }
  }


  function getdata1(str) {
    if (str == "") {
      document.getElementById("hiddiv").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("hiddiv").innerHTML = xmlhttp.responseText;
      }
    }

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

  function ExitWindow() {
    opener.window.location = "index.php?route=Inventory/transation/material_receipt_note_add&modid=<?php echo $_REQUEST['modid']; ?>&frmid=<?php echo $_REQUEST['frmid']; ?>&type=Direct";
    self.close();
  }

  function check_selectedItem() {
    var result = 0;
    var countItem = document.getElementById("row_count").value;
    for (var j = 0; j < countItem; j++) {
      if (document.getElementById("rowid_" + j).checked == true) {
        var countflag = 1;
        break;
      } else {
        var countflag = 0;
      }
    }
    if (countflag == 0) {
      alert("Please select an Item Code");
      return false;
    } else {
      var site = $('#site').val();
      var store = $('#store').val();
      var reveive_date = $('#reveive_date').val();
      if (site == "") {
        alert("Please select branch");
        return false;
      }
      if (store == "0") {
        alert("Please select store");
        return false;
      }
      if (reveive_date == "") {
        alert("Please select recieve date");
        return false;
      }
    }
    $("input[type='checkbox']:checked").each(function() {
      obj = $(this);
      var id = obj.attr('id');
      var ids = id.split('_');
      var rowcount = document.getElementById("row_count").value;
      var rowid = rowcount++;
      if (ids[1] == rowid) {
        i = ids[1];
        var flag = 1;
      } else {
        i = ids[1];
        var flag = 1;
      }
      if (flag) {
        var site = document.getElementById("site").value;
        var store = document.getElementById("store").value;
        var item = document.getElementById("rowid_" + i).value;
        var unit = document.getElementById("unit_" + i).value;
        var reveive_date = document.getElementById("reveive_date").value;
        var stock = document.getElementById("stock_" + i).value;
        var rate = document.getElementById("rate_" + i).value;
        var amount = document.getElementById("amount_" + i).value;
        var batch = document.getElementById("batch_" + i).value;
        var expiry = document.getElementById("expiry_" + i).value;
        var item_id = document.getElementById("rowid_" + i).value;
        var mfg = document.getElementById("mfg_" + i).value;
        jQuery('input[id^=batch_]').each(function() {
          var batch;
          var checkBatch = document.getElementById("data-batch_" + i).value;
          var ids = jQuery(this).attr('id');
          if (checkBatch == 'Y' && document.getElementById("batch_" + i).value == "") {
            alert('batch Qty cannot be empty');
            var vq = document.getElementById("batch_" + i).focus();
            alert(vq.innerHTML);
            return false;
          }
          if (document.getElementById("mfg_" + i).value == '0' || document.getElementById("mfg_" + i).value == '') {
            alert('Manufacturing Date cannot be empty');
            var vq = document.getElementById("mfg_" + i).focus();
            alert(vq.innerHTML);
            return false;
          }
          if (document.getElementById("expiry_" + i).value == '0' || document.getElementById("expiry_" + i).value == '') {
            alert('Expiry Date cannot be empty');
            var vq = document.getElementById("expiry_" + i).focus();
            alert(vq.innerHTML);
            return false;
          }
          if (document.getElementById("stock_" + i).value == '0' || document.getElementById("stock_" + i).value == '') {
            alert('Stock Qty cannot be empty');
            var vq = document.getElementById("stock_" + i).focus();
            alert(vq.innerHTML);
            return false;
          }
          if (document.getElementById("rate_" + i).value == '0' || document.getElementById("rate_" + i).value == '') {
            alert('Mrp Qty cannot be empty');
            var vq = document.getElementById("rate_" + i).focus();
            alert(vq.innerHTML);
            return false;
          }
        });
      }
      if (item != '') {
        $.post("GoDownByBranchnew.php", {
          "additem": 'yes',
          'site': site,
          'store': store,
          'reveive_date': reveive_date,
          'item': item,
          'stock': stock,
          'rate': rate,
          "amount": amount,
          "batch": batch,
          "expiry": expiry,
          "item_id": item_id,
          "mfg": mfg
        }, function(data) {
          if (parseInt(data) == 0) {
            document.getElementById("res").value = 0;
          }

        });
      }
    });
    if (document.getElementById("res").value == 0) {
      alert('Opening stock has been added');
      window.location.reload();
    }
  }
</script>
