<?php
$cs = Yii::app()->getClientScript();
$baseUrl = Yii::app()->baseUrl;
?>
<div id="stockhelper" style='display:none;' ></div>
<div id ="div_service_item_details">
    <div class="table-responsive" style="max-height:500px">
        <table class="table table-hover table-bordered personal-task" id="order_item_table">
            <tr>
                <th style="width:2%">No</th>
                <th style="width:17%">Item</th>
                <th style="width:30%">Description</th>
                <th style="width:5%">Quantity</th>
                <th style="width:10%">Unit</th>
                <th style="width:5%">Rate</th>
                <th>Tax(%)</th>
                <!--th style="width:5%">Tolerance</th-->
                <th style="width:10%">Exp Dy. Date</th>
                <th style="width:5%">Amount</th>

                <th class="text-center" style="width:10%">
                    <a class="btn btn-xs btn-theme " href="#" onclick="addOrderRow($('#order_item_table'));"><i class="fa fa-plus"></i></a></th>
            </tr>
            <?php
            $total_cubic_meter = 0;
            $total_weight = 0;
            foreach ($modelOrderStockItem as $i => $modelOrder) {

                $table_row_class = "orderItemTable_" . $i;

                $modelOrder->cubic_meter = "";
                if ((float) $modelOrder->product->height > 0) {
                    $modelOrder->cubic_meter = $modelOrder->product->height;
                }

                if ((float) $modelOrder->product->width > 0) {
                    if (!empty($modelOrder->cubic_meter)) {
                        $modelOrder->cubic_meter = $modelOrder->cubic_meter * $modelOrder->product->width;
                    } else {
                        $modelOrder->cubic_meter = $modelOrder->product->width;
                    }
                }

                if ((float) $modelOrder->product->length > 0) {
                    if (!empty($modelOrder->cubic_meter)) {
                        $modelOrder->cubic_meter = $modelOrder->cubic_meter * $modelOrder->product->length;
                    } else {
                        $modelOrder->cubic_meter = $modelOrder->product->length;
                    }
                }

                $modelOrder->weight = $modelOrder->product->weight;

                if ((int) $modelOrder->stock_item_id > 0) {

                    if (!empty($modelOrder->cubic_meter)) {
                        $total_cubic_meter += ($modelOrder->cubic_meter * $modelOrder->stock_item_quantity);
                    }

                    if (!empty($modelOrder->product->weight)) {
                        $total_weight += ($modelOrder->weight * $modelOrder->stock_item_quantity);
                    }
                }
                ?>
                <tr class="orderItemTableRow_<?php echo $i; ?> <?php if ($modelOrder->stock_item_rate <= 0 && $modelOrder->id > 0) echo "bg-danger"; ?>" >
                    <?php
                    $value = $modelOrder->product->part_number;

                    if ($modelOrder->product->inventory_item_type == 2 || $modelOrder->product->inventory_item_type == 3) {
                        $value = $modelOrder->product->part_number;
                    }
                    ?>
                    <td>  <label><?php echo ($i + 1); ?> </label></td>
                    <td>
                        <div class="info-block purchase-helper-new-<?php echo $i; ?>">
                            <?php
                            if ($modelOrder->stock_item_name != '') {
                                $stock_item_name = $modelOrder->stock_item_name;
                            } else {
                                $stock_item_name = $modelRequisitionStockItem->stock_item_name;
                            }
                            ?>
                            <?php
                            echo $form->textField($modelOrder, "[" . $i . "]stock_item_name", array('class' => 'tooltipster go', 'value' => $value, 'placeholder' => 'Type & Select',
                                'OnKeypress' => 'js:autoCompleteProduct(this.id,"purchasingorder");', 'title' => 'Select product'));
                            ?>
                            <?php echo $form->hiddenField($modelOrder, "[" . $i . "]stock_item_id"); ?>
                            <?php echo $form->error($modelOrder, "[" . $i . "]stock_item_id"); ?>
                            <?php echo $form->hiddenField($modelOrder, "[" . $i . "]id"); ?>
                            <?php echo $form->hiddenField($modelOrder, "[" . $i . "]cubic_meter"); ?>
                            <?php echo $form->hiddenField($modelOrder, "[" . $i . "]weight"); ?>

                            <span class="info-btn" onclick="$('.info-table').hide();loadTable(this.id);" id="PurchasingOrderStockItem_<?php echo $i; ?>_helper" title="Previous Orders"><i class="fa fa-info-circle" aria-hidden="true"></i></span>
                            <div class="info-table" id="PurchasingOrderStockItem_<?php echo $i; ?>_mini_table">
                                <span class="info-table-close" onclick="$('.info-table').hide()">
                                    <i class="fa fa-times-circle" aria-hidden="true"></i>
                                </span>
                                <div class="temp_div" id="data_of_<?php echo $i; ?>">

                                </div>
                            </div>

                        </div>
                        <?php //echo CHtml::link('<i class="fa fa-info-circle"><div class="triangle-right"></div></i>', 'javascript:;', array('class' => 'purchase-helper-trigger', 'title' => 'Purchase Helper','id'=>"purchase_".$i,'onclick' => 'showpurchase(this,this.id)'));  ?>
                        <?php //echo CHtml::link('<i class="fa fa-shopping-cart "><div class="triangle-right"></div></i>', 'javascript:;', array('class' => 'stock-helper-trigger', 'title' => 'Stock Helper','id'=>"stockhlp_".$i,'onclick' => 'showstockdetails(this,this.id)'));   ?>

                    </td>
                    <td>
                        <?php
                        if ($modelOrder->stock_item_description != '') {
                            $stock_item_name = $modelOrder->stock_item_description;
                        } else {
                            $stock_item_name = $modelRequisitionStockItem->stock_item_description;
                        }
                        ?>
                        <?php echo $form->textArea($modelOrder, "[" . $i . "]stock_item_description", array('class' => 'tooltipster desc go en-text-area', 'title' => 'Add Description here', 'readonly' => false)); ?>
                        <?php echo $form->error($modelOrder, "[" . $i . "]stock_item_description"); ?>
                    </td>
                    <td>
                        <?php
                        if ($modelOrder->stock_item_quantity != '') {
                            $stock_item_name = $modelOrder->stock_item_quantity;
                        } else {
                            $stock_item_name = $modelRequisitionStockItem->stock_item_quantity;
                        }
                        ?>
                        <?php
                        $modelOrder->stock_item_quantity = number_format($modelOrder->stock_item_quantity, 2, ".", "");

                        echo $form->textField($modelOrder, "[" . $i . "]stock_item_quantity", array('class' => 'qty go cell-center text-right', 'style' => 'width:83px;', 'onkeypress' => 'return isPositiveNumber(event)', 'onkeyup' => 'calculatestockValues($("#order_item_table"),this.id);getmaxVal(this.id,this.value,1);'));
                        ?>
                        <?php echo $form->error($modelOrder, "[" . $i . "]stock_item_quantity"); ?> </td>
                    <td id="unit_<?php echo $i; ?>">
                        <?php
                        ($modelOrder->stock_item_id > 0) ? $data = UnitOfMeasurement::getUnits($modelOrder->stock_item_id) : $data = array();
                        ?>
                        <?php echo $form->dropdownlist($modelOrder, "[" . $i . "]stock_item_unit", $data, array('class' => 'qty go')); ?>
                    </td>
                    <td>
                        <?php
                        $modelOrder->stock_item_rate = number_format($modelOrder->stock_item_rate, 2, ".", "");
                        echo $form->textField($modelOrder, "[" . $i . "]stock_item_rate", array('class' => 'qty go cell-center text-right', 'style' => 'width:83px;', 'onkeypress' => 'return isPositiveNumber(event)', 'onkeyup' => 'calculatestockValues($("#order_item_table"),this.id);'));
                        ?>
                        <?php echo $form->error($modelOrder, "[" . $i . "]stock_item_rate"); ?>
                    </td>
                    <td>
                        <?php
                        if ($modelOrder->stock_item_id > 0) {
                            $modelOrder->tax_percentage = $modelOrder->product->tax->percentage;
                            $modelOrder->tax_amount = ($modelOrder->stock_item_amount * $modelOrder->product->tax->percentage) / 100;
                        }
                        ?>
                        <?php echo $form->textField($modelOrder, "[" . $i . "]tax_percentage", array('class' => 'rate go text-right', 'onkeypress' => 'return isNumberKey(event)', 'readonly' => 'readonly')); ?>
                        <?php echo $form->hiddenField($modelOrder, "[" . $i . "]tax_amount"); ?>
                        <input type="hidden" id="check_tax_purchaseOrder_<?php echo $i; ?>" value="<?php echo $modelOrder->product->tax->percentage; ?>" />
                    </td>
                    <!--td>
                    <?php //echo $form->textField($modelOrder, "[" . $i . "]stock_item_tolerance", array('class' => 'qty go','onkeyup' => 'getmaxVal(this.id,this.value,2);'));  ?>
                    <?php //echo $form->hiddenField($modelOrder, "[" . $i . "]stock_item_max_qty");  ?>
                   </td-->
                    <td>
                        <?php
                        if ($modelOrder->id > 0) {
                            if ($modelOrder->expected_delivery_date != '0000-00-00')
                                $modelOrder->expected_delivery_date = date("d/m/Y", strtotime($modelOrder->expected_delivery_date));
                            else
                                $modelOrder->expected_delivery_date = '';
                        } else {
                            $modelOrder->expected_delivery_date = date('d/m/Y', strtotime('+5 days'));
                        }
                        ?>
                        <?php echo $form->textField($modelOrder, "[" . $i . "]expected_delivery_date", array('class' => 'datepicker go', 'onclick' => 'start_date(this.id);')); ?>
                    </td>
                    <td width="10">
                        <?php
                        echo $form->textField($modelOrder, "[" . $i . "]stock_item_amount", array('class' => 'qty go cell-center text-right', 'style' => 'width:83px;', 'readonly' => true));
                        //,'onkeypress' => 'return isPositiveNumber(event)','onKeyup'=>'validate1(this.id);'--commented by jisha on 11-5-22
                        ?>
                        <?php $stocktotal += $modelOrder->stock_item_amount; ?>
                    </td>

                    <td class="text-center nw" width="1%">
                        <?php //echo CHtml::link('<i class="fa fa-arrow-up"></i>', 'javascript:void(0);', array('class' => 'up btn btn-primary btn-xs', 'title' => 'Move to Up')); ?>
                        <?php //echo CHtml::link('<i class="fa fa-arrow-down"></i>', 'javascript:void(0);', array('class' => 'down btn btn-primary btn-xs', 'title' => 'Move to Down')); ?>
                        <?php echo CHtml::link('<i class="fa fa-times"></i>', 'javascript:void(0);', array('class' => 'btn btn-xs btn-danger', 'onclick' => 'removeTable($(\'#order_item_table\'),this,this.id)', 'title' => 'Remove this item', 'id' => 'order_' . $i)); ?>
                    </td>
                </tr>
                <?php
                $total_tax_amt += $modelOrder->tax_amount;
            }
            ?>
        </table>
        <?php
        if ((float) $total_cubic_meter > 0) {
            $str_cubic_meter_per_weight = 'Total CBM: ' . number_format($total_cubic_meter, 2) . ' m<sup>3</sup> / weight: ' . number_format($total_weight, 2) . ' kg';
        } else {
            $str_cubic_meter_per_weight = 'Total CBM: 0.00 m<sup>3</sup> / weight: ' . number_format($total_weight, 2) . ' kg';
        }
        ?>
        <table class="table table-hover table-bordered table-nexted order_total">
            <tr class="bg-total" style="display:none;">

                <td width="20%" class="text-left table_total_title">
                    <h2><span id="span_total_cubic_meter"><?php echo $str_cubic_meter_per_weight; ?></span></h2>
                </td>
                <td width="50%" class="text-right table_total_title">
                    <h2>Total</h2>
                </td>
                <td width="30%" class="text-right table_total">
                    <h2 class="total" class="text-right"><?php echo Yii::app()->numberFormatter->formatCurrency($stocktotal, " "); ?></h2>
                </td>
            </tr>
        </table>
        <?php
        $stockgrand_total = $stocktotal;

        //$stockgrand_total+=$total_tax_amt;
        ?>
        <!--<table id="order_final_add_table" class="table table-hover table-bordered table-nexted">
        <?php /* foreach($modelOrderAdditions as $i => $modelOrderAdditions): ?>
          <tr>
          <td class="text-right td-in-6">
          Additions
          <a class="btn btn-xs btn-theme " href="javascript:void(0);" onclick="addOrderRow($('#order_final_add_table'));"><i class="fa fa-plus"></i></a>
          </td>
          <td class="td-in-6">
          <?php echo $form->dropDownList($modelOrderAdditions, "[" . $i . "]particular",MasFooterItems::getPurchaseAdditions(),array('class' => 'go','data-label'=>'Particulars','empty'=>'Select'));?>
          <?php echo $form->hiddenField($modelOrderAdditions, "[" . $i . "]id");?>
          </td>
          <td>
          <?php echo $form->textField($modelOrderAdditions, "[" . $i . "]particular_value", array('onkeyup' => 'calculatestockValues($("#order_item_table"),this.id);', 'onkeypress' => 'return isNumberKey(event)', 'class' => 'value_rate go text-right', 'placeholder' => 'value')); ?>
          </td>
          <td>
          <?php echo $form->textField($modelOrderAdditions, "[" . $i . "]calculated_value", array('readonly' => true, 'class' => 'value_rate additions_value go text-right')); ?>
          </td>
          <td width="0">
          <?php echo CHtml::link('<i class="fa fa-times"></i>', 'javascript:void(0);', array('class'=>'btn btn-xs btn-danger','onclick' => 'removeExtrasRow($("#order_final_add_table"), this)')); ?>
          </td>
          <?php $stockgrand_total +=$modelOrderAdditions->calculated_value; ?>
          </tr>
          <?php endforeach; ?>
          </table>
          <table id="order_final_ded_table" class="table table-hover table-bordered  table-nexted">
          <?php  foreach ($modelOrderDeductions as $i => $modelOrderDeductions): ?>
          <tr>
          <td class="text-right td-in-6">
          Deductions
          <a class="btn btn-xs btn-theme " href="javascript:void(0);" onclick="addOrderRow($('#order_final_ded_table'));"><i class="fa fa-plus"></i></a>
          </td>
          <td class="td-in-6">
          <?php echo $form->dropDownList($modelOrderDeductions, "[" . $i . "]particular",MasFooterItems::getPurchaseDeductions(),array('class' => 'go','data-label'=>'Particulars','empty'=>'Select'));?>
          <?php echo $form->hiddenField($modelOrderDeductions, "[" . $i . "]id");?>
          </td>
          <td>
          <?php echo $form->textField($modelOrderDeductions, "[" . $i . "]particular_value", array('onkeyup' => 'calculatestockValues($("#order_item_table"),this.id);', 'onkeypress' => 'return isNumberKey(event)', 'class' => 'value_rate go text-right', 'placeholder' => 'value')); ?>
          </td>
          <td>
          <?php echo $form->textField($modelOrderDeductions, "[" . $i . "]calculated_value", array('readonly' => true, 'class' => 'value_rate deductions_value go text-right')); ?>
          </td>
          <td width="0">
          <?php echo CHtml::link('<i class="fa fa-times"></i>', 'javascript:void(0);', array('class'=>'btn btn-xs btn-danger','onclick' => 'removeExtrasRow($("#order_final_ded_table"), this)')); ?>
          </td>
          <?php $stockgrand_total -=$modelOrderDeductions->calculated_value; ?>
          </tr>
          <?php endforeach; */ ?>
    </table>-->

        <table class="table table-hover table-bordered table-nexted order_grand_total">

            <tr class="summary_tr bg-total">
                <td width="70%" class="text-right table_total_title"><h1>VAT</h1></td>
                <td width="30%" class="table_total">
                    <h1 class="vattotal text-right"> <?php echo Yii::app()->numberFormatter->formatCurrency($total_tax_amt, " "); ?></h1>
                </td>
            </tr>
            <tr class="summary_tr bg-total">
                <td width="70%" class="text-right table_total_title">
                    <h1>Grand Total</h1></td>
                <td width="30%" class="text-right table_total">
                    <h1 class="grandtotal" class="text-right">
                        <?php echo Yii::app()->numberFormatter->formatCurrency($stockgrand_total, " "); ?>
                    </h1></td>
            </tr>
        </table>
    </div>
