<?php 
/********************************************************************************* 
 *  This file is part of Sentrifugo.
 *  Copyright (C) 2014 Sapplica
 *   
 *  Sentrifugo is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Sentrifugo is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Sentrifugo.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  Sentrifugo Support <support@sentrifugo.com>
 ********************************************************************************/
?>

<?php sapp_Global::generateClientValidations($this->form);?>
<script type='text/javascript'>
	function getdepartments(flag)
	{
		if(flag == 'perpage')
		{
		   $('#pageno').val('1');
		} 	

     if(flag == 'button'){
		$('#pageno').val('1');
		deptnametemp = $.trim($('#deptname').val());
		deptname = '';
		if(deptnametemp != '')
		{
			deptname = $.trim($('#hiddendeptname').val());          
			if(deptname != '')
			{
				deptnametext = $('#hiddendeptnametext').val();
				$('#deptname').val($('#hiddendeptnametext').val());
				$('#deptnameclear').show();
			}else{
				$('#deptname').val('');
			}		   
		} 
		
		dcodetemp = $.trim($('#dcode').val());
		dcode = '';
		if(dcodetemp != '')
		{
			dcode = $.trim($('#hiddendeptcode').val());	
			if(dcode != '')
			{
				dcodetext = $('#hiddendeptcodetext').val();
				$('#dcode').val($('#hiddendeptcodetext').val());
				$('#dcodeclear').show();
			}else{
				$('#dcode').val('');
			}			
		}	
		bunitnametemp = $.trim($('#bname').val());
		bunitname = '';
		if(bunitnametemp != '')
		{
			bunitnametext = $.trim($('#hiddenbunametext').val());
			bunitname = $.trim($('#hiddenbuname').val());	
			$('#bnameclear').show();
		}	
		country = $('#country').val();
		if(country !='')
		{
			countrytext = $("#country option:selected").text();	
			$('#countryclear').show();
		}	
		startdate = $('#startdate').val();
		if(startdate !='')
		{
			$('#startdateclear').show();
		}	
	}else{
		 if($('#deptnameclear').is(':visible'))
		 { 
		    $('#deptname').val(deptnametext);
			$('#hiddendeptname').val(deptname);
			$('#hiddendeptnametext').val(deptnametext);
		 }
		 if($('#dcodeclear').is(':visible'))
		 { 
		    $('#dcode').val(dcodetext);
			$('#hiddendeptcode').val(dcode);
			$('#hiddendeptcodetext').val(dcodetext);
		 }
		 if($('#bnameclear').is(':visible'))
		 { 
		    $('#bname').val(bunitnametext);
			$('#hiddenbuname').val(bunitname);
			$('#hiddenbunametext').val(bunitnametext)
			
		 }
		 if($('#countryclear').is(':visible'))
		   {
			 $('#country').val(country);
			 $('#s2id_country .select2-choice span').html(countrytext);		
		   }
		 if($('#startdateclear').is(':visible'))
		   {
			 $('#startdate').val(startdate);
		   }
		
	}
		var pageno = $('#pageno').val();
		var perpage = $('#perPagetext').val();
		$('#perpage').val(perpage);
		var sortby = $('#sortby').val();
		var by = $('#by').val();
		
		var columnsortby = $('#columnsortby').val();
		var columnby = $('#columnby').val();
		var checkedheaders = $('#checkedheaders').val();		
		var param_str = $('#filters_div').find('select, textarea, input').serialize();
		$('#id_param_string').val(param_str);
		
		$.ajax({
				url : base_url+'/reports/departments/format/html',
				type : 'POST',
				data : 'bunitname='+bunitname+'&country='+country+'&startdate='+startdate+'&pageno='+pageno+'&perpage='+perpage+'&sortby='+sortby+'&by='+by+'&columnsortby='+columnsortby+'&columnby='+columnby+'&checkedheaders='+checkedheaders+'&deptname='+deptname+'&dcode='+dcode,
				datatype : 'html',
				beforeSend : function () 
							{
								$.blockUI({ width:'50px',message: $("#spinner").html() });
							},
				success : function(response)						
							{
								$('#loader').remove();
								if(response != '' && response != 'null' && $.trim(response) != 'norecord')
								{
									$('#userlogpreview').html(response);
								}
								if($.trim(response) == 'norecord')
								{
									$('#userlogpreview').html('No Data Found');
								}
							}
		});
	}
	function sortcolumn(sortflag,divid)
	{
		$('#columnid').val(divid);
	    if($('#columnsortby').val() == sortflag)
		{
			if($('#columnby').val() == 'Asc')
				$('#columnby').val('Desc');		
			else
				$('#columnby').val('Asc');
		}
		else
		{
		    $('#columnsortby').val(sortflag);
			if($('#columnby').val() == 'Asc')
				$('#columnby').val('Desc');	
			else
				$('#columnby').val('Asc'); 		
		}
		getdepartments('');
	}
	function clearall()
	{		
		startdate = '';country='';countrytext = '';bunitname = '';bunitnametext= '';bunitnametemp = '';dcode ='';dcodetext = '';deptname = '';deptnametext = '';
		$('#deptname').val('');
		$('#hiddendeptname').val(''); 
		$('#dcode').val('');
		$('#hiddendeptcode').val('');
		$('#bname').val(''); 
		$('#hiddenbuname').val(''); 	
		
		if($('#hiddendeptnametext').val() != '')
			$('#hiddendeptnametext').val('');
		if($('#hiddendeptcodetext').val() != '')
			$('#hiddendeptcodetext').val('');
		if($('#hiddenbunametext').val() != '')
			$('#hiddenbunametext').val('');
			
		if($('#country').val() !='')
		{
			$('#s2id_country .select2-choice span').html('All');
			$('#country').val(''); 
		} 		
		
		$('#startdate').val(''); 
		
		 /* Start Make all hidden variables to default */
		   $('#perPagetext').val('20');
		   $('#pageno').val('1');
		   $('#sortby').val('d.modifieddate');
		   $('#by').val('Desc');
		   $('#columnsortby').val('');
		   $('#columnby').val('');
		   $('#columnid').val('');
		   $('#checkedheaders').val('deptname,deptcode,unitname,startdate,empcount,address,ccity,sstate,ccountry,status');
		   $('#deptnameclear').hide();
		   $('#dcodeclear').hide();
		   $('#bnameclear').hide();
		   $('#countryclear').hide();
		   $('#startdateclear').hide();
	  /* End */ 

		getdepartments();	  
	}
	function changepagenum()
	{
		$('#pageno').val('1');
	}
	function displaytabs()
	{	
            if($('#selectfields').hasClass("config-up"))		
            {
                $( '#selectfields').removeClass("config-up");
                $( '#selectfields').addClass("config-down");
                $('#tabdiv').slideDown();	
		    
                var overlay	= '<div id="reportgridoverlay" class="overlayreport"></div>';
                $('#reportgrid').prepend(overlay);      
			  
            }
            else
            {
                $( '#selectfields').removeClass("config-down");
                $( '#selectfields').addClass("config-up");
                $('#tabdiv').slideUp();
                $('.overlayreport').remove();
            }
	}
	function assignheaders()
	{
		var chkArray = [];     	  
		$("#tabdiv input:checked").each(function() {
			chkArray.push($(this).val());
		});   
	
		var checkedheaders;
		checkedheaders = chkArray.join(',');
		$('#checkedheaders').val(checkedheaders);
	}
	
	function setdepartmentstab()
	{
            var chk_len = $("#tabdiv input:checked").length;
            if(chk_len == 0)
            {
                jAlert("Please check atleast one column.");                
                $( '#selectfields').addClass("config-up");
                displaytabs();
                return false;
            }
            else 
            {
                assignheaders();
                getdepartments('button');
            }
	}
	
	function getdatabyperpage()
	{
		  $('#pageno').val('1');
		   if($('#perPagetext').val() == ''){
			   $('#perPagetext').val('<?php echo $this->perpage;?>');
			}
		   $('#per_page').val($('#perPagetext').val());
		   getdepartments();
	}
	
	function cleardeptsearch(searchfilterid)
	{
	  var inputid = jQuery.trim(searchfilterid.replace("clear", ""));
	  $('#'+inputid).val(''); 
		 if(inputid == 'country'){
			 country='';countrytext = '';
			  $('#s2id_country .select2-choice span').html('All');
		 }else if(inputid == 'deptname'){ 
			 deptname = '';deptnametext = '';
			$('#hiddendeptname').val('');
			$('#hiddendeptnametext').val('');
		 }else if(inputid == 'dcode'){
			dcode ='';dcodetext = '';
			$('#hiddendeptcode').val('');
			$('#hiddendeptcodetext').val('');
		 }else if(inputid == 'bname'){
			bunitname = '';bunitnametemp = '';bunitnametext= '';
				$('#hiddenbuname').val('');
				$('#hiddenbunametext').val('');
		 }
		 else if(inputid == 'startdate'){
			 startdate = '';
		 } 
    	$('#'+searchfilterid).hide(); 
	    getdepartments('');
	}
	
	function canceldepartmenttab()
	{
		var selectedColumns = $('#selectedColumns').val();
		  selectedColumns = selectedColumns.split(','); 
		  if(selectedColumns.length > 0){ 	 
			setTimeout(function(){	  
				$("#tabdiv input").each(function() {
					var val = jQuery.trim($(this).val()); 				
					if(jQuery.inArray(val, selectedColumns) != -1){
						$('#check_'+val).prop('checked', true);
					}else{
					$('#check_'+val).prop('checked', false);
					}   		
				});
			},1000);
		  }
		  
	   $('#selectfields').removeClass("config-down").addClass("config-up");
	   $('#tabdiv').slideUp();
	   $('#reportgridoverlay').remove();
	}
	function clearautocompletenames(ele)
	{
		var elementid = $(ele).prop('id');	    
		var elementvalue = $('#'+elementid).val();
		if(elementvalue != '')
		{
			var text = '';var hiddenname = '';			   
		    if(elementid == 'deptname')
		    {
				text = $('#hiddendeptnametext').val();
				hiddenname = $('#hiddendeptname').val();
				if(hiddenname =='' && text != elementvalue)
				{
					$("#"+elementid).val('');
					$('#deptnameclear').hide();
					$('#hiddendeptname').val('');
					$('#hiddendeptnametext').val('');
				}else if(text != elementvalue){
					$("#"+elementid).val(text);
				}
			}
			else if(elementid == 'dcode')
			{
				text = $('#hiddendeptcodetext').val();
				hiddenname = $('#hiddendeptcode').val();
				if(hiddenname =='' && text != elementvalue)
				{
					$("#"+elementid).val('');
					$('#dcodeclear').hide();
					$('#hiddendeptcode').val('');
					$('#hiddendeptcodetext').val('');
				}else if(text != elementvalue){
					$("#"+elementid).val(text);
				}
			}
			else if(elementid == 'bname')
			{
				text = $('#hiddenbunametext').val();
				hiddenname = $('#hiddenbuname').val();
				if(hiddenname == '' && text != elementvalue)
				{
					$("#"+elementid).val('');
					$('#bnameclear').hide();
					$('#hiddenbuname').val('');
					$('#hiddenbunametext').val('');
				}else if(text != elementvalue){
					$("#"+elementid).val(text);
				}
			}
		}  
	}
