<script type="text/javascript">
    $(function(){
        $( "#showhidesearch" ).button({
            icons: {
                primary: "ui-icon-search"
            },
            text: true
        });
        $('#datepicker').datepicker({ dateFormat: 'yy-mm-dd' });
        $("#search").click(function(){

            loadGrid();
//             var mcategory = document.getElementById('mcategory');
//
//            var location = document.getElementById('location');
//            var products = document.getElementById('products');
//                $.ajax(
//                {
//                    type: "POST",
//                    url: "<?= site_url() ?>inventory/currentinventory/setparamsinsessionforprintcurrentstock",
//                    dataType: "json",
//                    data: {location: location.value, mcategory: mcategory.value, products: products.value},
//                    success: function(data){
//                         document.location.href="<?= site_url() ?>inventory/currentinventory/printcurrentstock/";
//                    },
//                    error:function (xhr, ajaxOptions, thrownError){
//                        alert(thrownError);
//                    }
//                });
//
//                e.preventDefault();
//                alert('here also ');
//                return false;
//                });

        });
        $("#add").click(function(){

            document.location.href="<?= site_url() ?>inventory/stock/addstockdiary";
        });
//        $("#addm").click(function(){
//
//            document.location.href="<?= site_url() ?>stock/addmultistockdiary";
//        });
        $("#showhidesearch").click(function(){
            if(document.getElementById('searchbartop').style.display == 'none')
                $("#searchbartop").show("blind", { direction: "vertical" }, 300);
            else
                $("#searchbartop").hide("blind", { direction: "vertical" }, 300);
        });
       
 $("#print").click(function(){




            var gr = jQuery("#lines").jqGrid('getGridParam','selarrrow');
//            if( gr != 0){
             var selid = jQuery("#lines").jqGrid('getCell', gr, 'ID');
                document.location.href="<?= site_url() ?>inventory/currentinventory/printcurrentstock/"+ selid;

//            }

//            else alert ("Please select a row.");
        });

        function loadGrid()
        {

            var mcategory = document.getElementById('mcategory');

            var location = document.getElementById('location');
            var products = document.getElementById('products');
            var date = document.getElementById('datepicker');

            $("#lines").GridUnload();
            jQuery("#lines").jqGrid({
                url:'<?= site_url() ?>inventory/stocksummaryitemwise/getstocksummaryitemwise',
                postData: { mcategory: mcategory.value, location: location.value, products: products.value, date: date.value},
                datatype: "json",
                mtype : "post",
                colNames:['CATEGORY','NAME','DATE','UOM','Quantity','Rate','Value','Quantity','Rate','Value','Quantity','Rate','Value', 'Quantity','Rate','Value'],
                colModel:[
                    {name:'CATEGORY',index:'CATEGORY', width:50,editoptions:{readonly:true,size:10}},
                    {name:'NAME',index:'NAME', width:100,editoptions:{readonly:true,size:10}},
                     {name:'DATE',index:'DATE', width:100,editable:true,align:"left", editoptions:{readonly:true,size:10}},
                     {name:'UOM',index:'UOM', width:50,editable:true,align:"left", editoptions:{readonly:true,size:10}},
                      {name:'OPENINGSTOCK',index:'OPENINGSTOCK', width:75, editable:true,align:"left",editoptions:{size:10}, classes: 'openingcell'},
                      {name:'RATE',index:'RATE', width:75, formatter:'currency', formatoptions: {thousandsSeparator:','}, editable:true,align:"right",editoptions:{size:10}, classes: 'openingcell'},
                    {name:'VALUE1',index:'VALUE1', width:75, formatter:'currency', formatoptions: {thousandsSeparator:','}, editable:true,align:"right",editoptions:{size:10},summaryType:'sum', classes: 'openingcell'},
                    {name:'STOCKIN',index:'STOCKIN', width:75,  editable:true,align:"left",editoptions:{size:10}, classes: 'inwardscell'},
                     {name:'RATE',index:'RATE', width:75, formatter:'currency', formatoptions: {thousandsSeparator:','}, editable:true,align:"right",editoptions:{size:10}, classes: 'inwardscell'},
                    {name:'VALUE2',index:'VALUE2', width:75, formatter:'currency', formatoptions: {thousandsSeparator:','}, editable:true,align:"right",editoptions:{size:10},summaryType:'sum', classes: 'inwardscell'},
                    {name:'STOCKOUT',index:'STOCKOUT', width:75, editable:true,align:"left",editoptions:{size:10}, classes: 'outwardscell'},
                     {name:'RATE',index:'RATE', width:75, formatter:'currency', formatoptions: {thousandsSeparator:','}, editable:true,align:"right",editoptions:{size:10}, classes: 'outwardscell'},
                   {name:'VALUE3',index:'VALUE3', width:75, formatter:'currency', formatoptions: {thousandsSeparator:','}, editable:true,align:"right",editoptions:{size:10},summaryType:'sum', classes: 'outwardscell'},
                   {name:'CLOSING',index:'CLOSING', width:75,editable:true,align:"left",editoptions:{size:10}, classes: 'closingcell'},
                     {name:'RATE',index:'RATE', width:75, formatter:'currency', formatoptions: {thousandsSeparator:','}, editable:true,align:"right",editoptions:{size:10}, classes: 'closingcell'},
                      {name:'VALUE4',index:'VALUE4', width:75, formatter:'currency', formatoptions: {thousandsSeparator:','}, editable:true,align:"right",editoptions:{size:10},summaryType:'sum', classes: 'closingcell'},
                    
                ],
                rowNum:100000,
//                rowList:[15,30,100000000],
                rownumbers: true,
                key: true,
                rownumWidth: 40,
                height: 'auto',
                width: 'auto',
                pager: '#pgtoolbar1',
                sortname: 'NAME',
                viewrecords: true,
                sortorder: "asc",
                multiselect: true,
                reloadAfterEdit: true,
                reloadAfterSubmit: true,
                                loadComplete: function() {
    $("option[value=100000000]").text('All');
},grouping:true,
            groupingView : {
                groupField : ['CATEGORY'],
                groupSummary : [true],
                groupColumnShow : [false],
                groupText : ['<b>{0} - {1} Item(s)</b>'],
                groupCollapse : true,
           
                groupOrder: ['asc'],
                groupSummary : [true],
		showSummaryOnHide: true,
		groupDataSorted : true
            },

                     beforeSelectRow: function(rowid, e)
    {
    jQuery("#lines").jqGrid('resetSelection');
    return(true);
    loadGrid();
    }



            });

            jQuery("#lines").jqGrid('setGroupHeaders', {
  useColSpanStyle: true,
  groupHeaders:[
	{startColumnName: 'OPENINGSTOCK', numberOfColumns: 3, titleText: '<em>Opening Balance</em>'},
	{startColumnName: 'STOCKIN', numberOfColumns: 3, titleText: '<em>Inwards</em>'},
        {startColumnName: 'STOCKOUT', numberOfColumns: 3, titleText: '<em>Outwards</em>'},
	{startColumnName: 'CLOSING', numberOfColumns: 3, titleText: '<em>Closing Balance</em>'}
  ]
});
            $("#lines").jqGrid('navGrid', '#pgtoolbar1',{view:false, del:false, search:false, refresh:false, add:false, edit:false, excel:true})
                .navButtonAdd('#pgtoolbar1',{
                                caption:"Export to Excel",
                                buttonicon:"ui-icon-save",
                                onClickButton: function(){
                                  exportExcel();
                                },
                                position:"last"
                            });
 function exportExcel()
        {
            var mya=new Array();
            mya=$("#lines").getDataIDs();  // Get All IDs
            var data=$("#lines").getRowData(mya[0]);     // Get First row to get the labels
            var colNames=new Array();
            var ii=0;
            for (var i in data){colNames[ii++]=i;}    // capture col names
            var html="";
            for(i=0;i<mya.length;i++)
                {
                data=$("#lines").getRowData(mya[i]); // get each row
                for(j=0;j<colNames.length;j++)
                    {
                    html=html+data[colNames[j]]+","; // output each column as tab delimited
                    }
                html=html+"\n";  // output each row with end of line

                }
            html=html+"\n";  // end of line at the end

document.forms[0].exportdata.value=html;
            document.forms[0].method='POST';
            document.forms[0].action='<?php echo site_url('inventory/stocksummaryitemwise/exportcsv'); ?>';  // send it to server which will open this contents in excel file
            document.forms[0].target='_blank';
            document.forms[0].submit();

        }


//            // Set navigator with search enabled.
//jQuery("#lines").jqGrid('navGrid','#pgtoolbar1',{add:false,edit:false,del:false});
//// add custom button to export the data to excel
//jQuery("#lines").jqGrid('navButtonAdd','#pgtoolbar1',{
//caption:"",
//onClickButton : function () {
//jQuery("#lines").jqGrid('excelExport', {tag:'pdf',url:(' <?= site_url() ?>grid.php') });
//alert('yyyy');
//}
//});

        }
        $(document).ready(function() {
            $("button").button();
            loadGrid(null);
        });
    });