</div>
<script>
</script>

<?php
$cs = Yii::app()->getClientScript();
$baseUrl = Yii::app()->baseUrl;
$cs->registerScript("start_date", "function start_date(id){

        var date_value = $('#PurchasingOrder_order_date').val().split('/');
        var current = new Date(date_value[2], date_value[1] - 1, date_value[0]);

        var exp_date1 = $('#PurchasingOrder_required_date').val().split('/');
        var current_21 = new Date(exp_date1[2], exp_date1[1] - 1, exp_date1[0]);


};", CClientScript::POS_HEAD);
?>
<?php
$cs = Yii::app()->getClientScript();
$cs->registerScript("autoCompleteProduct", "function autoCompleteProduct(field_id,frm)
        {
        var arr_fields= field_id.split('_');
        var model_name   = arr_fields[0];
        var row_field  = arr_fields[1];

        var rows = $('#order_item_table').find('tr:gt(0)').length;
        var vendor_id = $('#PurchasingOrder_vendor_id').val();
        var product_ids = [];
        var i=0;

        for(i=0; i<rows ; i++){
            if($('#PurchasingOrderStockItem_'+i+'_stock_item_id').val() > 0)
                product_ids.push($('#PurchasingOrderStockItem_'+i+'_stock_item_id').val());
        }

        $('#PurchasingOrderStockItem_'+row_field+'_stock_item_id').val('');
        var url = '" . Yii::app()->createUrl('purchasingorder/GetAllProducts') . "'+'&frm='+frm+'&vendor_id='+vendor_id+'&products='+product_ids.toString();
                $('#'+field_id).autocomplete({
                minLength   : 1,
                source      : function (request, response) { autoCompleteSource(request, response,url) },
                focus       : function( event, ui ) { $(this).val((ui.item.label)); return false;},
                select          : function( event, ui ) {
                event.preventDefault();
                trigger_target_id   =   $(event.target).attr('id');
                                    var product_id = desc = part_numbr = unit_id = unit_name =rate= '';
                                    product_id=ui.item.value;
                                    desc=ui.item.description;
                                    part_numbr=ui.item.part_number;
                                    unit_id=ui.item.unit_id;
                                    unit_name=ui.item.unit_name;
                                    cubic_meter = ui.item.cubicmeter;
                                    weight=ui.item.other;
                                    rate =ui.item.rate;
                                    var tax_percentage = 0;
                                    if(ui.item.tax_code != null){
                                        tax_percentage = ui.item.tax_code.percentage;
                                    }


                                var quantity='1';
                                $('#PurchasingOrderStockItem_'+row_field+'_stock_item_description').val(desc);
                                $('#PurchasingOrderStockItem_'+row_field+'_stock_item_name').val(part_numbr);
                                $('#PurchasingOrderStockItem_'+row_field+'_unit_id').val(unit_id); //for showing hidden field
                                $('#PurchasingOrderStockItem_'+row_field+'_stock_item_unit').val(unit_name); //FOR SHOWING UNIT NAME
                                $('#PurchasingOrderStockItem_'+row_field+'_stock_item_id').val(product_id);
                                $('#PurchasingOrderStockItem_'+row_field+'_stock_item_quantity').val(quantity);
                                $('#PurchasingOrderStockItem_'+row_field+'_cubic_meter').val(cubic_meter);
                                $('#PurchasingOrderStockItem_'+row_field+'_weight').val(weight);
                                $('#PurchasingOrderStockItem_'+row_field+'_stock_item_rate').val(rate);
                                $('#info_button_'+row_field).show();
                                if(product_id > 0){
                                         jQuery.ajax({
                                            'type': 'post',
                                            'dataType': 'json',
                                            'url': '" . Yii::app()->createUrl('Purchasingorder/getunitdrop') . "',
                                            'data': {'row_field' : row_field, 'product_id' : product_id},
                                            'cache': false,
                                            'success': function(data) {
                                                $('#unit_'+row_field).html(data.drop);
                                                return false;
                                            }
                                        });
                                }
                                var PurchaseOrder_invoice_type  = $('#PurchasingOrder_invoice_type').val();

                                if(PurchaseOrder_invoice_type>0){

                                        jQuery.ajax({
                                                'dataType' : 'json',
                                              'type'  : 'post',
                                              'data'  : 'id='+PurchaseOrder_invoice_type,
                                              'url'  : $('#liveSite').val()+'index.php?r=masinvoicetype/getInvoiceTypeTax',
                                              'cache': false,
                                              'success':function(data){

                                                if(data.status=='success'){
                                                    if(data.tax == 'Y'){

                                                        $('#PurchasingOrderStockItem_'+row_field+'_tax_percentage').val(tax_percentage);
                                                        $('#check_tax_purchaseOrder_'+row_field).val(tax_percentage);
                                                    }
                                                    else{
                                                        $('#PurchasingOrderStockItem_'+row_field+'_tax_percentage').val(0);
                                                       $('#check_tax_purchaseOrder_'+row_field).val(tax_percentage);
                                                    }

                                                }
                                                calculatestockValues($('#order_item_table'));
                                               }
                                            });

                                    }
                            }
            })
        }", CClientScript::POS_HEAD);
?>
<?php
$cs = Yii::app()->getClientScript();

$cs->registerScript("removeTable", " function removeTable(jQtable,evt,field_id) {

            formIdStarter   =   jQtable.attr('id').split(/_(.+)?/)[0];

            var num_rows    =   jQtable.find('tr:gt(0)').length;

            if(num_rows>1){

            var tr  =   $(evt).parent().parent();

            if(isRowEmpty(tr)) {

                amount = $(evt).parents('tr').find('[id$=\"_amount\"]').val();

                total =   $('.'+formIdStarter+'_total .total').text();

                total =   (Number(total)-Number(amount)).toFixed(2);

                $('.'+formIdStarter+'_total .total').text(total)

                gd_total =   $('.'+formIdStarter+'_grand_total .grandtotal').text();

                gd_total =   (Number(gd_total)-Number(amount)).toFixed(2);

                $('.'+formIdStarter+'_grand_total .grandtotal').text(gd_total);

                $(evt).parents('tr').remove();

                var i=0;

                jQtable.find('tr:gt(0)').each(function() { $(this).find('input,select,textarea,.errorMessage').each(function()

                {

                old_id   =   $(this).attr('id');

                new_id   =   old_id.replace(/\d+/,i);

                $(this).attr('id',new_id);

                old_name =   $(this).attr('name');

                if(old_name!==undefined) {

                    new_name =   old_name.replace(/\d+/,i);

                    $(this).attr('name',new_name);} });

                    $(this).find('td:first label').html(++i); }); }

                   calculatestockValues(jQtable,field_id);
                    } else alert('Atleast one item needed here'); }", CClientScript::POS_HEAD
);