</script>
<?php $checkedheaders = 'deptname,deptcode,unitname,startdate,empcount,address,ccity,sstate,ccountry,status';
echo $this->reportsheader('organization');
?>

<div class="export-links">
<div class="fltright">
<div class="sprite export-xls" style="display:none;" id="excel">Export to Excel</div>
<div class="sprite export-pdf" style="display:none;" id="pdf">Export to PDF</div>
</div>
</div>
<div class="left-config-ctrl">
	<div class="total-form-controller-left">
	<div class="heading-name-1">Generate Custom Report</div>
    <form name="<?php echo $this->form->getName(); ?>"	id="<?php echo $this->form->getId(); ?>" action="<?php echo $this->form->getAction();?>" method="<?php echo $this->form->getMethod(); ?>">
	<div id="filters_div">		
		<div class="new-form-ui">
			 <label><?php echo $this->form->deptname->getLabel(); ?></label>
			 <button type="button" id="deptnameclear" name="deptnameclear" class="inputclear" style="display:none;" onclick="cleardeptsearch('deptnameclear')">Clear</button>
			 <div class="division"><?php echo $this->form->deptname; ?>
				 <input type="hidden" name="hiddendeptname" id="hiddendeptname" value="" />
				 <input type="hidden" name="hiddendeptnametext" id="hiddendeptnametext" value="" />
				<span id="errors-<?php echo $this->form->deptname->getId(); ?>" class="errors">
				 <?php echo isset($this->msgarray['deptname'])?$this->msgarray['deptname']:"";?>
				</span>
			 </div>
		</div>
		
		<div class="new-form-ui">
			 <label><?php echo $this->form->dcode->getLabel(); ?></label>
			 <button type="button" id="dcodeclear" name="dcodeclear" class="inputclear" style="display:none;" onclick="cleardeptsearch('dcodeclear')">Clear</button>
			 <div class="division"><?php echo $this->form->dcode; ?>
				 <input type="hidden" name="hiddendeptcode" id="hiddendeptcode" value="" />
				 <input type="hidden" name="hiddendeptcodetext" id="hiddendeptcodetext" value="" />
				<span id="errors-<?php echo $this->form->dcode->getId(); ?>" class="errors">
					<?php echo isset($this->msgarray['dcode'])?$this->msgarray['dcode']:"";?>
				</span>
			 </div>
		</div>
		
		<div class="new-form-ui">
			 <label><?php echo $this->form->bname->getLabel(); ?></label>
			 <button type="button" id="bnameclear" name="bnameclear" class="inputclear" style="display:none;" onclick="cleardeptsearch('bnameclear')">Clear</button>
			 <div class="division"><?php echo $this->form->bname; ?>
				 <input type="hidden" name="hiddenbuname" id="hiddenbuname" value="" />
				 <input type="hidden" name="hiddenbunametext" id="hiddenbunametext" value="" />
				<span id="errors-<?php echo $this->form->bname->getId(); ?>" class="errors">
				 <?php echo isset($this->msgarray['bname'])?$this->msgarray['bname']:"";?>
				</span>
			 </div>
		</div>	
		
		<div class="new-form-ui">
			 <label><?php echo $this->form->country->getLabel(); ?></label>
			 <button type="button" id="countryclear" name="countryclear" class="inputclear" style="display:none;" onclick="cleardeptsearch('countryclear')">Clear</button>
			 <div class="division"><?php echo $this->form->country; ?>
				<span id="errors-<?php echo $this->form->country->getId(); ?>" class="errors">
				 <?php echo isset($this->msgarray['country'])?$this->msgarray['country']:"";?>
				</span>
			 </div>
		</div>
		
		<div class="new-form-ui">
			 <label><?php echo $this->form->startdate->getLabel(); ?></label>
			 <button type="button" id="startdateclear" name="startdateclear" class="inputclear" style="display:none;" onclick="cleardeptsearch('startdateclear')">Clear</button>
			 <div class="division"><?php echo $this->form->startdate; ?>
				<span id="errors-<?php echo $this->form->startdate->getId(); ?>" class="errors">
				 <?php echo isset($this->msgarray['startdate'])?$this->msgarray['startdate']:"";?>
				</span>
			 </div>
		</div>	
		<input type="hidden" id="id_param_string" value="" />
		<input type="hidden" id="generatereport" name="generatereport" value="" /> 
		<input type="hidden" id="pageno" name="pageno" value="<?php echo $this->pageno;?>" />
		<input type="hidden" id="sortby" name="sortby" value="<?php echo $this->sortby?>" />
		<input type="hidden" id="by" name="by" value="<?php echo $this->by;?>" />
		<input type="hidden" id="perpage" name="perpage" value="<?php echo $this->perpage;?>" />
		<input type="hidden" id="columnsortby" name="columnsortby" value="<?php echo $this->columnsortby;?>" />
		<input type="hidden" id="columnby" name="columnby" value="<?php echo $this->columnby;?>" />
		<input type="hidden" id="columnid" name="columnid" value="" />
		<input type="hidden" id="checkedheaders" name="checkedheaders" value="<?php echo $checkedheaders; ?>" />	
	</div>
		<div class="new-form-ui-submit mrgetop5">
			<button type="button" class="previewreport"  id="businessunitsgo" title="Generate Preview">Generate Report</button>			
			<button type="button" id="clear" onclick="clearall();" name="clear">Reset</button>
		</div>
        </form>
	</div>	
				