</script>
<!--GET PRODUCTS FROM PRODUCT'S TABLE-->
<style>
    .ui-autocomplete-loading { background: white url('<?= site_url() ?>public/images/ui-anim_basic_16x16.gif') right center no-repeat; }
</style>
<script type="text/javascript">

    $(function() {


        $( "#products" ).autocomplete({
            source: function(request, response) {
                $.ajax({ url: "<?php echo site_url('inventory/searchmaterials/getmaterialautocomplete'); ?>",
                    data: { term: $("#products").val()},
                    dataType: "json",
                    type: "POST",
                    success: function(data){
                        response(data);

                    }
                });
            },
            minLength: 1
        });
    });
</script>
<script type="text/javascript">
    $(function() {
        $( "#mcategory" ).autocomplete({
            source: function(request, response) {
                $.ajax({ url: "<?php echo site_url('inventory/categories/getmatcategoriesautocomplete'); ?>",
                    data: { term: $("#mcategory").val()},
                    dataType: "json",
                    type: "POST",
                    success: function(data){
                        response(data);

                    }
                });

            },
            minLength: 1
        });

    });
</script>
<script>
	// increase the default animation speed to exaggerate the effect
	$.fx.speeds._default = 1000;
	$(function() {
		$( "#dialog" ).dialog({
			autoOpen: false,
			show: "blind",
			hide: "explode",buttons: {
				Ok: function() {
					$( this ).dialog( "close" );
				}
			}

		});

	});
	</script>