/* $cs->registerScript("removeTable1 ", "function removeTable1(jQtable,evt,field_id) {
  var arr_fields= field_id.split('_');
  var row_field=arr_fields[1];

  var row_id       =  $(evt).parents('tr').attr('class');
  var row_id_num   = row_id.match(/\d+/g);
  var id=$('#PurchasingOrderStockItem_'+row_id_num+'_id').val();

  formIdStarter   =   jQtable.attr('id').split(/_(.+)?/)[0];
  var num_rows    =   jQtable.find('tr:gt(0)').length;
  if(num_rows>1){
  var tr  =   $(evt).parent().parent();
  if(isRowEmpty(tr)) {


  var i=0;
  jQtable.find('tr:gt(0)').each(function() { $(this).find('input,textarea,.errorMessage,td,select').each(function()
  {
  old_id   =   $(this).attr('id');
  new_id   =   old_id.replace(/\d+/,i);
  $(this).attr('id',new_id);
  old_name =   $(this).attr('name');
  if(old_name!==undefined) {
  new_name =   old_name.replace(/\d+/,i);
  $(this).attr('name',new_name);
  }

  });
  $(this).find('td:first label').html(++i); });

  $(evt).parents('tr').remove();
  calculatestockValues(jQtable,field_id);



  }else {
  alert('Atleast one item needed here','Alert');
  }
  }
  else {
  alert('Atleast one item needed here','Alert');
  }
  };", CClientScript::POS_HEAD); */