</div>
	<div class="right-config-ctrl">
		<div id="userlogpreview" class="all-grid-control" ></div>
	</div>
</div>
</div>
<div id="empinfo" style="display:none;"></div>
<script type='text/javascript'>
var yearrange = <?php echo "'".YEAR.':'.(date('Y')+20)."'"; ?>;
$(document).ready(function(){
	startdate = '';country='';countrytext = '';bunitname = '';bunitnametemp = '';bunitnametext= '';dcode ='';dcodetext = '';deptnametemp = '';deptnametext = '';
	
	getdepartments();
	$('#perpage').val('<?php echo $this->perpage; ?>');
	var now = new Date();
	now.setDate(now.getDate()+1);
        $('#businessunitsgo').click(function(){
           setdepartmentstab() 
        });
	$('#startdate').datepicker({
					showOn:'both',		
					yearRange: yearrange,				
					dateFormat: '<?php echo DATEFORMAT_JS;?>',
					buttonImage: "<?php echo $this->baseUrl("public/media/images/cal.jpg");?>",
					buttonImageOnly: true,
					buttonText: "",
					changeMonth: true,
					changeYear: true,
					showButtonPanel: true					
			});	
	
	$('#deptname').autocomplete({
        source: base_url+"/reports/bunitauto/flag/dname",        
        select: function( event, ui ) 
        {
            var sel_id = ui.item.id;           
            $('#hiddendeptname').val(ui.item.id);		
			$('#hiddendeptnametext').val(ui.item.value);			
            if(sel_id == '')
            {
                $('#deptname').val('');
				$('#hiddendeptnametext').val('');
                return false;
            }
        }
    }).data( "ui-autocomplete" )._renderItem = function( ul, item ) 
		{
			return $( "<li>" )
			.append( "<a>" + item.label + "</a>" )
			.appendTo( ul );
		}; 
	
	$('#bname').autocomplete({
        source: base_url+"/reports/bunitauto/flag/fromdept",        
        select: function( event, ui ) 
        {
            var sel_id = ui.item.id;           
            $('#hiddenbuname').val(ui.item.id);
			$('#hiddenbunametext').val(ui.item.value);			
            if(sel_id == '')
            {
                $('#bname').val('');
				$('#hiddenbunametext').val('');
                return false;
            }
        }
    }).data( "ui-autocomplete" )._renderItem = function( ul, item ) 
		{
			return $( "<li>" )
			.append( "<a>" + item.label + "</a>" )
			.appendTo( ul );
		}; 
	
	$('#dcode').autocomplete({
        source: base_url+"/reports/bunitcodeauto/flag/dcode",        
        select: function( event, ui ) 
        {
            var sel_id = ui.item.id;           
            $('#hiddendeptcode').val(ui.item.id);			
			$('#hiddendeptcodetext').val(ui.item.value);
            if(sel_id == '')
            {
                $('#dcode').val('');
				$('#hiddendeptcodetext').val('');
                return false;
            }
        }
    }).data( "ui-autocomplete" )._renderItem = function( ul, item ) 
		{
			return $( "<li>" )
			.append( "<a>" + item.label + "</a>" )
			.appendTo( ul );
		}; 
	
	$('#perpage').keydown(function(e) {
          var code = e.keyCode || e.which;
		 if (code  == 13) {
				changepagenum();
              getdepartments();
			}
		});
	
	
		
    $('#pdf').click(function(){
	   $('#generatereport').val('pdf');
            downloadBUsPdf(base_url + '/reports/exportdepartmentpdf', '#<?php echo $this->form->getId();?>');	
   });
   $('#excel').click(function() {
		/*$('#generatereport').val('excel');
	    document.getElementById("<?php echo $this->form->getId(); ?>").submit();*/
		var param_str = $('#id_param_string').val();
        var url= base_url+"/default/reports/getexcelreportdepartment?"+param_str; 	
		var form = [ '<form method="POST" action="', url, '" accept-charset=utf-8 id="idfrm_export" >' ];	
		form.push('</form>');        
		jQuery(form.join('')).appendTo('body')[0].submit();       
			$('#idfrm_export').remove();
   });
});
</script>