<div class="demo">

<div id="dialog" title="Message">
	<p>Please select a row !</p>
</div>

</div><!-- End demo -->

<div class="main content clearfix">
<div class="page-heading">
            <h2>Stock Summary</h2>
        </div>
        <!-- end page-heading -->

        <table align="right" border="0" width="100%" cellpadding="0" cellspacing="0" id="content-table">
            <tr>
                <th rowspan="3" class="sized"><img src="<?= site_url() ?>images/shared/side_shadowleft.jpg" width="20" height="300" alt="" /></th>
                <th class="topleft"></th>
                <td id="tbl-border-top">&nbsp;</td>
                <th class="topright"></th>
                <th rowspan="3" class="sized"><img src="<?= site_url() ?>images/shared/side_shadowright.jpg" width="20" height="300" alt="" /></th>
            </tr>
            <tr>
                <td id="tbl-border-left"></td>
                <td>
                    <!-- start content-table-inner ...................................................................... START -->
                    <div id="content-table-inner">

                        <!-- start table-content -->
                        <div id="table-content">
                            <?php
                            if ($this->session->flashdata('msgt') == 'E') {
                                echo '
<div id="message-red">
<table border="0" width="100%" cellpadding="0" cellspacing="0">
<tr>
<td class="red-left">' . $this->session->flashdata('msg') . '</td>
<td class="red-right"><a class="close-red"><img src="' . site_url() . 'images/table/icon_close_red.gif" alt="" /></a></td>
</tr>
</table>
</div><br>
';
                            }
                            if ($this->session->flashdata('msgt') == 'S') {
                                echo '
<div id="message-green">
<table border="0" width="100%" cellpadding="0" cellspacing="0">
<tr>
<td class="green-left">' . $this->session->flashdata('msg') . '</a></td>
<td class="green-right"><a class="close-green"><img src="' . site_url() . 'images/table/icon_close_green.gif" alt="" /></a></td>
</tr>
</table>
</div><br>
';
                            }
                            ?>
                            <!-- start product-table ..................................................................................... -->
                            <div id="toolbartop">

 <?php
                                    $date = date('Y-m-d');
                                    ?>
                                     <button id="print" name="print">Print</button></span>
                                <button id="showhidesearch" name="showhidesearch" style="float: right;">Search</button>
                            </div>
                            <div id="searchbartop" style="display:none">
                                 <div class="myform-search clearfix">
                                <table>
                                    <tr>
                                    <form>
                                        <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
                                        <td><label>Warehouse</label><br>
                                            <select id="location" name="location" type="text" class="styledselect_form_1">
                                                <?= $location ?>
                                            </select>
                                        </td>

                                         <td>Date<br>
                                                <input name="datefrom" type="text" value="<?= $date ?>" id="datepicker" class="inp-form-small"/>
                                            </td>


                                        <td>Material Category<br>
                                            <input id="mcategory" type="text" name="mcategory" class="inp-form"/>

                                        </td>

                                        <td>Material<br>
                                            <input id="products" type="text" name="product" class="inp-form"/>
                                        </td>

                                        <td>&nbsp;</td>

                                          <td>
                                            <br>
                                            <button value="Reset">Reset</button>
                                        </td>

                                       <form method="post" action="<?php echo site_url('inventory/stocksummaryitemwise/exportcsv'); ?>">
    <input type="hidden" name="exportdata" id="exportdata" value="" />
</form>

                                        </form>



                                        <td>   &nbsp;&nbsp;&nbsp;&nbsp; </td>

                                        <td>
                                            <br>
                                            <button id="search" name="search">Search</button>

                                        </td>
                                    </tr>
                                </table>
                                <br>
                                 </div>
                            </div>

                            <table id="lines"></table>
                            <div id="pgtoolbar1"></div>
                            <!-- end content-table -->
                        </div>

                        <div class="clear"></div>

                    </div>
                    <!-- end content-table-inner ............................................END -->
                </td>
                <td id="tbl-border-right"></td>
            </tr>
            <tr>
                <th class="sized bottomleft"></th>
                <td id="tbl-border-bottom">&nbsp;</td>
                <th class="sized bottomright"></th>
            </tr>
        </table>

<div class="clear">&nbsp;</div>
</div>