?>
<?php
$cs = Yii::app()->getClientScript();
$cs->registerScript("validate1", "function validate1(field_id){
        var arr_fields= field_id.split('_');
        var row_field=arr_fields[1];
        var id=$('#PurchasingEnquiryStockItem_'+row_field+'_stock_item_quantity').val();
        if($('#PurchasingEnquiryStockItem_'+row_field+'_stock_item_quantity').val()<=0)
        {
            alert('Plse enter valid quantity');
            return false;
         }
        else
        {
         return true;
        }
      };", CClientScript::POS_HEAD);
?>
<?php
$cs->registerScript("calculatestockValues", " function calculatestockValues(jQtable,id) {
        $('.quotation-helper,.purchase-helper,.stock-helper').each(function(){ $(this).hide(); $(this).find('table').remove();});
            formIdStarter   =   jQtable.attr('id').split(/_(.+)?/)[0];
            var count,qty,rate,amount,addition_value,deduction_value,net;
            var other_additions = 0;
            var other_deductions = 0;
            var total   =   0;
            var grand_total =   0;
            var total_tax_amount = 0;
            var total_cubic_meter=0;
            var total_weight=0;
            jQtable.find('tr:gt(0)').each(function() {
                net = 0;
                qty =   $(this).find('[id $=_stock_item_quantity]').val().replace(',','');
                rate =   $(this).find('[id $=_stock_item_rate]').val().replace(',','');
                if(qty==undefined)
                    qty=0;
                if(rate==undefined)
                    rate=0;
                amount  =   (Number(qty)*Number(rate)).toFixed(2);
                net =   (Number(amount)).toFixed(2);
                var cub_m =$(this).find('[id $=_cubic_meter]').val();
                var wght =$(this).find('[id $=_weight]').val();
                if(cub_m==undefined)
                    cub_m=0;
                if(wght==undefined)
                    wght=0;

                if(qty > 0){
                    cubic_meter = Number(cub_m) * Number(qty);
                    weight = Number(wght) * Number(qty);
                }
                else{
                    cubic_meter = 0;
                    weight = 0;
                }

                if(net != 0){
                    total   =   Number(total)+Number(net);
                }
                else{
                    total   =   Number(total);
                }
                if(cubic_meter !=''){
                    total_cubic_meter+=   Number(cubic_meter);
                }
                 if(weight !=''){
                    total_weight+=   Number(weight);
                }
                $(this).find('[id $=_amount]').val(Number(amount).toFixed(2));
                $(this).find('[id $=_addition_amount]').val(Number(addition_value).toFixed(2));
                $(this).find('[id $=_deduction_amount]').val(Number(deduction_value).toFixed(2));
                $(this).find('[id $=_net_amount]').val(Number(net).toFixed(2));

                $(this).find('[id $=_tax_amount]').val(Number(tax_amount).toFixed(2));
                if($(this).find('[id $=_tax_percentage]').length > 0)
                {
                    tax_percentage = $(this).find('[id $=_tax_percentage]').val();
                    var tax_amount = Number(((amount * tax_percentage) / 100)).toFixed(2);
                    $(this).find('[id $=_tax_amount]').val(Number(tax_amount).toFixed(2));
                    total_tax_amount += Number(tax_amount);

                }

            });
            //other_additions    =   calculateExtra($('#'+formIdStarter+'_final_add_table'),total,total_tax_amount);
            //other_deductions  =    calculateExtra($('#'+formIdStarter+'_final_ded_table'),total,total_tax_amount);
            other_additions     =   0.00;
            other_deductions    =   0.00;
            grand_total =   Number(total)   +   Number(other_additions);
            grand_total+=Number(total_tax_amount);
            grand_total -=  Number(other_deductions);
            if(other_deductions > total){
                $('#'+id).val('');
                calculatestockValues(jQtable,id);
            }else{
                $('.'+formIdStarter+'_total .total').html(Number(total).toFixed(2));
                $('.'+formIdStarter+'_grand_total .grandtotal').text(Number(grand_total).toFixed(2));
                $('#grnd_total_id').val(Number(grand_total).toFixed(2));
                $('.vattotal').html(Number(total_tax_amount).toFixed(2));
                if(Number(total_cubic_meter) > 0){
                    $('#span_total_cubic_meter').html('Total CBM: '+Number(total_cubic_meter).toFixed(2)+' m<sup>3</sup> / weight: '+Number(total_weight).toFixed(2)+' kg');
                }
                else{
                    $('#span_total_cubic_meter').html('Total CBM: 0.00 m<sup>3</sup> / weight: '+Number(total_weight).toFixed(2)+' kg');
                }
            }


        }", CClientScript::POS_HEAD);
$cs->registerScript("getmaxVal", " function getmaxVal(field_id,value,frm){
                var arr_field_id = field_id.split('_');
                var row_id   =  arr_field_id[1];
                var max_percentage_value = max_value = 0;
                var stock_qty = $('#PurchasingOrderStockItem_'+row_id+'_stock_item_quantity').val();
                if(frm == 1){
                    value = $('#PurchasingOrderStockItem_'+row_id+'_stock_item_tolerance').val();
                }

                if(stock_qty > 0 && value != ''){

                     count = value.match(/%/g);
                     value   =   value.replace(/%/,'');
                     max_percentage_value = Number(stock_qty) * Number(value/100);
                     if(isNumber(value))
                        max_value  =   (count!=null && count.length>0) ? max_percentage_value : value;
                     $('#PurchasingOrderStockItem_'+row_id+'_stock_item_max_qty').val(Number(stock_qty)+Number(max_value));
                }else{
                    if(value>100){
                        t8.error('Tolerence Should be less than 100');
                        $('#PurchasingOrderStockItem_'+row_id+'_stock_item_tolerance').val('0');
                    }else{
                     t8.error('Enter Quantity!');
                    }
                }

        }", CClientScript::POS_HEAD);
$cs->registerScript("loadTable", "function loadTable(field_id){
                var arr_field_id = field_id.split('_');
                var row_id   =  arr_field_id[1];
                var product_id = $('#PurchasingOrderStockItem_'+row_id+'_stock_item_id').val();
                var vendor_id = $('#PurchasingOrder_vendor_id').val();
                var order_id = $('#PurchasingOrder_id').val();
                $('.temp_div').empty();
                if(vendor_id > 0 && product_id > 0){
                         jQuery.ajax({
                            'data' :{'vendor_id':vendor_id,'product_id':product_id,'order_id' : order_id},
                            'dataType' : 'json',
                            'type':'post',
                            'url': '" . Yii::app()->createUrl('purchasingorder/itemhistory') . "',
                            'success': function(data) {
                                      $('#data_of_'+row_id).html(data.table);
                                       $('#PurchasingOrderStockItem_'+row_id+'_mini_table').show();
                            }
                        });
                }else{
                        if(vendor_id == ''){
                            t8.error('Choose a Vendor!');
                        }
                        if(product_id == ''){
                             t8.error('Choose an Item!');
                        }
                         $('#PurchasingOrderStockItem_'+row_id+'_mini_table').hide();
                         $('.temp_div').empty();
                }
      };", CClientScript::POS_HEAD);
$cs->registerScript("addOrderRow", " function addOrderRow(jQtable) {

                $('.info-table').each(function(){ $(this).hide(); $(this).find('table').remove();});
                formIdStarter   =   jQtable.attr('id').split(/_(.+)?/)[0];
                lastId = jQtable.find('tr:last input:first').attr('id');
                thenum = lastId.match(/\d+/g);
                newId = Number(thenum) + 1;
                var date = $('#PurchasingOrderStockItem_'+thenum+'_expected_delivery_date').val();
                newrow= jQtable.find('tr:last').clone();
                newrow.find('label:first').html(newId+1);
                newrow.attr('class',newId);
                newrow.find('.hasDatepicker').removeClass('hasDatepicker');
                newrow.find('.datetimepicker').siblings().remove();
                newrow.find('.datetimepicker').datetimepicker( 'destroy' );
                newrow.find('div,input,textarea,td,checkbox,select,span,.errorMessage').each(function() {
                this.id= this.id.replace(/\d+/,newId);
                if(!$(this).is(':checkbox'))
                    this.value  = '';
               else
                   $(this).prop('checked', false);

                    (this.name!==undefined) ? this.name= this.name.replace(/\d+/,newId) : this.style  =   '';});

                jQtable.append(newrow);
             $('#PurchasingOrderStockItem_'+newId+'_expected_delivery_date').datetimepicker({format: 'DD/MM/YYYY'}).val(date);
             $('#PurchasingOrderStockItem_'+newId+'_stock_item_tolerance').val(0);


    }", CClientScript::POS_HEAD);

$cs->registerScript("showpurchase", "function showpurchase(evt,field_id) {
        var arr_fields= field_id.split('_');
        var row_field=arr_fields[1];
        var id=$('#PurchasingOrderStockItem_'+row_field+'_stock_item_id').val();
        var company_id=$('#PurchasingOrder_vendor_id').val()
        var order_id = $('#PurchasingOrder_id').val();
        jQuery.ajax({
            'type': 'post',
            'url': '" . Yii::app()->createUrl('purchasingorder/PurchaseHelper') . "',
            'data': {'id':id,'company_id':company_id, 'order_id' : order_id}  ,
            'cache': false,
            'success': function(data) {
                $('#stockhelper').show();
                $('#stockhelper').html(data);
            }
        });
    };", CClientScript::POS_HEAD);
$cs->registerScript("showstockdetails", "function showstockdetails(evt,field_id) {
        var arr_fields= field_id.split('_');
        var row_field=arr_fields[1];
        var id=$('#PurchasingOrderStockItem_'+row_field+'_stock_item_id').val();
        jQuery.ajax({
            'type': 'post',
            'url': '" . Yii::app()->createUrl('inventory/StockHelper') . "',
            'data': {'id':id}  ,
            'cache': false,
            'success': function(data) {
                $('#stockhelper').show();
                $('#stockhelper').html(data);
            }
        });
    };", CClientScript::POS_HEAD);
?>
