<!DOCTYPE html>
<html lang="en">
<head>
<style type='text/css'>
.bg-orange
{
	background-color:orange ;
	color:#fff;
}

.bg-green
{
	background-color:green ;
	color:#fff;
}

.bg-blue
{
	background-color:red ;
	color:#fff;
}

</style>
	
	<?php 
	use App\Libraries\MyEncrypt;

	$this->db = db_connect();
		$session = \Config\Services::session();
		$admin_login=$session->get('userid');
		$get_admin=$this->db->query("select * from admin where id='".$admin_login."'")->getRow();
		$user_group = $get_admin->user_group;
		

	echo view('admin/common_header'); ?>

	<!-- Theme JS files -->
	<script type="text/javascript" src="<?php echo base_url('assets/js/plugins/visualization/d3/d3.min.js');?>"></script>
	<script type="text/javascript" src="<?php echo base_url('assets/js/plugins/visualization/d3/d3_tooltip.js');?>"></script>
	<script type="text/javascript" src="<?php echo base_url('assets/js/plugins/forms/styling/switchery.min.js');?>"></script>
	<script type="text/javascript" src="<?php echo base_url('assets/js/plugins/forms/styling/uniform.min.js');?>"></script>
	<script type="text/javascript" src="<?php echo base_url('assets/js/plugins/ui/moment/moment.min.js');?>"></script>
	<script type="text/javascript" src="<?php echo base_url('assets/js/plugins/pickers/daterangepicker.js');?>"></script>

	<!-- /theme JS files -->
	
	

	<script type="text/javascript" src="<?php echo base_url('assets/js/plugins/visualization/echarts/echarts.js');?>"></script>
	<script type="text/javascript" src="<?php echo base_url('assets/js/plugins/visualization/echarts/chart/bar.js');?>"></script>
	<script type="text/javascript" src="<?php echo base_url('assets/js/plugins/visualization/echarts/chart/line.js');?>"></script>
	<script type="text/javascript" src="<?php echo base_url('assets/js/plugins/visualization/echarts/theme/limitless.js');?>"></script>

	<!-- notify JS files -->
    <script type="text/javascript" src="<?php echo base_url('assets/js/plugins/notifications/jgrowl.min.js');?>"></script>

    <script type="text/javascript" src="<?php echo base_url('assets/js/core/app.js');?>"></script>
	


</head>

<body class="navbar-top-md-md">

	<!-- Fixed navbars wrapper -->
	<div class="navbar-fixed-top">

		<!-- Main navbar -->
		<?php echo view('admin/mainnav'); ?>
		<!-- /main navbar -->


		<!-- Second navbar -->
		<?php echo view('admin/secondnav'); ?>
		<!-- /second navbar -->

	</div>
	<!-- /fixed navbars wrapper -->

		<?php 
		helper('inflector');

		$currency_info = defaultcurrency();
		?>

	<!-- Page header -->
	<div class="page-header">
		<div class="page-header-content">
			<div class="page-title">
				<h4><i id="icon-bck" class="icon-arrow-left52 position-left"></i> <span class="text-semibold"><?php echo lang('language_lang.dashboard_page_title'); ?></h4>

				<ul class="breadcrumb breadcrumb-caret position-right">
					<?php foreach ($breadcrumbs as $breadcrumb) { ?>
					    <li><a href="<?php echo $breadcrumb['href']; ?>"><?php echo $breadcrumb['text']; ?></a></li>
					<?php } ?>
				</ul>
			</div>
			<?php echo view('admin/'.$module_name.'_header'); ?>
		</div>
	</div>
	<!-- /page header -->

	<!-- Page container -->
	<div class="page-container">

		<!-- Page content -->
		<div class="page-content">

			<!-- Main content -->
			<div class="content-wrapper">

			<div class="row" style='display:none;'>
				<div class="col-lg-12">
					<div class="col-lg-3">	
						<div class="panel bg-indigo-400">
							<div class="panel-body">
								<div class="heading-elements">
									<ul class="icons-list">
						        		<li><a data-action="reload"></a></li>
                                     </ul>
								 </div>


									<h3 class="no-margin"><?php if($tot == '') { echo "0"; } else { echo $tot; } ?> <?php echo $tokenname;?></h3>
									<?php echo lang('language_lang.dash_token_supply'); ?>
									<div class="text-muted text-size-small"></div>
							</div>
							<div class="container-fluid">
								<div id="members-online1"></div>
							</div>
							</div>
						</div>
						<div class="col-lg-3">	
						<div class="panel bg-slate-400">
							<div class="panel-body">
								<div class="heading-elements">
									<ul class="icons-list">
						        		<li><a data-action="reload"></a></li>
                                     </ul>
								</div>
									<h3 class="no-margin"><?php if($tot1 == '') { echo "0"; } else { echo $tot1; } ?> <?php echo $tokenname;?></h3>
									<?php echo lang('language_lang.dash_token_sold'); ?>
									<div class="text-muted text-size-small"></div>
							</div>
							<div class="container-fluid">
								<div id="server-load1"></div>
							</div>
							</div>
						</div>

						<div class="col-lg-3">	
						<div class="panel bg-orange-400">
							<div class="panel-body">
								<div class="heading-elements">
									<ul class="icons-list">
						        		<li><a data-action="reload"></a></li>
                                     </ul>
								</div>
								<h3 class="no-margin"><?php if($bal_t == '') { echo "0"; } else { echo $bal_t; } ?> <?php echo $tokenname;?></h3>
									<?php echo lang('language_lang.dash_token_avail'); ?>
									
									<div class="text-muted text-size-small"></div>
							</div>
							<div class="container-fluid">
								<div id="server-load2"></div>
							</div>
							</div>
						</div>

						<div class="col-lg-3">	
						<div class="panel bg-pink-400">
							<div class="panel-body">
								<div class="heading-elements">
									<ul class="icons-list">
						        		<li><a data-action="reload"></a></li>
                                     </ul>
								</div>
									<h3 class="no-margin"><?php echo $token_value;?> <?php echo strtoupper($currency_info->currency_unit);?></h3>
									<?php echo lang('language_lang.dash_token_price'); ?>
									<div class="text-muted text-size-small"></div>
							</div>
							<div class="container-fluid">
								<div id="today-revenue1"></div>
							</div>
							</div>
						</div>


						<div class="col-lg-3">	
						<div class="panel bg-green-400">
							<div class="panel-body">
								<div class="heading-elements">
									<ul class="icons-list">
						        		<li><a data-action="reload"></a></li>
                                     </ul>
								</div>
								<h3 class="no-margin"><?php if($lend_dep_amt[0]->amt == '') { echo "0"; } else { echo number_format($lend_dep_amt[0]->amt,$currency_info->deimal_point); } ?> <?php echo strtoupper($currency_info->currency_unit);?> </h3>
									<?php echo lang('language_lang.dash_len_dep'); ?>
									
									<div class="text-muted text-size-small"></div>
							</div>
							<div class="container-fluid">
								<div id="server-load3"></div>
							</div>
							</div>
						</div>

						<div class="col-lg-3">	
						<div class="panel bg-blue-400">
							<div class="panel-body">
								<div class="heading-elements">
									<ul class="icons-list">
						        		<li><a data-action="reload"></a></li>
                                     </ul>
								</div>
								<h3 class="no-margin"><?php if($lend_amt[0]->amt == '') { echo "0"; } else { echo number_format($lend_amt[0]->amt,$currency_info->deimal_point); } ?> <?php echo strtoupper($currency_info->currency_unit);?></h3>
									<?php echo lang('language_lang.dash_len_bal'); ?>
									
									<div class="text-muted text-size-small"></div>
							</div>
							<div class="container-fluid">
								<div id="members-online2"></div>
							</div>
							</div>
						</div>


						<div class="col-lg-3">	
						<div class="panel bg-purple-400">
							<div class="panel-body">
								<div class="heading-elements">
									<ul class="icons-list">
						        		<li><a data-action="reload"></a></li>
                                     </ul>
								</div>
								<h3 class="no-margin"><?php if($lend_amt1[0]->amt == '') { echo "0"; } else { echo number_format($lend_amt1[0]->amt,$currency_info->deimal_point); } ?> <?php echo strtoupper($currency_info->currency_unit);?></h3>
									<?php echo lang('language_lang.dash_len_int'); ?>
									
									<div class="text-muted text-size-small"></div>
							</div>
							<div class="container-fluid">
								<div id="today-revenue3"></div>
							</div>
							</div>
						</div>


						<div class="col-lg-3">	
						<div class="panel bg-violet-400">
							<div class="panel-body">
								<div class="heading-elements">
									<ul class="icons-list">
						        		<li><a data-action="reload"></a></li>
                                     </ul>
								</div>
								<h3 class="no-margin"><?php if($lend_amt1_today[0]->amt == '') { echo "0"; } else { echo number_format($lend_amt1_today[0]->amt,$currency_info->deimal_point); } ?></h3>
									<?php echo lang('language_lang.dash_len_into'); ?>
									
									<div class="text-muted text-size-small"></div>
							</div>
							<div class="container-fluid">
								<div id="today-revenue4"></div>
							</div>
							</div>
						</div>
					
					</div>
				</div>

				<!-- Main charts -->
				<div class="row">
					<div class="col-lg-6">
						<!-- Traffic sources -->
						<div class="panel panel-flat">
							<div class="panel-heading">
								<h6 class="panel-title"><?php echo lang('language_lang.dash_traffic_source'); ?></h6>
								<div class="heading-elements">
									
								</div>
							</div>

							<div class="container-fluid">
								<div class="row">
									<div class="col-lg-4">
										<ul class="list-inline text-center">
											<li>
												<a class="btn border-teal text-teal btn-flat btn-rounded btn-icon btn-xs valign-text-bottom"><i class="icon-plus3"></i></a>
											</li>
											<li class="text-left">
												<div class="text-semibold"><?php echo lang('language_lang.dash_active_user'); ?></div>
												<div class="text-muted"><?php if($total_active_acc == '') { echo "0"; } else { echo $total_active_acc; } ?></div>
											</li>
										</ul>

										<div class="col-lg-10 col-lg-offset-1">
											<div class="content-group" id="new-visitors"></div>
										</div>
									</div>

									<div class="col-lg-4">
										<ul class="list-inline text-center">
											<li>
												<a class="btn border-warning-400 text-warning-400 btn-flat btn-rounded btn-icon btn-xs valign-text-bottom"><i class="icon-watch2"></i></a>
											</li>
											<li class="text-left">
												<div class="text-semibold"><?php echo lang('language_lang.dash_new_user'); ?></div>
												<div class="text-muted"><?php if($new_member_acc == '') { echo "0"; } else { echo $new_member_acc; } ?></div>
											</li>
										</ul>

										<div class="col-lg-10 col-lg-offset-1">
											<div class="content-group" id="new-sessions"></div>
										</div>
									</div>

									<div class="col-lg-4">
										<ul class="list-inline text-center">
											<li>
												<a class="btn border-indigo-400 text-indigo-400 btn-flat btn-rounded btn-icon btn-xs valign-text-bottom"><i class="icon-people"></i></a>
											</li>
											<li class="text-left">
												<div class="text-semibold"><?php echo lang('language_lang.dash_total_user'); ?></div>
												<div class="text-muted"><span class="status-mark border-success position-left"></span><?php if($total_accounts == '') { echo "0"; } else { echo $total_accounts; } ?></div>
											</li>
										</ul>

										<div class="col-lg-10 col-lg-offset-1">
											<div class="content-group" id="total-online"></div>
										</div>
									</div>
								</div>
							</div>

							<div class="chart-container">
							<div class="chart has-fixed-height" id="stacked_columns"></div>
						</div>
						</div>
						<!-- /traffic sources -->

					</div>

					<div class="col-lg-6">

						<!-- Sales stats -->
						<div class="panel panel-flat">
							<div class="panel-heading">
								<h6 class="panel-title"><?php echo "Statistics"?></h6>
								<div class="heading-elements">
									<form class="heading-form" action="#">
										<div class="form-group">
											<select style="display:none;" class="change-date select-sm" id="select_date">
												<?php
                                                 
				    									$current_date = date("Y-m-d H:i:s");
		    											$date = $current_date;
														$date = strtotime($date);
														$firstenddate = date("F",$date);
														$first_end_day = date("d",$date);
														$date = strtotime("-"."7"." day", $date);
														$firststart_week = date('Y-m-d H:i:s', $date);
														$assign_Data = strtotime($firststart_week);
														$firstval = date("F",$assign_Data);
														$firstvalday = date("d",$assign_Data);

				    									$second_date = strtotime("-"."7"." day", $assign_Data);
				    									$firstend_week = date('Y-m-d H:i:s', $second_date);
				    									$assign_newdata = strtotime($firstend_week);		
                    									$secondval = date("F",$assign_newdata);
									                    $secondvalday = date("d",$assign_newdata);
									
									                    $third_date = strtotime("-"."7"." day", $assign_newdata);
													    $thirdend_week = date('Y-m-d H:i:s', $third_date);
													    $assignthird_newdata = strtotime($thirdend_week);		
									                    $thirddval = date("F",$assignthird_newdata);
									                    $thirdvalday = date("d",$assignthird_newdata);
									                    
									                    $fourth_date = strtotime("-"."7"." day", $assignthird_newdata);
													    $fourthnd_week = date('Y-m-d H:i:s', $fourth_date);
													    $assignfourth_newdata = strtotime($fourthnd_week);		
                    									$fourthval = date("F",$assignfourth_newdata);
									                    $fourthvalday = date("d",$assignfourth_newdata);

												?>
													<option value="val1" selected="selected"><?php echo $firstval; ?>, <?php echo $firstvalday; ?> - <?php echo $firstenddate; ?>, <?php echo $first_end_day; ?></option>
													
												</optgroup>
											</select>
										</div>
									</form>
			                	</div>
							</div>
							<?php
			
							

							?>

							<div class="container-fluid">
								<div class="row text-center">
									<div class="col-md-4">
										<div class="content-group">
											<h5 class="text-semibold no-margin"><i class="icon-calendar5 position-left text-slate"></i> <?php if($last_weeklydep_rec == '') { echo $currency_info->currency_symbol." ".number_format("0", $currency_info->deimal_point, '.', '').' '.strtoupper($currency_info->currency_unit);} else { echo $currency_info->currency_symbol." ".number_format($last_weeklydep_rec, $currency_info->deimal_point, '.', '').' '.strtoupper($currency_info->currency_unit); } ?></h5>
											<span class="text-muted text-size-small"><?php echo lang('language_lang.weekly_deposits'); ?></span>
										</div>
									</div>

									<div class="col-md-4">
										<div class="content-group">
											<h5 class="text-semibold no-margin"><i class="icon-calendar52 position-left text-slate"></i> <?php if($last_dep_rec == '') { echo $currency_info->currency_symbol."".number_format("0", $currency_info->deimal_point, '.', '').' '.strtoupper($currency_info->currency_unit);} else { echo $currency_info->currency_symbol."".number_format($last_dep_rec, $currency_info->deimal_point, '.', '').' '.strtoupper($currency_info->currency_unit); } ?></h5>
											<span class="text-muted text-size-small"><?php echo lang('language_lang.monthly_deposits'); ?></span>
										</div>
									</div>

									<div class="col-md-4">
										<div class="content-group">
											<h5 class="text-semibold no-margin"><i class="icon-cash3 position-left text-slate"></i> <?php if($total_deposit_amnt == '') { echo $currency_info->currency_symbol."".number_format("0", $currency_info->deimal_point, '.', '').' '.strtoupper($currency_info->currency_unit);} else { echo $currency_info->currency_symbol."".number_format($total_deposit_amnt, $currency_info->deimal_point, '.', '').' '.strtoupper($currency_info->currency_unit); } ?></h5>
											<span class="text-muted text-size-small"><?php echo lang('language_lang.total_deposits'); ?></span>
										</div>
									</div>
								</div>
							</div>
							<br/>

														<div class="container-fluid">
								<div class="row text-center">
									<div class="col-md-4">
										<div class="content-group">
											<h5 class="text-semibold no-margin"><i class="icon-calendar5 position-left text-slate"></i> <?php if($last_weeklywithdraw_rec == '') { echo $currency_info->currency_symbol." ".number_format("0", $currency_info->deimal_point, '.', '').' '.strtoupper($currency_info->currency_unit);} else { echo $currency_info->currency_symbol." ".number_format($last_weeklywithdraw_rec, $currency_info->deimal_point, '.', '').' '.strtoupper($currency_info->currency_unit); } ?></h5>
											<span class="text-muted text-size-small"><?php echo "Weekly Withdrawals" ?></span>
										</div>
									</div>

									<div class="col-md-4">
										<div class="content-group">
											<h5 class="text-semibold no-margin"><i class="icon-calendar52 position-left text-slate"></i> <?php if($last_withdraw_rec == '') { echo $currency_info->currency_symbol."".number_format("0", $currency_info->deimal_point, '.', '').' '.strtoupper($currency_info->currency_unit);} else { echo $currency_info->currency_symbol."".number_format($last_withdraw_rec, $currency_info->deimal_point, '.', '').' '.strtoupper($currency_info->currency_unit); } ?></h5>
											<span class="text-muted text-size-small"><?php echo "Monthly Withdrawals" ?></span>
										</div>
									</div>

									<div class="col-md-4">
										<div class="content-group">
											<h5 class="text-semibold no-margin"><i class="icon-cash3 position-left text-slate"></i> <?php if($total_withdraw_amnt == '') { echo $currency_info->currency_symbol."".number_format("0", $currency_info->deimal_point, '.', '').' '.strtoupper($currency_info->currency_unit);} else { echo $currency_info->currency_symbol."".number_format($total_withdraw_amnt, $currency_info->deimal_point, '.', '').' '.strtoupper($currency_info->currency_unit); } ?></h5>
											<span class="text-muted text-size-small"><?php echo "Total Withdrawals" ?></span>
										</div>
									</div>
								</div>
							</div>

							<div style="margin-top: 85px;" class="content-group-sm" id="app_sales"></div>
						</div>
						<!-- /sales stats -->

					</div>
				</div>
				<!-- /main charts -->


				<!-- Dashboard content -->
				<div class="row">
					<div class="col-lg-8">

						<!-- Marketing campaigns -->
						<div class="panel panel-flat">
							<div class="panel-heading">
								<h6 class="panel-title"><?php echo lang('language_lang.menu_transaction'); ?></h6>
								<div class="heading-elements">
			                	</div>
							</div>



							<div class="table-responsive">
								<table class="table table-lg text-nowrap">
									<tbody>
										<tr>
											<td class="col-md-5">
												<div class="media-left">
													<div id="campaigns-donut"></div>
												</div>

												<div class="media-left">
													<h5 class="text-semibold no-margin"><?php echo $currency_info->currency_symbol."".number_format($total_deposit_amnt, $currency_info->deimal_point, '.', '').' '.strtoupper($currency_info->currency_unit); ?> <small class="text-success text-size-base"><i class="icon-arrow-up12"></i> (+<?php echo $tot_amnt_percent;?>%)</small></h5>
													<ul class="list-inline list-inline-condensed no-margin">
														<li>
															<span class="status-mark border-success"></span>
														</li>
														<li>
															<span class="text-muted"><?php echo lang('language_lang.profile_lbl_deposit'); ?></span>
														</li>
													</ul>
												</div>
											</td>

											<td class="col-md-5" style="display:none;">
												<div class="media-left">
													<div id="campaign-status-pie"></div>
												</div>

												<div class="media-left">
													<h5 class="text-semibold no-margin"><?php echo $currency_info->currency_symbol."".number_format($total_earning_amnt, $currency_info->deimal_point, '.', '').' '.strtoupper($currency_info->currency_unit); ?> <small class="text-danger text-size-base"><i class="icon-arrow-down12"></i> (+<?php echo $tot_earn_percent; ?>%)</small></h5>
													<ul class="list-inline list-inline-condensed no-margin">
														<li>
															<span class="status-mark border-danger"></span>
														</li>
														<li>
															<span class="text-muted"><?php echo lang('language_lang.profile_lbl_earnings'); ?></span>
														</li>
													</ul>
												</div>
											</td>

											<td class="text-right col-md-2">
												<a href="<?php echo base_url()."/admin/history/deposit"; ?>" class="btn bg-indigo-300"><i class="icon-statistics position-left"></i> View report</a>
											</td>
										</tr>
									</tbody>
								</table>	
							</div>

							<div class="table-responsive">
								<table class="table text-nowrap">
									<thead>
										<tr>
											<th><?php echo lang('language_lang.lbl_user_name');?></th>
											<th class="col-md-2"><?php echo lang('language_lang.lbl_transaction_id');?></th>
											<th class="col-md-2"><?php echo lang('language_lang.lbl_payment_gateway');?></th>
											<th class="col-md-2"><?php echo lang('language_lang.lbl_amount')/*. ' (<b>'.strtoupper($currency_info->currency_unit).'</b>)'*/;?></th>
											<th class="col-md-2"><?php echo lang('language_lang.lbl_type');?></th>
											<th class="text-center" style="width: 20px;"><i class="icon-arrow-down12"></i></th>
										</tr>
									</thead>
									<tbody>
										<tr class="active border-double">
											<td colspan="5"></td>
											<td class="text-right">
												<span class="progress-meter" id="today-progress" data-progress="30"></span>
											</td>
										</tr>
										<?php   

                                                use App\Models\finance_model;

											if($all_lasttransaction) { 
												$i=1; 
												foreach ($all_lasttransaction as $row) {
                                            	$condition = "payment_key in('status') AND payment_id = '".$row->payment_id."'";


                                                $this->finance_model = model('finance_model');
											   	$payment = $this->finance_model->PaymentName($condition);
											   	if($payment) {
										   			$payment_name = ucfirst($payment->payment_name);
										   		} else {
										   			$payment_name = '----';
										   		}

											   	if($row->uusersid == '0'){
											   		$email = 'Admin';
											   	}
											   	else
											   	{
											   		$user_condition = "uusersid = '".$row->uusersid."'";
											   		$email1 = $this->common_model->GetRow('uusers',$user_condition);
											   		if($email1)
											   			$email = $email1->email;
											   		else
											   			$email = '';
											   	}

											   	if($i == '1') {
                                                	$class1 = "label bg-pink";
                                                	$class2 = "text-pink-600";
										        }
										        elseif ($i == '2') {
	                                                $class1 = "label bg-success";
	                                                $class2 = "text-success-600";
										        }
										        elseif ($i == '3') {
	                                                $class1 = "label bg-warning";
	                                                $class2 = "text-warning-600";
										        }
										        elseif($i == '4'){
										        	$class1 = "label bg-blue";
	                                                $class2 = "text-primary-600";
										        }
										        else{
	                                                $class1 = "label bg-teal";
	                                                $class2 = "text-teal-600";
										        }

										        $currency = $row->currency;
										        $coin   = $this->db->query("select * from coin_info where coid = '".$currency."'");
												$coin_sym = $coin->getResult();										        

												

											?>
											
										
										<tr>
											<td>
												<div class="media-left media-middle">
													<a style="cursor:default;"><img src="<?php echo site_url('styles/img/usr.png');?>" class="img-circle img-xs" alt=""></a>
												</div>
												<div class="media-left">
													<div class=""><a style="cursor:default;" class="<?php echo $class2; ?> text-semibold"><?php echo ucfirst($email);?></a></div>
													<div class="text-muted text-size-small">
														<span class="status-mark border-blue position-left"></span>
														<?php echo date('Y-m-d H:i:s', strtotime($row->date));?>
													</div>
												</div>
											</td>
											<td><span class="text-muted"><?php echo $row->transactionid;?></span></td>
											<td><span class="<?php echo $class2; ?>"><i class="icon-stats-growth2 position-left"></i> <?php echo $payment_name;?></span></td>
											<td><h6 class="text-semibold"><?php echo $row->amount.' '.$coin_sym[0]->coin_symbol;?></h6></td>
											<td><span class="<?php echo $class1; ?>"><?php echo humanize($row->type);?></span></td>
											<td class="text-center">
												<span class="status-mark border-indigo position-left"></span>
											</td>
										</tr>
                                       <?php $i++; } } ?>

										<tr class="active border-double">
											<td colspan="5"></td>
											<td class="text-right">
												<span class="progress-meter" id="yesterday-progress" data-progress="65"></span>
											</td>
										</tr>

										<?php 
											if($last_transaction) 
											{ 
												$i=1; 
												foreach ($last_transaction as $row) 
												{ 
													// pr($row);
                                               		$condition = "payment_key in('status') AND payment_id = '".$row->payment_id."'";
											   		$payment = $this->finance_model->PaymentName($condition);
											   		if($payment) {
											   			$payment_name = ucfirst($payment->payment_name);
											   		} else {
											   			$payment_name = '';
											   		}


												    if($row->uusersid == '0'){
												   		$email = 'Admin';
												   	}
												   	else
												   	{
														$user_condition = "uusersid = '".$row->uusersid."'";
													   	$email1 = $this->common_model->GetRow('uusers',$user_condition);
													   	if($email1) {
													   		$email = $email1->email;
													   	}
												   	}

												    if($i == '1')
												    {
		                                                $class1 = "label bg-warning";
		                                                $class2 = "text-warning-600";
											        }
											        elseif ($i == '2') 
											        {
		                                                $class1 = "label bg-pink";
		                                                $class2 = "text-pink-600";
											        }
											        elseif ($i == '3')
											        {
		                                                $class1 = "label bg-blue";
		                                                $class2 = "text-primary-600";
											        }
											        elseif($i == '4')
											        {
											        	$class1 = "label bg-success";
		                                                $class2 = "text-success-600";
											        }
											        else
											        {
		                                                $class1 = "label bg-teal";
		                                                $class2 = "text-teal-600";
											        }

											        $cur=$row->currency;
					                            if($cur=='1')
					                            	$curr_name="USD";
					                            else if($cur=='2')
					                               $curr_name='BTC';
					                            else if($cur=='3')
					                            	$curr_name='ETH';
					                            else
					                            	$curr_name=strtoupper($currency_info->currency_unit);


					                             $currency = $row->currency;
										        $coin   = $this->db->query("select * from coin_info where coid = '".$currency."'");
												$coin_sym = $coin->getResult();		

											?>
													<tr>
														<td>
															<div class="media-left media-middle">
																<a style="cursor:default;"><img src="styles/img/usr.png" class="img-circle img-xs" alt=""></a>
															</div>
															<div class="media-left">
																<div class=""><a style="cursor:default;" class="<?php echo $class2;?> text-semibold"><?php echo ucfirst($email);?></a></div>
																<div class="text-muted text-size-small">
																	<span class="status-mark border-blue position-left"></span>
																	<?php echo date('Y-m-d H:i:s', strtotime($row->date));?>
																</div>
															</div>
														</td>
														<td><span class="text-muted"><?php echo $row->transactionid;?></span></td>
														<td><span class="<?php echo $class2; ?>"><i class="icon-stats-growth2 position-left"></i> <?php echo $payment_name;?></span></td>
														<td><?php echo $row->amount.' '.$coin_sym[0]->coin_symbol;?></td>
														<td><span class="<?php echo $class1; ?>"><?php echo humanize($row->type);?></span></td>
														<td class="text-center">
															<span class="status-mark border-teal position-left"></span>
														</td>
													</tr>
                                        <?php 
                                        			$i++; 
                                        		} 
                                        	} 
                                        ?>

									</tbody>
								</table>
							</div>
						</div>
						<!-- /marketing campaigns -->


						<!-- Quick stats boxes -->
						<div class="row">
							<div class="col-lg-4">

								<!-- Members online -->
								<div class="panel bg-teal-400">
									<div class="panel-body">
										<div class="heading-elements">
										<ul class="icons-list">
						                		<li><a data-action="reload"></a></li>
                                       
										</ul>
										</div>

										<h3 class="no-margin"><?php if($total_accounts == '') { echo "0"; } else { echo $total_accounts; } ?></h3>
										<?php echo lang('language_lang.site_totacc_lbl'); ?>
										<div class="text-muted text-size-small"></div>
									</div>

									<div class="container-fluid">
										<div id="members-online"></div>
									</div>
								</div>
								<!-- /members online -->

							</div>

							<div class="col-lg-4">

								<!-- Current server load -->
								<div class="panel bg-pink-400">
									<div class="panel-body">
										<div class="heading-elements">
											<ul class="icons-list">
						                		<li class="dropdown">
						                			<i class="icon-cog3"></i> 
													
						                		</li>
						                	</ul>
										</div>

										<h3 class="no-margin"><?php if($usercount == '') { echo "0"; } else { echo $usercount; } ?></h3>
										<?php echo lang('language_lang.dash_log_admin'); ?>
										<div class="text-muted text-size-small"></div>
									</div>

									<div id="server-load"></div>
								</div>
								<!-- /current server load -->

							</div>

							<div class="col-lg-4">

								<!-- Today's revenue -->
								<div class="panel bg-blue-400">
									<div class="panel-body">
										<div class="heading-elements">
											<ul class="icons-list">
						                		<li><a data-action="reload"></a></li>
						                	</ul>
					                	</div>

										<h3 class="no-margin"><?php echo $currency_info->currency_symbol."".number_format($today_deposit_amnt, $currency_info->deimal_point, '.', '');?></h3>
										<?php echo lang('language_lang.site_todayde_lbl'); ?>
										<div class="text-muted text-size-small"></div>
									</div>

									<div id="today-revenue"></div>
								</div>
								<!-- /today's revenue -->

							</div>
						</div>
						<!-- /quick stats boxes -->


						<!-- Support tickets -->
						<div class="panel panel-flat">
							<div class="panel-heading">
								<h6 class="panel-title"><?php echo lang('language_lang.dash_supp_tikts'); ?></h6>
								<div class="heading-elements">
									
			                	</div>
							</div>

							<div class="table-responsive">
								<table class="table table-xlg text-nowrap">
									<tbody>
										<tr>
											<td class="col-md-4">
												<div class="media-left media-middle">
													<div id="tickets-status"></div>
												</div>

												<div class="media-left">
													<h5 class="text-semibold no-margin"><?php if($new_ticket_count == '') { echo "0"; } else { echo $new_ticket_count; } ?> <small class="text-success text-size-base"><i class="icon-arrow-up12"></i></small></h5>
													<span class="text-muted"><span class="status-mark border-success position-left"></span><?php echo lang('language_lang.dash_new_tikts'); ?> </span>
												</div>
											</td>

											<td class="col-md-3">
												<div class="media-left media-middle">
													<a href="#" class="btn border-indigo-400 text-indigo-400 btn-flat btn-rounded btn-xs btn-icon"><i class="icon-alarm-add"></i></a>
												</div>

												<div class="media-left">
													<h5 class="text-semibold no-margin">
														<?php if($tot_tickets == '') { echo "0"; } else { echo $tot_tickets; } ?> <small class="display-block no-margin"><?php echo lang('language_lang.dash_tot_tikts'); ?></small>
													</h5>
												</div>
											</td>

											<td class="col-md-3">
												<div class="media-left media-middle">
													<a href="#" class="btn border-indigo-400 text-indigo-400 btn-flat btn-rounded btn-xs btn-icon"><i class="icon-spinner11"></i></a>
												</div>

												<div class="media-left">
													<h5 class="text-semibold no-margin">
														<?php if($reopen_ticket_count == '') { echo "0"; } else { echo $reopen_ticket_count; } ?><small class="display-block no-margin"><?php echo lang('language_lang.dash_resp_tikts'); ?></small>
													</h5>
												</div>
											</td>

											<td class="text-right col-md-2">
												<a href="<?php echo base_url()."/admin/support"; ?>" class="btn bg-teal-400"><i class="icon-statistics position-left"></i> <?php echo lang('language_lang.menu_reports'); ?></a>
											</td>
										</tr>
									</tbody>
								</table>	
							</div>

							<div class="table-responsive">
								<table class="table text-nowrap">
									<thead>
										<tr>
											<th style="width: 50px"><?php echo lang('language_lang.trans_date'); ?></th>
											<th style="width: 300px;"><?php echo lang('language_lang.plac_smtp_username'); ?></th>
											<th><?php echo lang('language_lang.lbl_mail_message'); ?></th>
											<th class="text-center" style="width: 20px;"><i class="icon-arrow-down12"></i></th>
										</tr>
									</thead>
									<tbody>
										<tr class="active border-double">
											<td colspan="3"><?php echo lang('language_lang.dash_new_tikts'); ?></td>
											<td class="text-right">
												<span class="badge bg-blue"><?php echo $new_ticket_count; ?></span>
											</td>
										</tr>

										<?php if($new_ticket_list) { $i=1; foreach ($new_ticket_list as $row) {

											// $this->load->library('MyEncrypt');
											$myencrypt = new MyEncrypt;

											$condition = "uusersid = '".$row->uusers_id."'";
									        $email = $this->common_model->GetRow('uusers',$condition);

									        if($i%2 == '0'){
                                                $class = "bg-blue";
									        }
									        else{
									        	$class = "bg-teal-400";
									        }
											
										?>

										<tr>
											<td class="text-center">
												<small class="display-block text-size-small no-margin"><?php echo $row->post_date; ?></small>
											</td>
											<td>
												<div class="media-left media-middle">
													<a href="<?php echo base_url()."/admin/support"; ?>" class="btn <?php echo $class; ?> btn-rounded btn-icon btn-xs">
														<span class="letter-icon"><?php echo ucfirst($email->email[0]); ?></span>
													</a>
												</div>

												<div class="media-body">
													<a href="<?php echo base_url()."/admin/support"; ?>" class="display-inline-block text-default text-semibold letter-icon-title"><?php echo ucfirst($email->email); ?></a>
													<div class="text-muted text-size-small"><span class="status-mark border-blue position-left"></span> <?php echo ucfirst($row->ticket_status); ?></div>
												</div>
											</td>
											<td>
												<a href="<?php echo base_url()."/admin/support"; ?>" class="text-default display-inline-block">
													<span class="text-semibold"><?php echo ucfirst(substr($row->message, 0, 80)); ?></span>
												</a>
											</td>
											<td class="text-center">
												<ul class="icons-list">
													<li class="dropdown">
														<a href="<?php echo base_url()."/admin/support"; ?>" class="dropdown-toggle" data-toggle="dropdown"><i class="icon-menu7"></i></a>
														<ul class="dropdown-menu dropdown-menu-right">
															<li><a href="<?php echo base_url()."/admin/support/ticketdetails/".$myencrypt->encode($row->ticket_no); ?>"><i class="icon-undo"></i> <?php echo lang('language_lang.dash_quick_reply'); ?></a></li>
															<li><a href="<?php echo base_url()."/admin/support/ticketdetails/".$myencrypt->encode($row->ticket_no); ?>"><i class="icon-history"></i> <?php echo lang('language_lang.dash_fullhistory_reply'); ?></a></li>
														</ul>
													</li>
												</ul>
											</td>
										</tr>

										<?php $i++; } } ?>
										<tr class="active border-double">
											<td colspan="3"><?php echo lang('language_lang.dash_resp_tikts'); ?></td>
											<td class="text-right">
												<span class="badge bg-success"><?php echo $reopen_ticket_count; ?></span>
											</td>
										</tr>

										<?php if($reopen_ticket_list) { $i=1; 
											// $this->load->library('MyEncrypt');
											$myencrypt = new MyEncrypt; foreach ($reopen_ticket_list as $row) {

											$condition = "uusersid = '".$row->uusers_id."'";
									        $email = $this->common_model->GetRow('uusers',$condition);
											
											if($i%2 == '0'){
                                                $class = "bg-pink-400";
									        }
									        else{
									        	$class = "bg-success-400";
									        }
										?>


										<tr>
											<td class="text-center">
												<i class="icon-checkmark3 text-success"></i>
											</td>
											<td>
												<div class="media-left media-middle">
													<a href="<?php echo base_url()."admin/support"; ?>" class="btn <?php echo $class; ?> btn-rounded btn-icon btn-xs">
														<span class="letter-icon"><?php echo ucfirst($email->email[0]); ?></span>
													</a>
												</div>

												<div class="media-body">
													<a href="<?php echo base_url()."admin/support"; ?>" class="display-inline-block text-default letter-icon-title"><?php echo ucfirst($email->email); ?></a>
													<div class="text-muted text-size-small"><span class="status-mark border-success position-left"></span> <?php echo ucfirst($row->ticket_status); ?></div>
												</div>
											</td>
											<td>
												<a href="<?php echo base_url()."admin/support"; ?>" class="text-default display-inline-block"><?php echo ucfirst(substr($row->message, 0, 805)); ?></a>
											</td>
											<td class="text-center">
												<ul class="icons-list">
													<li class="dropdown">
														<a href="<?php echo base_url()."admin/support"; ?>" class="dropdown-toggle" data-toggle="dropdown"><i class="icon-menu7"></i></a>
														<ul class="dropdown-menu dropdown-menu-right">
															<li><a href="<?php echo base_url()."admin/support/ticketdetails/".$myencrypt->encode($row->ticket_no); ?>"><i class="icon-undo"></i> <?php echo lang('language_lang.dash_quick_reply'); ?></a></li>
															<li><a href="<?php echo base_url()."admin/support/ticketdetails/".$myencrypt->encode($row->ticket_no); ?>"><i class="icon-history"></i> <?php echo lang('language_lang.dash_fullhistory_reply'); ?></a></li>
														</ul>
													</li>
												</ul>
											</td>
										</tr>

										<?php $i++; } } ?>

										<tr class="active border-double">
											<td colspan="3"><?php echo lang('language_lang.dash_closed_tickets'); ?></td>
											<td class="text-right">
												<span class="badge bg-danger"><?php echo $close_ticket_count; ?></span>
											</td>
										</tr>

                                        <?php if($close_ticket_list) { $i=1; 
                                        	// $this->load->library('MyEncrypt');
											$myencrypt = new MyEncrypt; foreach ($close_ticket_list as $row) {

											$condition = "uusersid = '".$row->uusers_id."'";
									        $email = $this->common_model->GetRow('uusers',$condition);

									        if($i%2 == '0'){
                                                $class = "bg-brown-400";
									        }
									        else{
									        	$class = "bg-danger-400";
									        }
											
										?>

										<tr>
											<td class="text-center">
												<i class="icon-cross2 text-danger-400"></i>
											</td>
											<td>
												<div class="media-left media-middle">
													<a href="<?php echo base_url()."admin/support"; ?>" class="btn <?php echo $class; ?> btn-rounded btn-icon btn-xs">
														<span class="letter-icon"><?php echo ucfirst($email->email[0]); ?></span>
													</a>
												</div>

												<div class="media-body">
													<a href="<?php echo base_url()."admin/support"; ?>" class="display-inline-block text-default"><?php echo $email->email; ?></a>
													<div class="text-muted text-size-small"><span class="status-mark border-danger position-left"></span> <?php echo ucfirst($row->ticket_status); ?></div>
												</div>
											</td>
											<td>
												<a href="<?php echo base_url()."admin/support"; ?>" class="text-default display-inline-block">
													<?php echo ucfirst(substr($row->message, 0, 805)); ?>
												</a>
											</td>
											<td class="text-center">
												<ul class="icons-list">
													<li class="dropdown">
														<a href="<?php echo base_url()."admin/support"; ?>" class="dropdown-toggle" data-toggle="dropdown"><i class="icon-menu7"></i></a>
														<ul class="dropdown-menu dropdown-menu-right">
															<li><a href="<?php echo base_url()."admin/support/ticketdetails/".$myencrypt->encode($row->ticket_no); ?>"><i class="icon-undo"></i> <?php echo lang('language_lang.dash_quick_reply'); ?></a></li>
															<li><a href="<?php echo base_url()."admin/support/ticketdetails/".$myencrypt->encode($row->ticket_no); ?>"><i class="icon-history"></i> <?php echo lang('language_lang.dash_fullhistory_reply'); ?></a></li>
														</ul>
													</li>
												</ul>
											</td>
										</tr>

										<?php $i++; } } ?>

									</tbody>
								</table>
							</div>
						</div>
						<!-- /support tickets -->


						<!-- Latest posts -->
						<div class="panel panel-flat">
							<div class="panel-heading">
								<h6 class="panel-title"><?php echo lang('language_lang.dash_latest_news'); ?></h6>
								<div class="heading-elements">
									<ul class="icons-list">
				                		<li><a data-action="collapse"></a></li>
				                		<li><a data-action="reload"></a></li>
				                		<li><a data-action="close"></a></li>
				                	</ul>
			                	</div>
		                	</div>

							<div class="panel-body">
								<div class="row">
									<div class="col-lg-6">
										<ul class="media-list content-group">

										<?php 
										if($news) 
										{ 
											// $this->load->library('MyEncrypt');
											$myencrypt = new MyEncrypt; 
											foreach ($news as $news_row) 
											{  
												$news_date = date("jS F Y", strtotime($news_row->news_date));
	                                            $news_date = str_replace('st', '<sup>st</sup>', $news_date);
	                                            $news_date = str_replace('nd', '<sup>nd</sup>', $news_date);
	                                            $news_date = str_replace('rd', '<sup>rd</sup>', $news_date);
	                                            $news_date = str_replace('th', '<sup>th</sup>', $news_date);?>
											
												<li class="media stack-media-on-mobile">
				                					<div class="media-left">
														<div class="thumb">
															<a href="<?php echo base_url()."/admin/news/edit/".$myencrypt->encode($news_row->news_id); ?>">
																<img src="styles/img/grp02.png" class="img-responsive img-rounded media-preview" alt="">
															</a>
														</div>
													</div>
	                                              
				                					<div class="media-body">
														<h6 class="media-heading"><a href="<?php echo base_url()."/admin/news/edit/".$myencrypt->encode($news_row->news_id); ?>"><?php echo strtoupper($news_row->news_header);?></a></h6>
							                    		<ul class="list-inline list-inline-separate text-muted mb-5">
							                    			<li><?php echo $news_date;?></li>
							                    		</ul>
														<?php echo ucfirst(substr($news_row->news_content, 0, 30));?>
													</div>
												</li>
											<?php } } else {
												echo lang('language_lang.lbl_no_records');
												} ?>

											
										</ul>
									</div>

									<div class="col-lg-6">
										<ul class="media-list content-group">

										<?php 
										if($newslist) 
										{ 
											// $this->load->library('MyEncrypt');
											$myencrypt = new MyEncrypt; 
											foreach ($newslist as $news_row) 
											{  
												$news_date = date("jS F Y", strtotime($news_row->news_date));
	                                            $news_date = str_replace('st', '<sup>st</sup>', $news_date);
	                                            $news_date = str_replace('nd', '<sup>nd</sup>', $news_date);
	                                            $news_date = str_replace('rd', '<sup>rd</sup>', $news_date);
	                                            $news_date = str_replace('th', '<sup>th</sup>', $news_date);
	                                    ?>
											
												<li class="media stack-media-on-mobile">
				                					<div class="media-left">
														<div class="thumb">
															<a href="<?php echo base_url()."/admin/news/edit/".$myencrypt->encode($news_row->news_id); ?>">
																<img src="styles/img/grp04.png" class="img-responsive img-rounded media-preview" alt="">
															</a>
														</div>
													</div>
	                                              
				                					<div class="media-body">
														<h6 class="media-heading"><a href="<?php echo base_url()."/admin/news/edit/".$myencrypt->encode($news_row->news_id); ?>"><?php echo strtoupper($news_row->news_header);?></a></h6>
							                    		<ul class="list-inline list-inline-separate text-muted mb-5">
							                    			<li><?php echo $news_date;?></li>
							                    		</ul>
														<?php echo ucfirst(substr($news_row->news_content, 0, 30));?>
													</div>
												</li>
											<?php } } ?>

											
										</ul>
									</div>
								</div>
							</div>
						</div>
						<!-- /latest posts -->

					</div>

					<div class="col-lg-4">

						<!-- Progress counters -->
						<div class="row">
							<div class="col-md-6">

								<!-- Available hours -->
								<div class="panel text-center">
									<div class="panel-body">
										<div class="heading-elements">
											<ul class="icons-list">
						                		<li class="dropdown text-muted">
						                			<i class="icon-cog3"></i>
						                		</li>
						                	</ul>
					                	</div>

					                	<!-- Progress counter -->
										<div class="content-group-sm svg-center position-relative" id="hours-available-progress"></div>
										<!-- /progress counter -->


										<!-- Bars -->
										<div id="hours-available-bars"></div>
										<!-- /bars -->

									</div>
								</div>
								<!-- /available hours -->

							</div>

							<div class="col-md-6">

								<!-- Productivity goal -->
								<div class="panel text-center">
									<div class="panel-body">
										<div class="heading-elements">
											<ul class="icons-list">
						                		<li class="dropdown text-muted">
						                			<i class="icon-cog3"></i>
						                		</li>
						                	</ul>
										</div>

										<!-- Progress counter -->
										<div class="content-group-sm svg-center position-relative" id="goal-progress"></div>
										<!-- /progress counter -->

										<!-- Bars -->
										<div id="goal-bars"></div>
										<!-- /bars -->

									</div>
								</div>
								<!-- /productivity goal -->

							</div>
						</div>
						<!-- /progress counters -->


						<!-- Daily sales -->
						<div class="panel panel-flat">
							<div class="panel-heading">
								<h6 class="panel-title">Montly Bot Activation Earnings</h6>
								<div class="heading-elements">
									
								</div>
							</div>
							<?php 
							$db = db_connect();
							if($user_group=='1')
							    $activation_by_month = $db->query("select year(date) as year,month(date) as month,sum(amount) as amount from history where type='activation' and user_group='0' group by year(date),month(date) order by year(date),month(date) desc")->getResult();
							else if($user_group=='2')
							    $activation_by_month = $db->query("select year(date) as year,month(date) as month,sum(amount) as amount from history where type='activation' and user_group='1' group by year(date),month(date) order by year(date),month(date) desc")->getResult();
							else
							    $activation_by_month = $db->query("select year(date) as year,month(date) as month,sum(amount) as amount from history where type='activation' group by year(date),month(date) order by year(date),month(date) desc")->getResult();
                            ?>


							<div class="table-responsive">
								<table class="table text-nowrap">
									<thead>
										<tr>
											<!-- <th><?php echo lang('language_lang.lbl_user_name');?></th> -->
											<th><?php echo "Transaction Month";?></th>
											<th><?php echo lang('language_lang.lbl_amount');?></th>
										</tr>
									</thead>
									<tbody>
									<?php if($activation_by_month) { $i=1; foreach ($activation_by_month as $row) {

											   $user_condition = "uusersid = '".$row->uusersid."'";
											   $email = $this->common_model->GetRow('uusers',$user_condition);

											     if($i == '1'){
                                                $class = "btn bg-primary-400 btn-rounded btn-icon btn-xs";
                                                

									        }
									        elseif ($i == '2') {
									        	$class = "btn bg-indigo-400 btn-rounded btn-icon btn-xs";
                                                

									        }elseif ($i == '3') {
									        	$class = "btn bg-teal-400 btn-rounded btn-icon btn-xs";
                                                

									        
									        }elseif($i == '4'){

									        	$class = "btn bg-warning-400 btn-rounded btn-icon btn-xs";
									        	

									        }else{
									        	$class = "btn bg-success-400 btn-rounded btn-icon btn-xs";
                                                

									        }
											
											?>
										<tr>
				                            <td>
												<h6 class="<?php echo $class;?>"><?php echo $row->year.'-'.$row->month;?></h6>
											</td>
											<td>
												<h6 class="<?php echo $class;?>"><?php echo $row->amount.' USDT';?></h6>
											</td>
										</tr>

										<?php $i++; } } ?>
										
									</tbody>
								</table>
							</div>
						</div>
						<!-- /daily sales -->


						<!-- Last Payouts -->
						<div class="panel panel-flat">
							<div class="panel-heading">
								<h6 class="panel-title"><?php echo lang('language_lang.menu_payouts'); ?></h6>
								
							</div>

						
							<!-- /tabs -->
							<div class="table-responsive">
								<table class="table text-nowrap">
									<thead>
										<tr class="bg-indigo-400">
											<th><?php echo lang('language_lang.lbl_user_name');?></th>
											<th><?php echo lang('language_lang.lbl_trans_date');?></th>
											<th><?php echo lang('language_lang.lbl_amount');?></th>
										</tr>
									</thead>
									<tbody>
									<?php 
										if($last_payouts) 
										{ 
											foreach ($last_payouts as $row) 
											{

												$coid=$row->currency;
												$find_cur=$this->db->query("select * from coin_info where coid='".$coid."'");
												$us_cur=$find_cur->getResult();
												$coin_symbol=strtoupper($us_cur[0]->coin_symbol);
												$user_condition = "uusersid = '".$row->uusersid."'";
											   	$email = $this->common_model->GetRow('uusers',$user_condition);
											
											?>
										<tr>
											<td>
												<div class="media-left media-middle">
													<a style="cursor:default;" class="<?php echo $class; ?>">
														<span class="letter-icon"><?php echo ucfirst(substr($email->email, 0, 1)); ?></span>
													</a>
												</div>

												<div class="media-body">
													<div class="media-heading">
														<a style="cursor:default;" class="letter-icon-title"><?php echo ucfirst($email->email); ?></a>
													</div>

													<div class="text-muted text-size-small"><i class="icon-checkmark3 text-size-mini position-left"></i> <?php echo humanize($row->type);?></div>
												</div>
											</td>
											<td>
												<span class="text-muted text-size-small"><?php echo date('Y-m-d H:i:s', strtotime($row->date));?></span>
											</td>
											<td>
												<h6 class="text-semibold no-margin" style='font-size:12px;'><?php  echo number_format($row->amount,$us_cur[0]->coin_decimal, '.', '');?> USDT</h6>
											</td>
										</tr>

									<?php 
											
											} 
										} else {
									?>
										<tr>
											<td colspan="3" class="text-center"><?php echo lang('language_lang.lbl_no_records');?></td>
										</tr>

									<?php
										}
									?>
										
									</tbody>
								</table>
							</div>


							<!-- Tabs content -->
							
							<!-- /tabs content -->

						</div>
						<!-- /Last Payouts -->




						

						<!-- Daily financials -->
						<div class="panel panel-flat">
							<div class="panel-heading">
								<h6 class="panel-title"><?php echo lang('language_lang.dash_log_admin'); ?></h6>
								<div class="heading-elements">
								</div>
							</div>

							<div class="panel-body">
								

								<ul class="media-list">
								 <?php if($user_data) { $i=1; foreach ($user_data as $row) {

								 	
									$email = "Admin";

									        if($i == '1'){
                                                $class = "btn border-pink text-pink btn-flat btn-rounded btn-icon btn-xs";
                                                $class1 = "icon-statistics";
                                                $class2 = "text-pink-600";

									        }
									        elseif ($i == '2') {
									        	$class = "btn border-success text-success btn-flat btn-rounded btn-icon btn-xs";
                                                $class1 = "icon-checkmark3";
                                                $class2 = "text-success-600";

									        }elseif ($i == '3') {
									        	$class = "btn border-warning-400 text-warning-400 btn-flat btn-rounded btn-icon btn-xs";
                                                $class1 = "icon-spinner11";
                                                $class2 = "text-warning-600";

									        
									        }elseif($i == '4'){

									        	$class = "btn border-primary text-primary btn-flat btn-rounded btn-icon btn-xs";
									        	$class1 = "icon-alignment-unalign";
                                                $class2 = "text-primary-600";

									        }else{
									        	$class = "btn border-teal-400 text-teal btn-flat btn-rounded btn-icon btn-xs";
                                                $class1 = "icon-redo2";
                                                $class2 = "text-teal-600";

									        }
											
										?>

									<li class="media">
										<div class="media-left">
											<a href="<?php echo base_url().'/admin/checkip'; ?>" class="<?php echo $class; ?>"><i class="<?php echo $class1; ?>"></i></a>
										</div>
										
										<div class="media-body">
											<?php echo ucfirst($email); ?> <span class="<?php echo $class2; ?>"><i class="icon-stats-growth2 position-left"></i> <?php echo $row->uusers_ip; ?></span>
											<div class="media-annotation"><?php echo $row->lastaccess; ?></div>
										</div>

										<div class="media-right media-middle">
											<ul class="icons-list">
												<li>
							                    	<a href="" style="cursor:default;"><i class="icon-arrow-right13"></i></a>
						                    	</li>
					                    	</ul>
										</div>
									</li>

									<?php $i++; } } ?>
					                    	</ul>
										</div>
									</li>
								</ul>
							</div>
						</div>
						<!-- /daily financials -->


						


					</div>
				</div>
				<!-- /dashboard content -->

			</div>
			<!-- /main content -->

	
		<!-- /page content -->




		<!-- Footer -->
		</div>
		<div class="footer text-muted">
			<?php //echo site_footer();?>
		</div>
		<!-- /footer -->

	</div>
	<!-- /page container -->
		</div>

<script type="text/javascript">

jQuery.noConflict();
(function( $ ) {
$(function() {

	

// Initialize chart
    sparkline("#new-visitors", "line", 30, 35, "basis", 750, 2000, "#26A69A");
    sparkline("#new-sessions", "line", 30, 35, "basis", 750, 2000, "#FF7043");
    sparkline("#total-online", "line", 30, 35, "basis", 750, 2000, "#5C6BC0");
    sparkline("#server-load", "area", 30, 50, "basis", 750, 2000, "rgba(255,255,255,0.5)");
    sparkline("#server-load1", "area", 30, 50, "basis", 750, 2000, "rgba(255,255,255,0.5)");
    sparkline("#server-load2", "area", 30, 50, "basis", 750, 2000, "rgba(255,255,255,0.5)");
    sparkline("#server-load3", "area", 30, 50, "basis", 750, 2000, "rgba(100,100,225,0.5)");

    // Chart setup
    function sparkline(element, chartType, qty, height, interpolation, duration, interval, color) {


        // Basic setup
        // ------------------------------

        // Define main variables
        var d3Container = d3.select(element),
            margin = {top: 0, right: 0, bottom: 0, left: 0},
            width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
            // width = d3Container.node().width - margin.left - margin.right,
            height = height - margin.top - margin.bottom;


        // Generate random data (for demo only)
        var data = [];
        for (var i=0; i < qty; i++) {
            data.push(Math.floor(Math.random() * qty) + 5)
        }



        // Construct scales
        // ------------------------------

        // Horizontal
        var x = d3.scale.linear().range([0, width]);

        // Vertical
        var y = d3.scale.linear().range([height - 5, 5]);



        // Set input domains
        // ------------------------------

        // Horizontal
        x.domain([1, qty - 3])

        // Vertical
        y.domain([0, qty])
            


        // Construct chart layout
        // ------------------------------

        // Line
        var line = d3.svg.line()
            .interpolate(interpolation)
            .x(function(d, i) { return x(i); })
            .y(function(d, i) { return y(d); });

        // Area
        var area = d3.svg.area()
            .interpolate(interpolation)
            .x(function(d,i) { 
                return x(i); 
            })
            .y0(height)
            .y1(function(d) { 
                return y(d); 
            });



        // Create SVG
        // ------------------------------

        // Container
        var container = d3Container.append('svg');

        // SVG element
        var svg = container
            .attr('width', width + margin.left + margin.right)
            .attr('height', height + margin.top + margin.bottom)
            .append("g")
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")");



        // Add mask for animation
        // ------------------------------

        // Add clip path
        var clip = svg.append("defs")
            .append("clipPath")
            .attr('id', function(d, i) { return "load-clip-" + element.substring(1) })

        // Add clip shape
        var clips = clip.append("rect")
            .attr('class', 'load-clip')
            .attr("width", 0)
            .attr("height", height);

        // Animate mask
        clips
            .transition()
                .duration(1000)
                .ease('linear')
                .attr("width", width);



        //
        // Append chart elements
        //

        // Main path
        var path = svg.append("g")
            .attr("clip-path", function(d, i) { return "url(#load-clip-" + element.substring(1) + ")"})
            .append("path")
                .datum(data)
                .attr("transform", "translate(" + x(0) + ",0)");

        // Add path based on chart type
        if(chartType == "area") {
            path.attr("d", area).attr('class', 'd3-area').style("fill", color); // area
        }
        else {
            path.attr("d", line).attr("class", "d3-line d3-line-medium").style('stroke', color); // line
        }

        // Animate path
        path
            .style('opacity', 0)
            .transition()
                .duration(750)
                .style('opacity', 1);



        // Set update interval. For demo only
        // ------------------------------

        setInterval(function() {

            // push a new data point onto the back
            data.push(Math.floor(Math.random() * qty) + 5);

            // pop the old data point off the front
            data.shift();

            update();

        }, interval);



        // Update random data. For demo only
        // ------------------------------

        function update() {

            // Redraw the path and slide it to the left
            path
                .attr("transform", null)
                .transition()
                    .duration(duration)
                    .ease("linear")
                    .attr("transform", "translate(" + x(0) + ",0)");

            // Update path type
            if(chartType == "area") {
                path.attr("d", area).attr('class', 'd3-area').style("fill", color)
            }
            else {
                path.attr("d", line).attr("class", "d3-line d3-line-medium").style('stroke', color);
            }
        }



        // Resize chart
        // ------------------------------

        // Call function on window resize
        $(window).on('resize', resizeSparklines);

        // Call function on sidebar width change
        $('.sidebar-control').on('click', resizeSparklines);

        // Resize function
        // 
        // Since D3 doesn't support SVG resize by default,
        // we need to manually specify parts of the graph that need to 
        // be updated on window resize
        function resizeSparklines() {

            // Layout variables
            width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;


            // Layout
            // -------------------------

            // Main svg width
            container.attr("width", width + margin.left + margin.right);

            // Width of appended group
            svg.attr("width", width + margin.left + margin.right);

            // Horizontal range
            x.range([0, width]);


            // Chart elements
            // -------------------------

            // Clip mask
            clips.attr("width", width);

            // Line
            svg.select(".d3-line").attr("d", line);

            // Area
            svg.select(".d3-area").attr("d", area);
        }
    }




    // Initialize charts
    generateBarChart("#hours-available-bars", 24, 40, true, "elastic", 1200, 50, "#EC407A", false);
    generateBarChart("#goal-bars", 24, 40, true, "elastic", 1200, 50, "#5C6BC0", false);
    
    generateBarChart("#members-online", 24, 50, true, "elastic", 1200, 50, "rgba(255,255,255,0.5)", false);
    generateBarChart("#members-online1", 24, 50, true, "elastic", 1200, 50, "rgba(255,255,255,0.5)", false);
    generateBarChart("#members-online2", 24, 50, true, "elastic", 1200, 50, "rgba(255,255,255,0.5)", false);
  
    // Chart setup
    function generateBarChart(element, barQty, height, animate, easing, duration, delay, color, tooltip) {


        // Basic setup
        // ------------------------------

        // Add data set
        var bardata = [];
        for (var i=0; i < barQty; i++) {
            bardata.push(Math.round(Math.random()*10) + 10)
        }

        // Main variables
        var d3Container = d3.select(element),
            width = d3Container.node().getBoundingClientRect().width;
        


        // Construct scales
        // ------------------------------

        // Horizontal
        var x = d3.scale.ordinal()
            .rangeBands([0, width], 0.3)

        // Vertical
        var y = d3.scale.linear()
            .range([0, height]);



        // Set input domains
        // ------------------------------

        // Horizontal
        x.domain(d3.range(0, bardata.length))

        // Vertical
        y.domain([0, d3.max(bardata)])



        // Create chart
        // ------------------------------

        // Add svg element
        var container = d3Container.append('svg');

        // Add SVG group
        var svg = container
            .attr('width', width)
            .attr('height', height)
            .append('g');



        //
        // Append chart elements
        //

        // Bars
        var bars = svg.selectAll('rect')
            .data(bardata)
            .enter()
            .append('rect')
                .attr('class', 'd3-random-bars')
                .attr('width', x.rangeBand())
                .attr('x', function(d,i) {
                    return x(i);
                })
                .style('fill', color);



        // Tooltip
        // ------------------------------

        var tip = d3.tip()
            .attr('class', 'd3-tip')
            .offset([-10, 0]);

        // Show and hide
        if(tooltip == "hours" || tooltip == "goal" || tooltip == "members") {
            bars.call(tip)
                .on('mouseover', tip.show)
                .on('mouseout', tip.hide);
        }

        // Daily meetings tooltip content
        if(tooltip == "hours") {
            tip.html(function (d, i) {
                return "<div class='text-center'>" +
                        "<h6 class='no-margin'>" + d + "</h6>" +
                        "<span class='text-size-small'>meetings</span>" +
                        "<div class='text-size-small'>" + i + ":00" + "</div>" +
                    "</div>"
            });
        }

        // Statements tooltip content
        if(tooltip == "goal") {
            tip.html(function (d, i) {
                return "<div class='text-center'>" +
                        "<h6 class='no-margin'>" + d + "</h6>" +
                        "<span class='text-size-small'>statements</span>" +
                        "<div class='text-size-small'>" + i + ":00" + "</div>" +
                    "</div>"
            });
        }

        // Online members tooltip content
        if(tooltip == "members") {
            tip.html(function (d, i) {
                return "<div class='text-center'>" +
                        "<h6 class='no-margin'>" + d + "0" + "</h6>" +
                        "<span class='text-size-small'>members</span>" +
                        "<div class='text-size-small'>" + i + ":00" + "</div>" +
                    "</div>"
            });
        }

         if(tooltip == "memberss") {
            tip.html(function (d, i) {
                return "<div class='text-center'>" +
                        "<h6 class='no-margin'>" + d + "0" + "</h6>" +
                        "<span class='text-size-small'>members</span>" +
                        "<div class='text-size-small'>" + i + ":00" + "</div>" +
                    "</div>"
            });
        }



        // Bar loading animation
        // ------------------------------

        // Choose between animated or static
        if(animate) {
            withAnimation();
        } else {
            withoutAnimation();
        }

        // Animate on load
        function withAnimation() {
            bars
                .attr('height', 0)
                .attr('y', height)
                .transition()
                    .attr('height', function(d) {
                        return y(d);
                    })
                    .attr('y', function(d) {
                        return height - y(d);
                    })
                    .delay(function(d, i) {
                        return i * delay;
                    })
                    .duration(duration)
                    .ease(easing);
        }

        // Load without animateion
        function withoutAnimation() {
            bars
                .attr('height', function(d) {
                    return y(d);
                })
                .attr('y', function(d) {
                    return height - y(d);
                })
        }



        // Resize chart
        // ------------------------------

        // Call function on window resize
        $(window).on('resize', barsResize);

        // Call function on sidebar width change
        $('.sidebar-control').on('click', barsResize);

        // Resize function
        // 
        // Since D3 doesn't support SVG resize by default,
        // we need to manually specify parts of the graph that need to 
        // be updated on window resize
        function barsResize() {

            // Layout variables
            width = d3Container.node().getBoundingClientRect().width;


            // Layout
            // -------------------------

            // Main svg width
            container.attr("width", width);

            // Width of appended group
            svg.attr("width", width);

            // Horizontal range
            x.rangeBands([0, width], 0.3);


            // Chart elements
            // -------------------------

            // Bars
            svg.selectAll('.d3-random-bars')
                .attr('width', x.rangeBand())
                .attr('x', function(d,i) {
                    return x(i);
                });
        }
    }

        // Initialize chart
    campaignDonut("#campaigns-donut", 42);

    // Chart setup
    function campaignDonut(element, size) {


        // Basic setup
        // ------------------------------

        // Add data set
        var data = [
            {
                "browser": "Google Adwords",
                "icon": "<i class='icon-google position-left'></i>",
                "value": 1047,
                "color" : "#66BB6A"
            }, {
                "browser": "Social media",
                "icon": "<i class='icon-share4 position-left'></i>",
                "value": 2948,
                "color": "#9575CD"
            }, {
                "browser":"Youtube video",
                "icon": "<i class='icon-youtube position-left'></i>",
                "value": 3909,
                "color": "#FF7043"
            }
        ];

        // Main variables
        var d3Container = d3.select(element),
            distance = 2, // reserve 2px space for mouseover arc moving
            radius = (size/2) - distance,
            sum = d3.sum(data, function(d) { return d.value; })



        // Tooltip
        // ------------------------------

        var tip = d3.tip()
            .attr('class', 'd3-tip')
            .offset([-10, 0])
            .direction('e')
            .html(function (d) {
                return "<ul class='list-unstyled mb-5'>" +
                    "<li>" + "<div class='text-size-base mb-5 mt-5'>" + d.data.icon + d.data.browser + "</div>" + "</li>" +
                    "<li>" + "Visits: &nbsp;" + "<span class='text-semibold pull-right'>" + d.value + "</span>" + "</li>" +
                    "<li>" + "Share: &nbsp;" + "<span class='text-semibold pull-right'>" + (100 / (sum / d.value)).toFixed(2) + "%" + "</span>" + "</li>" +
                "</ul>";
            })



        // Create chart
        // ------------------------------

        // Add svg element
        var container = d3Container.append("svg").call(tip);
        
        // Add SVG group
        var svg = container
            .attr("width", size)
            .attr("height", size)
            .append("g")
                .attr("transform", "translate(" + (size / 2) + "," + (size / 2) + ")");  



        // Construct chart layout
        // ------------------------------

        // Pie
        var pie = d3.layout.pie()
            .sort(null)
            .startAngle(Math.PI)
            .endAngle(3 * Math.PI)
            .value(function (d) { 
                return d.value;
            }); 

        // Arc
        var arc = d3.svg.arc()
            .outerRadius(radius)
            .innerRadius(radius / 2);



        //
        // Append chart elements
        //

        // Group chart elements
        var arcGroup = svg.selectAll(".d3-arc")
            .data(pie(data))
            .enter()
            .append("g") 
                .attr("class", "d3-arc")
                .style('stroke', '#fff')
                .style('cursor', 'pointer');
        
        // Append path
        var arcPath = arcGroup
            .append("path")
            .style("fill", function (d) { return d.data.color; });

       

        // Animate chart on load
        arcPath
            .transition()
                .delay(function(d, i) { return i * 500; })
                .duration(500)
                .attrTween("d", function(d) {
                    var interpolate = d3.interpolate(d.startAngle,d.endAngle);
                    return function(t) {
                        d.endAngle = interpolate(t);
                        return arc(d);  
                    }; 
                });
    }


    // Messages area chart
    // ------------------------------
    /*
    messagesArea("#messages-stats", 40, '#5C6BC0'); // initialize chart

    // Chart setup
    function messagesArea(element, height, color) {


        // Basic setup
        // ------------------------------

        // Define main variables
        var d3Container = d3.select(element),
            margin = {top: 0, right: 0, bottom: 0, left: 0},
            width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
            height = height - margin.top - margin.bottom;

        // Date and time format
        var parseDate = d3.time.format( '%Y-%m-%d' ).parse;


        // Create SVG
        // ------------------------------

        // Container
        var container = d3Container.append('svg');

        // SVG element
        var svg = container
            .attr('width', width + margin.left + margin.right)
            .attr('height', height + margin.top + margin.bottom)
            .append("g")
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")")


        // Construct chart layout
        // ------------------------------

        // Area
        var area = d3.svg.area()
            .x(function(d) { return x(d.date); })
            .y0(height)
            .y1(function(d) { return y(d.value); })
            .interpolate('monotone')


        // Construct scales
        // ------------------------------

        // Horizontal
        var x = d3.time.scale().range([0, width ]);

        // Vertical
        var y = d3.scale.linear().range([height, 0]);


        // Load data
        // ------------------------------

        d3.json("admin/sales_monthly", function (error, data) {

            // Show what's wrong if error
            if (error) return console.error(error);

            // Pull out values
            data.forEach(function (d) {
                d.date = parseDate(d.date);
                d.value = +d.value;
            });

            // Get the maximum value in the given array
            var maxY = d3.max(data, function(d) { return d.value; });

            // Reset start data for animation
            var startData = data.map(function(datum) {
                return {
                    date: datum.date,
                    value: 0
                };
            });


            // Set input domains
            // ------------------------------

            // Horizontal
            x.domain(d3.extent(data, function(d, i) { return d.date; }));

            // Vertical
            y.domain([0, d3.max( data, function(d) { return d.value; })]);



            //
            // Append chart elements
            //

            // Add area path
            svg.append("path")
                .datum(data)
                .attr("class", "d3-area")
                .style('fill', color)
                .attr("d", area)
                .transition() // begin animation
                    .duration(1000)
                    .attrTween('d', function() {
                        var interpolator = d3.interpolateArray(startData, data);
                        return function (t) {
                            return area(interpolator (t));
                        }
                    });


            // Resize chart
            // ------------------------------

            // Call function on window resize
            $(window).on('resize', messagesAreaResize);

            // Call function on sidebar width change
            $('.sidebar-control').on('click', messagesAreaResize);

            // Resize function
            // 
            // Since D3 doesn't support SVG resize by default,
            // we need to manually specify parts of the graph that need to 
            // be updated on window resize
            function messagesAreaResize() {

                // Layout variables
                width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;


                // Layout
                // -------------------------

                // Main svg width
                container.attr("width", width + margin.left + margin.right);

                // Width of appended group
                svg.attr("width", width + margin.left + margin.right);

                // Horizontal range
                x.range([0, width]);


                // Chart elements
                // -------------------------

                // Area path
                svg.selectAll('.d3-area').datum( data ).attr("d", area);
            }
        });
    }
	*/

    // Campaign status donut chart
    // ------------------------------

    // Initialize chart
    campaignStatusPie("#campaign-status-pie", 42);

    // Chart setup
    function campaignStatusPie(element, size) {


        // Basic setup
        // ------------------------------

        // Add data set
        var data = [
            {
                "status": "Active campaigns",
                "icon": "<span class='status-mark border-blue-300 position-left'></span>",
                "value": 439,
                "color": "#29B6F6"
            }, {
                "status": "Closed campaigns",
                "icon": "<span class='status-mark border-danger-300 position-left'></span>",
                "value": 290,
                "color": "#EF5350"
            }, {
                "status": "Pending campaigns",
                "icon": "<span class='status-mark border-success-300 position-left'></span>",
                "value": 190,
                "color": "#81C784"
            }, {
                "status": "Campaigns on hold",
                "icon": "<span class='status-mark border-grey-300 position-left'></span>",
                "value": 148,
                "color": "#999"
            }
        ];

        // Main variables
        var d3Container = d3.select(element),
            distance = 2, // reserve 2px space for mouseover arc moving
            radius = (size/2) - distance,
            sum = d3.sum(data, function(d) { return d.value; })



        // Tooltip
        // ------------------------------

        var tip = d3.tip()
            .attr('class', 'd3-tip')
            .offset([-10, 0])
            .direction('e')
            .html(function (d) {
                return "<ul class='list-unstyled mb-5'>" +
                    "<li>" + "<div class='text-size-base mb-5 mt-5'>" + d.data.icon + d.data.status + "</div>" + "</li>" +
                    "<li>" + "Total: &nbsp;" + "<span class='text-semibold pull-right'>" + d.value + "</span>" + "</li>" +
                    "<li>" + "Share: &nbsp;" + "<span class='text-semibold pull-right'>" + (100 / (sum / d.value)).toFixed(2) + "%" + "</span>" + "</li>" +
                "</ul>";
            })



        // Create chart
        // ------------------------------

        // Add svg element
        var container = d3Container.append("svg").call(tip);
        
        // Add SVG group
        var svg = container
            .attr("width", size)
            .attr("height", size)
            .append("g")
                .attr("transform", "translate(" + (size / 2) + "," + (size / 2) + ")");  



        // Construct chart layout
        // ------------------------------

        // Pie
        var pie = d3.layout.pie()
            .sort(null)
            .startAngle(Math.PI)
            .endAngle(3 * Math.PI)
            .value(function (d) { 
                return d.value;
            }); 

        // Arc
        var arc = d3.svg.arc()
            .outerRadius(radius)
            .innerRadius(radius / 2);



        //
        // Append chart elements
        //

        // Group chart elements
        var arcGroup = svg.selectAll(".d3-arc")
            .data(pie(data))
            .enter()
            .append("g") 
                .attr("class", "d3-arc")
                .style('stroke', '#fff')
                .style('cursor', 'pointer');
        
        // Append path
        var arcPath = arcGroup
            .append("path")
            .style("fill", function (d) { return d.data.color; });

     

        // Animate chart on load
        arcPath
            .transition()
                .delay(function(d, i) { return i * 500; })
                .duration(500)
                .attrTween("d", function(d) {
                    var interpolate = d3.interpolate(d.startAngle,d.endAngle);
                    return function(t) {
                        d.endAngle = interpolate(t);
                        return arc(d);  
                    }; 
                });
    }




    // Tickets status donut chart
    // ------------------------------

    // Initialize chart
    ticketStatusDonut("#tickets-status", 42);

    // Chart setup
    function ticketStatusDonut(element, size) {


        // Basic setup
        // ------------------------------

        // Add data set
        var data = [
            {
                "status": "Pending tickets",
                "icon": "<i class='status-mark border-blue-300 position-left'></i>",
                "value": 295,
                "color": "#29B6F6"
            }, {
                "status": "Resolved tickets",
                "icon": "<i class='status-mark border-success-300 position-left'></i>",
                "value": 189,
                "color": "#66BB6A"
            }, {
                "status": "Closed tickets",
                "icon": "<i class='status-mark border-danger-300 position-left'></i>",
                "value": 277,
                "color": "#EF5350"
            }
        ];

        // Main variables
        var d3Container = d3.select(element),
            distance = 2, // reserve 2px space for mouseover arc moving
            radius = (size/2) - distance,
            sum = d3.sum(data, function(d) { return d.value; })



        // Tooltip
        // ------------------------------

        var tip = d3.tip()
            .attr('class', 'd3-tip')
            .offset([-10, 0])
            .direction('e')
            .html(function (d) {
                return "<ul class='list-unstyled mb-5'>" +
                    "<li>" + "<div class='text-size-base mb-5 mt-5'>" + d.data.icon + d.data.status + "</div>" + "</li>" +
                    "<li>" + "Total: &nbsp;" + "<span class='text-semibold pull-right'>" + d.value + "</span>" + "</li>" +
                    "<li>" + "Share: &nbsp;" + "<span class='text-semibold pull-right'>" + (100 / (sum / d.value)).toFixed(2) + "%" + "</span>" + "</li>" +
                "</ul>";
            })



        // Create chart
        // ------------------------------

        // Add svg element
        var container = d3Container.append("svg").call(tip);
        
        // Add SVG group
        var svg = container
            .attr("width", size)
            .attr("height", size)
            .append("g")
                .attr("transform", "translate(" + (size / 2) + "," + (size / 2) + ")");  



        // Construct chart layout
        // ------------------------------

        // Pie
        var pie = d3.layout.pie()
            .sort(null)
            .startAngle(Math.PI)
            .endAngle(3 * Math.PI)
            .value(function (d) { 
                return d.value;
            }); 

        // Arc
        var arc = d3.svg.arc()
            .outerRadius(radius)
            .innerRadius(radius / 2);



        //
        // Append chart elements
        //

        // Group chart elements
        var arcGroup = svg.selectAll(".d3-arc")
            .data(pie(data))
            .enter()
            .append("g") 
                .attr("class", "d3-arc")
                .style('stroke', '#fff')
                .style('cursor', 'pointer');
        
        // Append path
        var arcPath = arcGroup
            .append("path")
            .style("fill", function (d) { return d.data.color; });

        // Add tooltip
       

        // Animate chart on load
        arcPath
            .transition()
                .delay(function(d, i) { return i * 500; })
                .duration(500)
                .attrTween("d", function(d) {
                    var interpolate = d3.interpolate(d.startAngle,d.endAngle);
                    return function(t) {
                        d.endAngle = interpolate(t);
                        return arc(d);  
                    }; 
                });
    }

  // Initialize charts
    progressCounter('#hours-available-progress', 38, 2, "#F06292", <?php if($penalty_count == '') {echo "0";}else { echo $penalty_count; } ?>, "icon-watch text-pink-400", 'Today penalty (<?php echo strtoupper($currency_info->currency_unit); ?>)', '')
    progressCounter('#goal-progress', 38, 2, "#5C6BC0", <?php if($bonus_count == '') {echo "0";}else { echo $bonus_count; } ?>, "icon-trophy3 text-indigo-400", 'Today bonus (<?php echo strtoupper($currency_info->currency_unit); ?>)', '')

    // Chart setup
    function progressCounter(element, radius, border, color, end, iconClass, textTitle, textAverage) {


        // Basic setup
        // ------------------------------

        // Main variables
        var d3Container = d3.select(element),
            startPercent = 0,
            iconSize = 32,
            endPercent = end,
            twoPi = Math.PI * 2,
            formatPercent = d3.format('0'),
            boxSize = radius * 2;

        // Values count
        var count = Math.abs((endPercent - startPercent) / 1);

        // Values step
        var step = endPercent < startPercent ? -1 : 1;



        // Create chart
        // ------------------------------

        // Add SVG element
        var container = d3Container.append('svg');

        // Add SVG group
        var svg = container
            .attr('width', boxSize)
            .attr('height', boxSize)
            .append('g')
                .attr('transform', 'translate(' + (boxSize / 2) + ',' + (boxSize / 2) + ')');



        // Construct chart layout
        // ------------------------------

        // Arc
        var arc = d3.svg.arc()
            .startAngle(0)
            .innerRadius(radius)
            .outerRadius(radius - border);



        //
        // Append chart elements
        //

        // Paths
        // ------------------------------

        // Background path
        svg.append('path')
            .attr('class', 'd3-progress-background')
            .attr('d', arc.endAngle(twoPi))
            .style('fill', '#eee');

        // Foreground path
        var foreground = svg.append('path')
            .attr('class', 'd3-progress-foreground')
            .attr('filter', 'url(#blur)')
            .style('fill', color)
            .style('stroke', color);

        // Front path
        var front = svg.append('path')
            .attr('class', 'd3-progress-front')
            .style('fill', color)
            .style('fill-opacity', 1);



        // Text
        // ------------------------------

        // Percentage text value
        var numberText = d3.select(element)
            .append('h2')
                .attr('class', 'mt-15 mb-5')

        // Icon
        d3.select(element)
            .append("i")
                .attr("class", iconClass + " counter-icon")
                .attr('style', 'top: ' + ((boxSize - iconSize) / 2) + 'px');

        // Title
        d3.select(element)
            .append('div')
                .text(textTitle);

        // Subtitle
        d3.select(element)
            .append('div')
                .attr('class', 'text-size-small text-muted')
                .text(textAverage);



        // Animation
        // ------------------------------

        // Animate path
        function updateProgress(progress) {
            foreground.attr('d', arc.endAngle(twoPi * progress));
            front.attr('d', arc.endAngle(twoPi * progress));
            numberText.text(formatPercent(progress));
        }

        // Animate text
        var progress = startPercent;
        (function loops() {
            updateProgress(progress);
            if (count > 0) {
                count--;
                progress += step;
                setTimeout(loops, 10);
            }
        })();

    }

     // Daily revenue line chart
    // ------------------------------

    dailyRevenue('#today-revenue', 50); 
    dailyRevenue('#today-revenue1', 50); 
    dailyRevenue('#today-revenue3', 50); 
    dailyRevenue('#today-revenue4', 50); 
	
	
    // initialize chart

    // Chart setup
    function dailyRevenue(element, height) {


        // Basic setup
        // ------------------------------

        // Add data set
        var dataset = [
            {
                "date": "04/13/14",
                "alpha": "60"
            }, {
                "date": "04/14/14",
                "alpha": "35"
            }, {
                "date": "04/15/14",
                "alpha": "65"
            }, {
                "date": "04/16/14",
                "alpha": "50"
            }, {
                "date": "04/17/14",
                "alpha": "65"
            }, {
                "date": "04/18/14",
                "alpha": "20"
            }, {
                "date": "04/19/14",
                "alpha": "60"
            }
        ];

        // Main variables
        var d3Container = d3.select(element),
            margin = {top: 0, right: 0, bottom: 0, left: 0},
            width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
            height = height - margin.top - margin.bottom,
            padding = 20;

        // Format date
        var parseDate = d3.time.format("%m/%d/%y").parse,
            formatDate = d3.time.format("%a, %B %e");



        // Add tooltip
        // ------------------------------

        var tooltip = d3.tip()
            .attr('class', 'd3-tip')
            .html(function (d) {
             
            });



        // Create chart
        // ------------------------------

        // Add svg element
        var container = d3Container.append('svg');

        // Add SVG group
        var svg = container
                .attr('width', width + margin.left + margin.right)
                .attr('height', height + margin.top + margin.bottom)
                .append("g")
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
                    .call(tooltip);



        // Load data
        // ------------------------------

        dataset.forEach(function (d) {
            d.date = parseDate(d.date);
            d.alpha = +d.alpha;
        });



        // Construct scales
        // ------------------------------

        // Horizontal
        var x = d3.time.scale()
            .range([padding, width - padding]);

        // Vertical
        var y = d3.scale.linear()
            .range([height, 5]);



        // Set input domains
        // ------------------------------

        // Horizontal
        x.domain(d3.extent(dataset, function (d) {
            return d.date;
        }));

        // Vertical
        y.domain([0, d3.max(dataset, function (d) {
            return Math.max(d.alpha);
        })]);



        // Construct chart layout
        // ------------------------------

        // Line
        var line = d3.svg.line()
            .x(function(d) {
                return x(d.date);
            })
            .y(function(d) {
                return y(d.alpha)
            });



        //
        // Append chart elements
        //

        // Add mask for animation
        // ------------------------------

        // Add clip path
        var clip = svg.append("defs")
            .append("clipPath")
            .attr("id", "clip-line-small");

        // Add clip shape
        var clipRect = clip.append("rect")
            .attr('class', 'clip')
            .attr("width", 0)
            .attr("height", height);

        // Animate mask
        clipRect
              .transition()
                  .duration(1000)
                  .ease('linear')
                  .attr("width", width);



        // Line
        // ------------------------------

        // Path
        var path = svg.append('path')
            .attr({
                'd': line(dataset),
                "clip-path": "url(#clip-line-small)",
                'class': 'd3-line d3-line-medium'
            })
            .style('stroke', '#fff');

        // Animate path
        svg.select('.line-tickets')
            .transition()
                .duration(1000)
                .ease('linear');



        // Add vertical guide lines
        // ------------------------------

        // Bind data
        var guide = svg.append('g')
            .selectAll('.d3-line-guides-group')
            .data(dataset);

        // Append lines
        guide
            .enter()
            .append('line')
                .attr('class', 'd3-line-guides')
                .attr('x1', function (d, i) {
                    return x(d.date);
                })
                .attr('y1', function (d, i) {
                    return height;
                })
                .attr('x2', function (d, i) {
                    return x(d.date);
                })
                .attr('y2', function (d, i) {
                    return height;
                })
                .style('stroke', 'rgba(255,255,255,0.3)')
                .style('stroke-dasharray', '4,2')
                .style('shape-rendering', 'crispEdges');

        // Animate guide lines
        guide
            .transition()
                .duration(1000)
                .delay(function(d, i) { return i * 150; })
                .attr('y2', function (d, i) {
                    return y(d.alpha);
                });



        // Alpha app points
        // ------------------------------

        // Add points
        var points = svg.insert('g')
            .selectAll('.d3-line-circle')
            .data(dataset)
            .enter()
            .append('circle')
                .attr('class', 'd3-line-circle d3-line-circle-medium')
                .attr("cx", line.x())
                .attr("cy", line.y())
                .attr("r", 3)
                .style('stroke', '#fff')
                .style('fill', '#29B6F6');



        // Animate points on page load
        points
            .style('opacity', 0)
            .transition()
                .duration(250)
                .ease('linear')
                .delay(1000)
                .style('opacity', 1);


        // Add user interaction
   



        // Resize chart
        // ------------------------------

        // Call function on window resize
        $(window).on('resize', revenueResize);

        // Call function on sidebar width change
        $('.sidebar-control').on('click', revenueResize);

        // Resize function
        // 
        // Since D3 doesn't support SVG resize by default,
        // we need to manually specify parts of the graph that need to 
        // be updated on window resize
        function revenueResize() {

            // Layout variables
            width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;


            // Layout
            // -------------------------

            // Main svg width
            container.attr("width", width + margin.left + margin.right);

            // Width of appended group
            svg.attr("width", width + margin.left + margin.right);

            // Horizontal range
            x.range([padding, width - padding]);


            // Chart elements
            // -------------------------

            // Mask
            clipRect.attr("width", width);

            // Line path
            svg.selectAll('.d3-line').attr("d", line(dataset));

            // Circles
            svg.selectAll('.d3-line-circle').attr("cx", line.x());

            // Guide lines
            svg.selectAll('.d3-line-guides')
                .attr('x1', function (d, i) {
                    return x(d.date);
                })
                .attr('x2', function (d, i) {
                    return x(d.date);
                });
        }
    }

    
 	appSalesLines('#app_sales', 255); // initialize chart

    // Chart setup
    function appSalesLines(element, height) {


        // Basic setup
        // ------------------------------

        // Define main variables
        var d3Container = d3.select(element),
            margin = {top: 5, right: 30, bottom: 30, left: 50},
            width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
            height = height - margin.top - margin.bottom;

        // Tooltip
        var tooltip = d3.tip()
            .attr('class', 'd3-tip')
            .html(function (d) {
                return "<ul class='list-unstyled mb-5'>" +
                    "<li>" + "<div class='text-size-base mt-5 mb-5'><i class='icon-circle-left2 position-left'></i>" + d.name + "" + "</div>" + "</li>" +
                   
                    "<li>" + "value: &nbsp; " + "<span class='text-semibold pull-right'>" + "$" + (d.value).toFixed(2) + "</span>" + "</li>" + 
                "</ul>";
            });

        // Format date
        var parseDate = d3.time.format("%Y/%m/%d").parse,
            formatDate = d3.time.format("%b %d, '%y");

        // Line colors
        var scale = ["#4CAF50", "#FF5722", "#5C6BC0"],
            color = d3.scale.ordinal().range(scale);



        // Create chart
        // ------------------------------

        // Container
        var container = d3Container.append('svg');

        // SVG element
        var svg = container
            .attr('width', width + margin.left + margin.right)
            .attr('height', height + margin.top + margin.bottom)
            .append("g")
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
                .call(tooltip);



        // Add date range switcher
        // ------------------------------

        // Menu
        var menu = $("#select_date").multiselect({
            buttonClass: 'btn btn-link text-semibold',
            enableHTML: true,
            dropRight: true,
            onChange: function() { change(), $.uniform.update(); },
            buttonText: function (options, element) {
                var selected = '';
                options.each(function() {
                    selected += $(this).html() + ', ';
                });
                return '<span class="status-mark border-warning position-left"></span>' + selected.substr(0, selected.length -2);
            }
        });

        // Radios
        $(".multiselect-container input").uniform({ radioClass: 'choice' });



        // Load data
        // ------------------------------

        d3.csv("admin/bulltes", function(error, data) {
            formatted = data;
            redraw();
        });



        // Construct layout
        // ------------------------------

        // Add events
        var altKey;
        d3.select(window)
            .on("keydown", function() { altKey = d3.event.altKey; })
            .on("keyup", function() { altKey = false; });
    
        // Set terms of transition on date change   
        function change() {
          d3.transition()
              .duration(altKey ? 7500 : 500)
              .each(redraw);
        }



        // Main chart drawing function
        // ------------------------------

        function redraw() { 
            // Construct chart layout
            // ------------------------------
            // Create data nests
            var nested = d3.nest()
                .key(function(d) { return d.type; })
                .map(formatted)
            
            // Get value from menu selection
            // the option values correspond
            //to the [type] value we used to nest the data  
            var series = menu.val();
            
            // Only retrieve data from the selected series using nest
            var data = nested[series];
            
            // For object constancy we will need to set "keys", one for each type of data (column name) exclude all others.
            color.domain(d3.keys(data[0]).filter(function(key) { return (key !== "date" && key !== "type"); }));

            // Setting up color map
            var linedata = color.domain().map(function(name) {
                return {
                            name: name,
                            values: data.map(function(d) {
                                return {name: name, date: parseDate(d.date), value: parseFloat(d[name], 10)};
                            })
                        };
                    });

            // Draw the line
            var line = d3.svg.line()
                .x(function(d) { return x(d.date); })
                .y(function(d) { return y(d.value); })
                .interpolate('cardinal');



            // Construct scales
            // ------------------------------

            // Horizontal
            var x = d3.time.scale()
                .domain([
                    d3.min(linedata, function(c) { return d3.min(c.values, function(v) { return v.date; }); }),
                    d3.max(linedata, function(c) { return d3.max(c.values, function(v) { return v.date; }); })
                ])
                .range([0, width]);

            // Vertical
            var y = d3.scale.linear()
                .domain([
                    d3.min(linedata, function(c) { return d3.min(c.values, function(v) { return v.value; }); }),
                    d3.max(linedata, function(c) { return d3.max(c.values, function(v) { return v.value; }); })
                ])
                .range([height, 0]);



            // Create axes
            // ------------------------------

            // Horizontal
            var xAxis = d3.svg.axis()
                .scale(x)
                .orient("bottom")
                .tickPadding(8)
                .ticks(d3.time.days)
                .innerTickSize(4)
                .tickFormat(d3.time.format("%a")); // Display hours and minutes in 24h format

            // Vertical
            var yAxis = d3.svg.axis()
                .scale(y)
                .orient("left")
                .ticks(6)
                .tickSize(0 -width)
                .tickPadding(8);
            


            //
            // Append chart elements
            //

            // Append axes
            // ------------------------------

            // Horizontal
            svg.append("g")
                .attr("class", "d3-axis d3-axis-horizontal d3-axis-solid")
                .attr("transform", "translate(0," + height + ")");

            // Vertical
            svg.append("g")
                .attr("class", "d3-axis d3-axis-vertical d3-axis-transparent");



            // Append lines
            // ------------------------------

            // Bind the data
            var lines = svg.selectAll(".lines")
                .data(linedata)
         
            // Append a group tag for each line
            var lineGroup = lines
                .enter()
                .append("g")
                    .attr("class", "lines")
                    .attr('id', function(d){ return d.name + "-line"; });

            // Append the line to the graph
            lineGroup.append("path")
                .attr("class", "d3-line d3-line-medium")
                .style("stroke", function(d) { return color(d.name); })
                .style('opacity', 0)
                .attr("d", function(d) { return line(d.values[0]); })
                .transition()
                    .duration(500)
                    .delay(function(d, i) { return i * 200; })
                    .style('opacity', 1);
          


            // Append circles
            // ------------------------------

            var circles = lines.selectAll("circle")
                .data(function(d) { return d.values; })
                .enter()
                .append("circle")
                    .attr("class", "d3-line-circle d3-line-circle-medium")
                    .attr("cx", function(d,i){return x(d.date)})
                    .attr("cy",function(d,i){return y(d.value)})
                    .attr("r", 3)
                    .style('fill', '#fff')
                    .style("stroke", function(d) { return color(d.name); });

            // Add transition
            circles
                .style('opacity', 0)
                .transition()
                    .duration(500)
                    .delay(500)
                    .style('opacity', 1);



            // Append tooltip
            // ------------------------------

            // Add tooltip on circle hover
            circles
                .on("mouseover", function (d) {
                    tooltip.offset([-15, 0]).show(d);

                    // Animate circle radius
                    d3.select(this).transition().duration(250).attr('r', 4);
                })
                .on("mouseout", function (d) {
                    tooltip.hide(d);

                    // Animate circle radius
                    d3.select(this).transition().duration(250).attr('r', 3);
                });

            // Change tooltip direction of first point
            // to always keep it inside chart, useful on mobiles
            lines.each(function (d) { 
                d3.select(d3.select(this).selectAll('circle')[0][0])
                    .on("mouseover", function (d) {
                        tooltip.offset([0, 15]).direction('e').show(d);

                        // Animate circle radius
                        d3.select(this).transition().duration(250).attr('r', 4);
                    })
                    .on("mouseout", function (d) {
                        tooltip.direction('n').hide(d);

                        // Animate circle radius
                        d3.select(this).transition().duration(250).attr('r', 3);
                    });
            })

            // Change tooltip direction of last point
            // to always keep it inside chart, useful on mobiles
            lines.each(function (d) { 
                d3.select(d3.select(this).selectAll('circle')[0][d3.select(this).selectAll('circle').size() - 1])
                    .on("mouseover", function (d) {
                        tooltip.offset([0, -15]).direction('w').show(d);

                        // Animate circle radius
                        d3.select(this).transition().duration(250).attr('r', 4);
                    })
                    .on("mouseout", function (d) {
                        tooltip.direction('n').hide(d);

                        // Animate circle radius
                        d3.select(this).transition().duration(250).attr('r', 3);
                    })
            })



            // Update chart on date change
            // ------------------------------

            // Set variable for updating visualization
            var lineUpdate = d3.transition(lines);
            
            // Update lines
            lineUpdate.select("path")
                .attr("d", function(d, i) { return line(d.values); });

            // Update circles
            lineUpdate.selectAll("circle")
                .attr("cy",function(d,i){return y(d.value)})
                .attr("cx", function(d,i){return x(d.date)});

            // Update vertical axes
            d3.transition(svg)
                .select(".d3-axis-vertical")
                .call(yAxis);   

            // Update horizontal axes
            d3.transition(svg)
                .select(".d3-axis-horizontal")
                .attr("transform", "translate(0," + height + ")")
                .call(xAxis);



            // Resize chart
            // ------------------------------

            // Call function on window resize
            $(window).on('resize', appSalesResize);

            // Call function on sidebar width change
            $('.sidebar-control').on('click', appSalesResize);

            // Resize function
            // 
            // Since D3 doesn't support SVG resize by default,
            // we need to manually specify parts of the graph that need to 
            // be updated on window resize
            function appSalesResize() {

                // Layout
                // -------------------------

                // Define width
                width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;

                // Main svg width
                container.attr("width", width + margin.left + margin.right);

                // Width of appended group
                svg.attr("width", width + margin.left + margin.right);

                // Horizontal range
                x.range([0, width]);

                // Vertical range
                y.range([height, 0]);


                // Chart elements
                // -------------------------

                // Horizontal axis
                svg.select('.d3-axis-horizontal').call(xAxis);

                // Vertical axis
                svg.select('.d3-axis-vertical').call(yAxis.tickSize(0-width));

                // Lines
                svg.selectAll('.d3-line').attr("d", function(d, i) { return line(d.values); });

                // Circles
                svg.selectAll('.d3-line-circle').attr("cx", function(d,i){return x(d.date)})
            }
        }
    }



    // Monthly app sales area chart
    // ------------------------------

    monthlySalesArea("#monthly-sales-stats", 100, '#4DB6AC'); // initialize chart

    // Chart setup
    function monthlySalesArea(element, height, color) {


        // Basic setup
        // ------------------------------

        // Define main variables
        var d3Container = d3.select(element),
            margin = {top: 20, right: 35, bottom: 40, left: 35},
            width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
            height = height - margin.top - margin.bottom;

        // Date and time format
        var parseDate = d3.time.format( '%Y-%m-%d' ).parse,
            bisectDate = d3.bisector(function(d) { return d.date; }).left,
            formatDate = d3.time.format("%b %d");



        // Create SVG
        // ------------------------------

        // Container
        var container = d3Container.append('svg');

        // SVG element
        var svg = container
            .attr('width', width + margin.left + margin.right)
            .attr('height', height + margin.top + margin.bottom)
            .append("g")
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")")



        // Construct chart layout
        // ------------------------------

        // Area
        var area = d3.svg.area()
            .x(function(d) { return x(d.date); })
            .y0(height)
            .y1(function(d) { return y(d.value); })
            .interpolate('monotone')


        // Construct scales
        // ------------------------------

        // Horizontal
        var x = d3.time.scale().range([0, width ]);

        // Vertical
        var y = d3.scale.linear().range([height, 0]);


        // Create axes
        // ------------------------------

        // Horizontal
        var xAxis = d3.svg.axis()
            .scale(x)
            .orient("bottom")
            .ticks(d3.time.days, 6)
            .innerTickSize(4)
            .tickPadding(8)
            .tickFormat(d3.time.format("%b %d"));


        // Load data
        // ------------------------------

        d3.json('<?php echo base_url("admin/sales_monthly") ?>', function (error, data) {

            // Show what's wrong if error
            if (error) return console.error(error);

            // Pull out values
            data.forEach(function (d) {
                d.date = parseDate(d.date);
                d.value = +d.value;
            });

            // Get the maximum value in the given array
            var maxY = d3.max(data, function(d) { return d.value; });

            // Reset start data for animation
            var startData = data.map(function(datum) {
                return {
                    date: datum.date,
                    value: 0
                };
            });


            // Set input domains
            // ------------------------------

            // Horizontal
            x.domain(d3.extent(data, function(d, i) { return d.date; }));

            // Vertical
            y.domain([0, d3.max( data, function(d) { return d.value; })]);



            //
            // Append chart elements
            //

            // Append axes
            // -------------------------

            // Horizontal
            var horizontalAxis = svg.append("g")
                .attr("class", "d3-axis d3-axis-horizontal d3-axis-solid")
                .attr("transform", "translate(0," + height + ")")
                .call(xAxis);

            // Add extra subticks for hidden hours
            horizontalAxis.selectAll(".d3-axis-subticks")
                .data(x.ticks(d3.time.days), function(d) { return d; })
                .enter()
                    .append("line")
                    .attr("class", "d3-axis-subticks")
                    .attr("y1", 0)
                    .attr("y2", 4)
                    .attr("x1", x)
                    .attr("x2", x);



            // Append area
            // -------------------------

            // Add area path
            svg.append("path")
                .datum(data)
                .attr("class", "d3-area")
                .attr("d", area)
                .style('fill', color)
                .transition() // begin animation
                    .duration(1000)
                    .attrTween('d', function() {
                        var interpolator = d3.interpolateArray(startData, data);
                        return function (t) {
                            return area(interpolator (t));
                        }
                    });



            // Append crosshair and tooltip
            // -------------------------

            //
            // Line
            //

            // Line group
            var focusLine = svg.append("g")
                .attr("class", "d3-crosshair-line")
                .style("display", "none");

            // Line element
            focusLine.append("line")
                .attr("class", "vertical-crosshair")
                .attr("y1", 0)
                .attr("y2", -maxY)
                .style("stroke", "#e5e5e5")
                .style('shape-rendering', 'crispEdges')


            //
            // Pointer
            //

            // Pointer group
            var focusPointer = svg.append("g")
                .attr("class", "d3-crosshair-pointer")
                .style("display", "none");

            // Pointer element
            focusPointer.append("circle")
                .attr("r", 3)
                .style("fill", "#fff")
                .style('stroke', color)
                .style('stroke-width', 1)


            //
            // Text
            //

            // Text group
            var focusText = svg.append("g")
                .attr("class", "d3-crosshair-text")
                .style("display", "none");

            // Text element
            focusText.append("text")
                .attr("dy", -10)
                .style('font-size', 12);


            //
            // Overlay with events
            //

            svg.append("rect")
                .attr("class", "d3-crosshair-overlay")
                .style('fill', 'none')
                .style('pointer-events', 'all')
                .attr("width", width)
                .attr("height", height)
                    .on("mouseover", function() {
                        focusPointer.style("display", null);        
                        focusLine.style("display", null)
                        focusText.style("display", null);
                    })
                    .on("mouseout", function() {
                        focusPointer.style("display", "none"); 
                        focusLine.style("display", "none");
                        focusText.style("display", "none");
                    })
                    .on("mousemove", mousemove);


            // Display tooltip on mousemove
            function mousemove() {

                // Define main variables
                var mouse = d3.mouse(this),
                    mousex = mouse[0],
                    mousey = mouse[1],
                    x0 = x.invert(mousex),
                    i = bisectDate(data, x0),
                    d0 = data[i - 1],
                    d1 = data[i],
                    d = x0 - d0.date > d1.date - x0 ? d1 : d0;

                // Move line
                focusLine.attr("transform", "translate(" + x(d.date) + "," + height + ")");

                // Move pointer
                focusPointer.attr("transform", "translate(" + x(d.date) + "," + y(d.value) + ")");

                // Reverse tooltip at the end point
                if(mousex >= (d3Container.node().getBoundingClientRect().width - focusText.select('text').node().getBoundingClientRect().width - margin.right - margin.left)) {
                    focusText.select("text").attr('text-anchor', 'end').attr("x", function () { return (x(d.date) - 15) + "px" }).text(formatDate(d.date) + " - " + d.value + " deposit");
                }
                else {
                    focusText.select("text").attr('text-anchor', 'start').attr("x", function () { return (x(d.date) + 15) + "px" }).text(formatDate(d.date) + " - " + d.value + " deposit");
                }
            }



            // Resize chart
            // ------------------------------

            // Call function on window resize
            $(window).on('resize', monthlySalesAreaResize);

            // Call function on sidebar width change
            $('.sidebar-control').on('click', monthlySalesAreaResize);

            // Resize function
            // 
            // Since D3 doesn't support SVG resize by default,
            // we need to manually specify parts of the graph that need to 
            // be updated on window resize
            function monthlySalesAreaResize() {

                // Layout variables
                width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;


                // Layout
                // -------------------------

                // Main svg width
                container.attr("width", width + margin.left + margin.right);

                // Width of appended group
                svg.attr("width", width + margin.left + margin.right);


                // Axes
                // -------------------------

                // Horizontal range
                x.range([0, width]);

                // Horizontal axis
                svg.selectAll('.d3-axis-horizontal').call(xAxis);

                // Horizontal axis subticks
                svg.selectAll('.d3-axis-subticks').attr("x1", x).attr("x2", x);


                // Chart elements
                // -------------------------

                // Area path
                svg.selectAll('.d3-area').datum( data ).attr("d", area);

                // Crosshair
                svg.selectAll('.d3-crosshair-overlay').attr("width", width);
            }
        });
    }


			// Set paths
    require.config({
        paths: {
            echarts: 'assets/js/plugins/visualization/echarts'
        }
    });


    // Configuration
    require(
        [
            'echarts',
            'echarts/theme/limitless',
            'echarts/chart/line',   // load-on-demand, don't forget the Magic switch type.
            'echarts/chart/bar'
        ],


        // Charts setup
        function (ec, limitless) {

            // Init
           var stacked_columns = ec.init(document.getElementById('stacked_columns'), limitless);

            

            // Options
             stacked_columns_options = {

                // Setup grid
                grid: {
                    x: 40,
                    x2: 47,
                    y: 35,
                    y2: 25
                },

                // Add tooltip
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow' // 'line' | 'shadow'
                    }
                },

                // Add legend
                legend: {
                    data: ['Total users','Active users','New users']
                },

                // Add toolbox
                toolbox: {
                    show: true,
                    orient: 'vertical',
                    x: 'right',
                    y: 'center',
                    itemGap: 15,
                    showTitle: false,
                    feature: false
                },

                // Enable drag recalculate
                calculable: true,

                // Horizontal axis
                xAxis: [{
                    type: 'category',
                    data: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
                }],

                // Vertical axis
                yAxis: [{
                    type: 'value'
                }],

                // Add series
                series: [
                    {
                        name: 'Total users',
                        type: 'bar',
                        data: [<?php echo $mon_count->cou; ?>, <?php echo $tues_count->cou; ?>, <?php echo $wed_count->cou; ?>, <?php echo $thur_count->cou; ?>, <?php echo $fri_count->cou; ?>, <?php echo $sat_count->cou; ?>, <?php echo $sun_count->cou; ?>]
                    },
                    {
                        name: 'Active users',
                        type: 'bar',
                        data: [<?php echo $act_mon_count->cou; ?>, <?php echo $act_tues_count->cou; ?>, <?php echo $act_wed_count->cou; ?>, <?php echo $act_thur_count->cou; ?>, <?php echo $act_fri_count->cou; ?>, <?php echo $act_sat_count->cou; ?>, <?php echo $act_sun_count->cou; ?>]
                    },
                    {
                        name: 'New users',
                        type: 'bar',
                        data: [<?php echo $new_mon_count->cou; ?>, <?php echo $new_tues_count->cou; ?>, <?php echo $new_wed_count->cou; ?>, <?php echo $new_thur_count->cou; ?>, <?php echo $new_fri_count->cou; ?>, <?php echo $new_sat_count->cou; ?>, <?php echo $new_sun_count->cou; ?>]
                    }
                ]
            };

            stacked_columns.setOption(stacked_columns_options);
           

            //
            // Resize chart
            //

            window.onresize = function () {
                setTimeout(function (){
                    stacked_columns.resize();
                }, 200);
            }


            // Resize in tabs
            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                stacked_columns.resize();
            });
        }
    );





    });
})(jQuery);


!function ($) {
    "use strict";// jshint ;_;

    if (typeof ko !== 'undefined' && ko.bindingHandlers && !ko.bindingHandlers.multiselect) {
        ko.bindingHandlers.multiselect = {
            after: ['options', 'value', 'selectedOptions', 'enable', 'disable'],

            init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
                var $element = $(element);
                var config = ko.toJS(valueAccessor());

                $element.multiselect(config);

                if (allBindings.has('options')) {
                    var options = allBindings.get('options');
                    if (ko.isObservable(options)) {
                        ko.computed({
                            read: function() {
                                options();
                                setTimeout(function() {
                                    var ms = $element.data('multiselect');
                                    if (ms)
                                        ms.updateOriginalOptions();//Not sure how beneficial this is.
                                    $element.multiselect('rebuild');
                                }, 1);
                            },
                            disposeWhenNodeIsRemoved: element
                        });
                    }
                }

                //value and selectedOptions are two-way, so these will be triggered even by our own actions.
                //It needs some way to tell if they are triggered because of us or because of outside change.
                //It doesn't loop but it's a waste of processing.
                if (allBindings.has('value')) {
                    var value = allBindings.get('value');
                    if (ko.isObservable(value)) {
                        ko.computed({
                            read: function() {
                                value();
                                setTimeout(function() {
                                    $element.multiselect('refresh');
                                }, 1);
                            },
                            disposeWhenNodeIsRemoved: element
                        }).extend({ rateLimit: 100, notifyWhenChangesStop: true });
                    }
                }

                //Switched from arrayChange subscription to general subscription using 'refresh'.
                //Not sure performance is any better using 'select' and 'deselect'.
                if (allBindings.has('selectedOptions')) {
                    var selectedOptions = allBindings.get('selectedOptions');
                    if (ko.isObservable(selectedOptions)) {
                        ko.computed({
                            read: function() {
                                selectedOptions();
                                setTimeout(function() {
                                    $element.multiselect('refresh');
                                }, 1);
                            },
                            disposeWhenNodeIsRemoved: element
                        }).extend({ rateLimit: 100, notifyWhenChangesStop: true });
                    }
                }

                var setEnabled = function (enable) {
                    setTimeout(function () {
                        if (enable)
                            $element.multiselect('enable');
                        else
                            $element.multiselect('disable');
                    });
                };

                if (allBindings.has('enable')) {
                    var enable = allBindings.get('enable');
                    if (ko.isObservable(enable)) {
                        ko.computed({
                            read: function () {
                                setEnabled(enable());
                            },
                            disposeWhenNodeIsRemoved: element
                        }).extend({ rateLimit: 100, notifyWhenChangesStop: true });
                    } else {
                        setEnabled(enable);
                    }
                }

                if (allBindings.has('disable')) {
                    var disable = allBindings.get('disable');
                    if (ko.isObservable(disable)) {
                        ko.computed({
                            read: function () {
                                setEnabled(!disable());
                            },
                            disposeWhenNodeIsRemoved: element
                        }).extend({ rateLimit: 100, notifyWhenChangesStop: true });
                    } else {
                        setEnabled(!disable);
                    }
                }

                ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
                    $element.multiselect('destroy');
                });
            },

            update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
                var $element = $(element);
                var config = ko.toJS(valueAccessor());

                $element.multiselect('setOptions', config);
                $element.multiselect('rebuild');
            }
        };
    }

    function forEach(array, callback) {
        for (var index = 0; index < array.length; ++index) {
            callback(array[index], index);
        }
    }

    /**
     * Constructor to create a new multiselect using the given select.
     *
     * @param {jQuery} select
     * @param {Object} options
     * @returns {Multiselect}
     */
    function Multiselect(select, options) {

        this.$select = $(select);
        
        // Placeholder via data attributes
        if (this.$select.attr("data-placeholder")) {
            options.nonSelectedText = this.$select.data("placeholder");
        }
        
        this.options = this.mergeOptions($.extend({}, options, this.$select.data()));

        // Initialization.
        // We have to clone to create a new reference.
        this.originalOptions = this.$select.clone()[0].options;
        this.query = '';
        this.searchTimeout = null;
        this.lastToggledInput = null;

        this.options.multiple = this.$select.attr('multiple') === "multiple";
        this.options.onChange = $.proxy(this.options.onChange, this);
        this.options.onDropdownShow = $.proxy(this.options.onDropdownShow, this);
        this.options.onDropdownHide = $.proxy(this.options.onDropdownHide, this);
        this.options.onDropdownShown = $.proxy(this.options.onDropdownShown, this);
        this.options.onDropdownHidden = $.proxy(this.options.onDropdownHidden, this);
        this.options.onInitialized = $.proxy(this.options.onInitialized, this);
        
        // Build select all if enabled.
        this.buildContainer();
        this.buildButton();
        this.buildDropdown();
        this.buildSelectAll();
        this.buildDropdownOptions();
        this.buildFilter();

        this.updateButtonText();
        this.updateSelectAll(true);

        if (this.options.disableIfEmpty && $('option', this.$select).length <= 0) {
            this.disable();
        }
        
        this.$select.hide().after(this.$container);
        this.options.onInitialized(this.$select, this.$container);
    }

    Multiselect.prototype = {

        defaults: {
            /**
             * Default text function will either print 'None selected' in case no
             * option is selected or a list of the selected options up to a length
             * of 3 selected options.
             * 
             * @param {jQuery} options
             * @param {jQuery} select
             * @returns {String}
             */
            buttonText: function(options, select) {
                if (this.disabledText.length > 0 
                        && (this.disableIfEmpty || select.prop('disabled')) 
                        && options.length == 0) {
                    
                    return this.disabledText;
                }
                else if (options.length === 0) {
                    return this.nonSelectedText;
                }
                else if (this.allSelectedText 
                        && options.length === $('option', $(select)).length 
                        && $('option', $(select)).length !== 1 
                        && this.multiple) {

                    if (this.selectAllNumber) {
                        return this.allSelectedText + ' (' + options.length + ')';
                    }
                    else {
                        return this.allSelectedText;
                    }
                }
                else if (options.length > this.numberDisplayed) {
                    return options.length + ' ' + this.nSelectedText;
                }
                else {
                    var selected = '';
                    var delimiter = this.delimiterText;
                    
                    options.each(function() {
                        var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).text();
                        selected += label + delimiter;
                    });
                    
                    return selected.substr(0, selected.length - 2);
                }
            },
            /**
             * Updates the title of the button similar to the buttonText function.
             * 
             * @param {jQuery} options
             * @param {jQuery} select
             * @returns {@exp;selected@call;substr}
             */
            buttonTitle: function(options, select) {
                if (options.length === 0) {
                    return this.nonSelectedText;
                }
                else {
                    var selected = '';
                    var delimiter = this.delimiterText;
                    
                    options.each(function () {
                        var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).text();
                        selected += label + delimiter;
                    });
                    return selected.substr(0, selected.length - 2);
                }
            },
            /**
             * Create a label.
             *
             * @param {jQuery} element
             * @returns {String}
             */
            optionLabel: function(element){
                return $(element).attr('label') || $(element).text();
            },
            /**
             * Create a class.
             *
             * @param {jQuery} element
             * @returns {String}
             */
            optionClass: function(element) {
                return $(element).attr('class') || '';
            },
            /**
             * Triggered on change of the multiselect.
             * 
             * Not triggered when selecting/deselecting options manually.
             * 
             * @param {jQuery} option
             * @param {Boolean} checked
             */
            onChange : function(option, checked) {

            },
            /**
             * Triggered when the dropdown is shown.
             *
             * @param {jQuery} event
             */
            onDropdownShow: function(event) {

            },
            /**
             * Triggered when the dropdown is hidden.
             *
             * @param {jQuery} event
             */
            onDropdownHide: function(event) {

            },
            /**
             * Triggered after the dropdown is shown.
             * 
             * @param {jQuery} event
             */
            onDropdownShown: function(event) {
                
            },
            /**
             * Triggered after the dropdown is hidden.
             * 
             * @param {jQuery} event
             */
            onDropdownHidden: function(event) {
                
            },
            /**
             * Triggered on select all.
             */
            onSelectAll: function(checked) {
                
            },
            /**
             * Triggered after initializing.
             *
             * @param {jQuery} $select
             * @param {jQuery} $container
             */
            onInitialized: function($select, $container) {

            },
            enableHTML: false,
            buttonClass: 'btn btn-default',
            inheritClass: false,
            buttonWidth: 'auto',
            buttonContainer: '<div class="btn-group" />',
            dropRight: false,
            dropUp: false,
            selectedClass: 'active',
            // Maximum height of the dropdown menu.
            // If maximum height is exceeded a scrollbar will be displayed.
            maxHeight: false,
            checkboxName: false,
            includeSelectAllOption: false,
            includeSelectAllIfMoreThan: 0,
            selectAllText: ' Select all',
            selectAllValue: 'multiselect-all',
            selectAllName: false,
            selectAllNumber: true,
            selectAllJustVisible: true,
            enableFiltering: false,
            enableCaseInsensitiveFiltering: false,
            enableFullValueFiltering: false,
            enableClickableOptGroups: false,
            enableCollapsibelOptGroups: false,
            filterPlaceholder: 'Search',
            // possible options: 'text', 'value', 'both'
            filterBehavior: 'text',
            includeFilterClearBtn: true,
            preventInputChangeEvent: false,
            nonSelectedText: 'None selected',
            nSelectedText: 'selected',
            allSelectedText: 'All selected',
            numberDisplayed: 3,
            disableIfEmpty: false,
            disabledText: '',
            delimiterText: ', ',
            templates: {
                button: '',
                ul: '<ul class="multiselect-container dropdown-menu"></ul>',
                filter: '<li class="multiselect-item filter"><div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-search"></i></span><input class="form-control multiselect-search" type="text"></div></li>',
                filterClearBtn: '<span class="input-group-btn"><button class="btn btn-default multiselect-clear-filter" type="button"><i class="glyphicon glyphicon-remove-circle"></i></button></span>',
                li: '<li><a tabindex="0"><label></label></a></li>',
                divider: '<li class="multiselect-item divider"></li>',
                liGroup: '<li class="multiselect-item multiselect-group"><label></label></li>'
            }
        },

        constructor: Multiselect,

        /**
         * Builds the container of the multiselect.
         */
        buildContainer: function() {
            this.$container = $(this.options.buttonContainer);
            this.$container.on('show.bs.dropdown', this.options.onDropdownShow);
            this.$container.on('hide.bs.dropdown', this.options.onDropdownHide);
            this.$container.on('shown.bs.dropdown', this.options.onDropdownShown);
            this.$container.on('hidden.bs.dropdown', this.options.onDropdownHidden);
        },

        /**
         * Builds the button of the multiselect.
         */
        buildButton: function() {
            this.$button = $(this.options.templates.button).addClass(this.options.buttonClass);
            if (this.$select.attr('class') && this.options.inheritClass) {
                this.$button.addClass(this.$select.attr('class'));
            }
            // Adopt active state.
            if (this.$select.prop('disabled')) {
                this.disable();
            }
            else {
                this.enable();
            }

            // Manually add button width if set.
            if (this.options.buttonWidth && this.options.buttonWidth !== 'auto') {
                this.$button.css({
                    'width' : this.options.buttonWidth,
                    'overflow' : 'hidden',
                    'text-overflow' : 'ellipsis'
                });
                this.$container.css({
                    'width': this.options.buttonWidth
                });
            }

            // Keep the tab index from the select.
            var tabindex = this.$select.attr('tabindex');
            if (tabindex) {
                this.$button.attr('tabindex', tabindex);
            }

            this.$container.prepend(this.$button);
        },

        /**
         * Builds the ul representing the dropdown menu.
         */
        buildDropdown: function() {

            // Build ul.
            this.$ul = $(this.options.templates.ul);

            if (this.options.dropRight) {
                this.$ul.addClass('pull-right');
            }

            // Set max height of dropdown menu to activate auto scrollbar.
            if (this.options.maxHeight) {
                // TODO: Add a class for this option to move the css declarations.
                this.$ul.css({
                    'max-height': this.options.maxHeight + 'px',
                    'overflow-y': 'auto',
                    'overflow-x': 'hidden'
                });
            }
            
            if (this.options.dropUp) {
                
                var height = Math.min(this.options.maxHeight, $('option[data-role!="divider"]', this.$select).length*26 + $('option[data-role="divider"]', this.$select).length*19 + (this.options.includeSelectAllOption ? 26 : 0) + (this.options.enableFiltering || this.options.enableCaseInsensitiveFiltering ? 44 : 0));
                var moveCalc = height + 34;
                
                this.$ul.css({
                    'max-height': height + 'px',
                    'overflow-y': 'auto',
                    'overflow-x': 'hidden',
                    'margin-top': "-" + moveCalc + 'px'
                });
            }
            
            this.$container.append(this.$ul);
        },

        /**
         * Build the dropdown options and binds all nessecary events.
         * 
         * Uses createDivider and createOptionValue to create the necessary options.
         */
        buildDropdownOptions: function() {

            this.$select.children().each($.proxy(function(index, element) {

                var $element = $(element);
                // Support optgroups and options without a group simultaneously.
                var tag = $element.prop('tagName')
                    .toLowerCase();
            
                if ($element.prop('value') === this.options.selectAllValue) {
                    return;
                }

                if (tag === 'optgroup') {
                    this.createOptgroup(element);
                }
                else if (tag === 'option') {

                    if ($element.data('role') === 'divider') {
                        this.createDivider();
                    }
                    else {
                        this.createOptionValue(element);
                    }

                }

                // Other illegal tags will be ignored.
            }, this));

            // Bind the change event on the dropdown elements.
            $('li input', this.$ul).on('change', $.proxy(function(event) {
                var $target = $(event.target);

                var checked = $target.prop('checked') || false;
                var isSelectAllOption = $target.val() === this.options.selectAllValue;

                // Apply or unapply the configured selected class.
                if (this.options.selectedClass) {
                    if (checked) {
                        $target.closest('li')
                            .addClass(this.options.selectedClass);
                    }
                    else {
                        $target.closest('li')
                            .removeClass(this.options.selectedClass);
                    }
                }

                // Get the corresponding option.
                var value = $target.val();
                var $option = this.getOptionByValue(value);

                var $optionsNotThis = $('option', this.$select).not($option);
                var $checkboxesNotThis = $('input', this.$container).not($target);

                if (isSelectAllOption) {
                    if (checked) {
                        this.selectAll(this.options.selectAllJustVisible);
                    }
                    else {
                        this.deselectAll(this.options.selectAllJustVisible);
                    }
                }
                else {
                    if (checked) {
                        $option.prop('selected', true);

                        if (this.options.multiple) {
                            // Simply select additional option.
                            $option.prop('selected', true);
                        }
                        else {
                            // Unselect all other options and corresponding checkboxes.
                            if (this.options.selectedClass) {
                                $($checkboxesNotThis).closest('li').removeClass(this.options.selectedClass);
                            }

                            $($checkboxesNotThis).prop('checked', false);
                            $optionsNotThis.prop('selected', false);

                            // It's a single selection, so close.
                            this.$button.click();
                        }

                        if (this.options.selectedClass === "active") {
                            $optionsNotThis.closest("a").css("outline", "");
                        }
                    }
                    else {
                        // Unselect option.
                        $option.prop('selected', false);
                    }
                    
                    // To prevent select all from firing onChange: #575
                    this.options.onChange($option, checked);
                }

                this.$select.change();

                this.updateButtonText();
                this.updateSelectAll();

                if(this.options.preventInputChangeEvent) {
                    return false;
                }
            }, this));

            $('li a', this.$ul).on('mousedown', function(e) {
                if (e.shiftKey) {
                    // Prevent selecting text by Shift+click
                    return false;
                }
            });
        
            $('li a', this.$ul).on('touchstart click', $.proxy(function(event) {
                event.stopPropagation();

                var $target = $(event.target);
                
                if (event.shiftKey && this.options.multiple) {
                    if($target.is("label")){ // Handles checkbox selection manually (see https://github.com/davidstutz/bootstrap-multiselect/issues/431)
                        event.preventDefault();
                        $target = $target.find("input");
                        $target.prop("checked", !$target.prop("checked"));
                    }
                    var checked = $target.prop('checked') || false;

                    if (this.lastToggledInput !== null && this.lastToggledInput !== $target) { // Make sure we actually have a range
                        var from = $target.closest("li").index();
                        var to = this.lastToggledInput.closest("li").index();
                        
                        if (from > to) { // Swap the indices
                            var tmp = to;
                            to = from;
                            from = tmp;
                        }
                        
                        // Make sure we grab all elements since slice excludes the last index
                        ++to;
                        
                        // Change the checkboxes and underlying options
                        var range = this.$ul.find("li").slice(from, to).find("input");
                        
                        range.prop('checked', checked);
                        
                        if (this.options.selectedClass) {
                            range.closest('li')
                                .toggleClass(this.options.selectedClass, checked);
                        }
                        
                        for (var i = 0, j = range.length; i < j; i++) {
                            var $checkbox = $(range[i]);

                            var $option = this.getOptionByValue($checkbox.val());

                            $option.prop('selected', checked);
                        }                   
                    }
                    
                    // Trigger the select "change" event
                    $target.trigger("change");
                }
                
                // Remembers last clicked option
                if($target.is("input") && !$target.closest("li").is(".multiselect-item")){
                    this.lastToggledInput = $target;
                }

                $target.blur();
            }, this));

            // Keyboard support.
            this.$container.off('keydown.multiselect').on('keydown.multiselect', $.proxy(function(event) {
                if ($('input[type="text"]', this.$container).is(':focus')) {
                    return;
                }

                if (event.keyCode === 9 && this.$container.hasClass('open')) {
                    this.$button.click();
                }
                else {
                    var $items = $(this.$container).find("li:not(.divider):not(.disabled) a").filter(":visible");

                    if (!$items.length) {
                        return;
                    }

                    var index = $items.index($items.filter(':focus'));

                    // Navigation up.
                    if (event.keyCode === 38 && index > 0) {
                        index--;
                    }
                    // Navigate down.
                    else if (event.keyCode === 40 && index < $items.length - 1) {
                        index++;
                    }
                    else if (!~index) {
                        index = 0;
                    }

                    var $current = $items.eq(index);
                    $current.focus();

                    if (event.keyCode === 32 || event.keyCode === 13) {
                        var $checkbox = $current.find('input');

                        $checkbox.prop("checked", !$checkbox.prop("checked"));
                        $checkbox.change();
                    }

                    event.stopPropagation();
                    event.preventDefault();
                }
            }, this));

            if(this.options.enableClickableOptGroups && this.options.multiple) {
                $('li.multiselect-group', this.$ul).on('click', $.proxy(function(event) {
                    event.stopPropagation();
                    console.log('test');
                    var group = $(event.target).parent();

                    // Search all option in optgroup
                    var $options = group.nextUntil('li.multiselect-group');
                    var $visibleOptions = $options.filter(":visible:not(.disabled)");

                    // check or uncheck items
                    var allChecked = true;
                    var optionInputs = $visibleOptions.find('input');
                    var values = [];
                    
                    optionInputs.each(function() {
                        allChecked = allChecked && $(this).prop('checked');
                        values.push($(this).val());
                    });

                    if (!allChecked) {
                        this.select(values, false);
                    }
                    else {
                        this.deselect(values, false);
                    }
                    
                    this.options.onChange(optionInputs, !allChecked);
               }, this));
            }

            if (this.options.enableCollapsibleOptGroups && this.options.multiple) {
                $("li.multiselect-group input", this.$ul).off();
                $("li.multiselect-group", this.$ul).siblings().not("li.multiselect-group, li.multiselect-all", this.$ul).each( function () {
                    $(this).toggleClass('hidden', true);
                });
                
                $("li.multiselect-group", this.$ul).on("click", $.proxy(function(group) {
                    group.stopPropagation();
                }, this));
                
                $("li.multiselect-group > a > b", this.$ul).on("click", $.proxy(function(t) {
                    t.stopPropagation();
                    var n = $(t.target).closest('li');
                    var r = n.nextUntil("li.multiselect-group");
                    var i = true;
                    
                    r.each(function() {
                        i = i && $(this).hasClass('hidden');
                    });
                    
                    r.toggleClass('hidden', !i);
                }, this));
                
                $("li.multiselect-group > a > input", this.$ul).on("change", $.proxy(function(t) {
                    t.stopPropagation();
                    var n = $(t.target).closest('li');
                    var r = n.nextUntil("li.multiselect-group", ':not(.disabled)');
                    var s = r.find("input");
                    
                    var i = true;
                    s.each(function() {
                        i = i && $(this).prop("checked");
                    });
                    
                    s.prop("checked", !i).trigger("change");
                }, this));
                
                // Set the initial selection state of the groups.
                $('li.multiselect-group', this.$ul).each(function() {
                    var r = $(this).nextUntil("li.multiselect-group", ':not(.disabled)');
                    var s = r.find("input");
                    
                    var i = true;
                    s.each(function() {
                        i = i && $(this).prop("checked");
                    });
                    
                    $(this).find('input').prop("checked", i);
                });
                
                // Update the group checkbox based on new selections among the
                // corresponding children.
                $("li input", this.$ul).on("change", $.proxy(function(t) {
                    t.stopPropagation();
                    var n = $(t.target).closest('li');
                    var r1 = n.prevUntil("li.multiselect-group", ':not(.disabled)');
                    var r2 = n.nextUntil("li.multiselect-group", ':not(.disabled)');
                    var s1 = r1.find("input");
                    var s2 = r2.find("input");
                    
                    var i = $(t.target).prop('checked');
                    s1.each(function() {
                        i = i && $(this).prop("checked");
                    });
                    
                    s2.each(function() {
                        i = i && $(this).prop("checked");
                    });
                    
                    n.prevAll('.multiselect-group').find('input').prop('checked', i);
                }, this));
                
                $("li.multiselect-all", this.$ul).css('background', '#f3f3f3').css('border-bottom', '1px solid #eaeaea');
                $("li.multiselect-group > a, li.multiselect-all > a > label.checkbox", this.$ul).css('padding', '3px 20px 3px 35px');
                $("li.multiselect-group > a > input", this.$ul).css('margin', '4px 0px 5px -20px');
            }
        },

        /**
         * Create an option using the given select option.
         *
         * @param {jQuery} element
         */
        createOptionValue: function(element) {
            var $element = $(element);
            if ($element.is(':selected')) {
                $element.prop('selected', true);
            }

            // Support the label attribute on options.
            var label = this.options.optionLabel(element);
            var classes = this.options.optionClass(element);
            var value = $element.val();
            var inputType = this.options.multiple ? "checkbox" : "radio";

            var $li = $(this.options.templates.li);
            var $label = $('label', $li);
            $label.addClass(inputType);
            $li.addClass(classes);

            if (this.options.enableHTML) {
                $label.html(" " + label);
            }
            else {
                $label.text(" " + label);
            }
        
            var $checkbox = $('<input/>').attr('type', inputType);

            if (this.options.checkboxName) {
                $checkbox.attr('name', this.options.checkboxName);
            }
            $label.prepend($checkbox);

            var selected = $element.prop('selected') || false;
            $checkbox.val(value);

            if (value === this.options.selectAllValue) {
                $li.addClass("multiselect-item multiselect-all");
                $checkbox.parent().parent()
                    .addClass('multiselect-all');
            }

            $label.attr('title', $element.attr('title'));

            this.$ul.append($li);

            if ($element.is(':disabled')) {
                $checkbox.attr('disabled', 'disabled')
                    .prop('disabled', true)
                    .closest('a')
                    .attr("tabindex", "-1")
                    .closest('li')
                    .addClass('disabled');
            }

            $checkbox.prop('checked', selected);

            if (selected && this.options.selectedClass) {
                $checkbox.closest('li')
                    .addClass(this.options.selectedClass);
            }
        },

        /**
         * Creates a divider using the given select option.
         *
         * @param {jQuery} element
         */
        createDivider: function(element) {
            var $divider = $(this.options.templates.divider);
            this.$ul.append($divider);
        },

        /**
         * Creates an optgroup.
         *
         * @param {jQuery} group
         */
        createOptgroup: function(group) {            
            if (this.options.enableCollapsibleOptGroups && this.options.multiple) {
                var label = $(group).attr("label");
                var value = $(group).attr("value");
                var r = $('<li class="multiselect-item multiselect-group"><a href="javascript:void(0);"><input type="checkbox" value="' + value + '"/><b> ' + label + '<b class=""></b></b></a></li>');

                if (this.options.enableClickableOptGroups) {
                    r.addClass("multiselect-group-clickable")
                }
                this.$ul.append(r);
                if ($(group).is(":disabled")) {
                    r.addClass("disabled")
                }
                $("option", group).each($.proxy(function($, group) {
                    this.createOptionValue(group)
                }, this))
            }
            else {
                var groupName = $(group).prop('label');

                // Add a header for the group.
                var $li = $(this.options.templates.liGroup);

                if (this.options.enableHTML) {
                    $('label', $li).html(groupName);
                }
                else {
                    $('label', $li).text(groupName);
                }

                if (this.options.enableClickableOptGroups) {
                    $li.addClass('multiselect-group-clickable');
                }

                this.$ul.append($li);

                if ($(group).is(':disabled')) {
                    $li.addClass('disabled');
                }

                // Add the options of the group.
                $('option', group).each($.proxy(function(index, element) {
                    this.createOptionValue(element);
                }, this));
            }
        },

        /**
         * Build the select all.
         * 
         * Checks if a select all has already been created.
         */
        buildSelectAll: function() {
            if (typeof this.options.selectAllValue === 'number') {
                this.options.selectAllValue = this.options.selectAllValue.toString();
            }
            
            var alreadyHasSelectAll = this.hasSelectAll();

            if (!alreadyHasSelectAll && this.options.includeSelectAllOption && this.options.multiple
                    && $('option', this.$select).length > this.options.includeSelectAllIfMoreThan) {

                // Check whether to add a divider after the select all.
                if (this.options.includeSelectAllDivider) {
                    this.$ul.prepend($(this.options.templates.divider));
                }

                var $li = $(this.options.templates.li);
                $('label', $li).addClass("checkbox");
                
                if (this.options.enableHTML) {
                    $('label', $li).html(" " + this.options.selectAllText);
                }
                else {
                    $('label', $li).text(" " + this.options.selectAllText);
                }
                
                if (this.options.selectAllName) {
                    $('label', $li).prepend('<input type="checkbox" name="' + this.options.selectAllName + '" />');
                }
                else {
                    $('label', $li).prepend('<input type="checkbox" />');
                }
                
                var $checkbox = $('input', $li);
                $checkbox.val(this.options.selectAllValue);

                $li.addClass("multiselect-item multiselect-all");
                $checkbox.parent().parent()
                    .addClass('multiselect-all');

                this.$ul.prepend($li);

                $checkbox.prop('checked', false);
            }
        },

        /**
         * Builds the filter.
         */
        buildFilter: function() {

            // Build filter if filtering OR case insensitive filtering is enabled and the number of options exceeds (or equals) enableFilterLength.
            if (this.options.enableFiltering || this.options.enableCaseInsensitiveFiltering) {
                var enableFilterLength = Math.max(this.options.enableFiltering, this.options.enableCaseInsensitiveFiltering);

                if (this.$select.find('option').length >= enableFilterLength) {

                    this.$filter = $(this.options.templates.filter);
                    $('input', this.$filter).attr('placeholder', this.options.filterPlaceholder);
                    
                    // Adds optional filter clear button
                    if(this.options.includeFilterClearBtn){
                        var clearBtn = $(this.options.templates.filterClearBtn);
                        clearBtn.on('click', $.proxy(function(event){
                            clearTimeout(this.searchTimeout);
                            this.$filter.find('.multiselect-search').val('');
                            $('li', this.$ul).show().removeClass("filter-hidden");
                            this.updateSelectAll();
                        }, this));
                        this.$filter.find('.input-group').append(clearBtn);
                    }
                    
                    this.$ul.prepend(this.$filter);

                    this.$filter.val(this.query).on('click', function(event) {
                        event.stopPropagation();
                    }).on('input keydown', $.proxy(function(event) {
                        // Cancel enter key default behaviour
                        if (event.which === 13) {
                          event.preventDefault();
                        }
                        
                        // This is useful to catch "keydown" events after the browser has updated the control.
                        clearTimeout(this.searchTimeout);

                        this.searchTimeout = this.asyncFunction($.proxy(function() {

                            if (this.query !== event.target.value) {
                                this.query = event.target.value;

                                var currentGroup, currentGroupVisible;
                                $.each($('li', this.$ul), $.proxy(function(index, element) {
                                    var value = $('input', element).length > 0 ? $('input', element).val() : "";
                                    var text = $('label', element).text();

                                    var filterCandidate = '';
                                    if ((this.options.filterBehavior === 'text')) {
                                        filterCandidate = text;
                                    }
                                    else if ((this.options.filterBehavior === 'value')) {
                                        filterCandidate = value;
                                    }
                                    else if (this.options.filterBehavior === 'both') {
                                        filterCandidate = text + '\n' + value;
                                    }

                                    if (value !== this.options.selectAllValue && text) {

                                        // By default lets assume that element is not
                                        // interesting for this search.
                                        var showElement = false;

                                        if (this.options.enableCaseInsensitiveFiltering) {
                                            filterCandidate = filterCandidate.toLowerCase();
                                            this.query = this.query.toLowerCase();
                                        }

                                        if (this.options.enableFullValueFiltering && this.options.filterBehavior !== 'both') {
                                            var valueToMatch = filterCandidate.trim().substring(0, this.query.length);
                                            if (this.query.indexOf(valueToMatch) > -1) {
                                                showElement = true;
                                            }
                                        }
                                        else if (filterCandidate.indexOf(this.query) > -1) {
                                            showElement = true;
                                        }

                                        // Toggle current element (group or group item) according to showElement boolean.
                                        $(element).toggle(showElement).toggleClass('filter-hidden', !showElement);
                                        
                                        // Differentiate groups and group items.
                                        if ($(element).hasClass('multiselect-group')) {
                                            // Remember group status.
                                            currentGroup = element;
                                            currentGroupVisible = showElement;
                                        }
                                        else {
                                            // Show group name when at least one of its items is visible.
                                            if (showElement) {
                                                $(currentGroup).show().removeClass('filter-hidden');
                                            }
                                            
                                            // Show all group items when group name satisfies filter.
                                            if (!showElement && currentGroupVisible) {
                                                $(element).show().removeClass('filter-hidden');
                                            }
                                        }
                                    }
                                }, this));
                            }

                            this.updateSelectAll();
                        }, this), 300, this);
                    }, this));
                }
            }
        },

        /**
         * Unbinds the whole plugin.
         */
        destroy: function() {
            this.$container.remove();
            this.$select.show();
            this.$select.data('multiselect', null);
        },

        /**
         * Refreshs the multiselect based on the selected options of the select.
         */
        refresh: function () {
            var inputs = $.map($('li input', this.$ul), $);
            
            $('option', this.$select).each($.proxy(function (index, element) {
                var $elem = $(element);
                var value = $elem.val();
                var $input;
                for (var i = inputs.length; 0 < i--; /**/) {
                    if (value !== ($input = inputs[i]).val())
                        continue; // wrong li

                    if ($elem.is(':selected')) {
                        $input.prop('checked', true);

                        if (this.options.selectedClass) {
                            $input.closest('li')
                                .addClass(this.options.selectedClass);
                        }
                    }
                    else {
                        $input.prop('checked', false);

                        if (this.options.selectedClass) {
                            $input.closest('li')
                                .removeClass(this.options.selectedClass);
                        }
                    }

                    if ($elem.is(":disabled")) {
                        $input.attr('disabled', 'disabled')
                            .prop('disabled', true)
                            .closest('li')
                            .addClass('disabled');
                    }
                    else {
                        $input.prop('disabled', false)
                            .closest('li')
                            .removeClass('disabled');
                    }
                    break; // assumes unique values
                }
            }, this));

            this.updateButtonText();
            this.updateSelectAll();
        },

        /**
         * Select all options of the given values.
         * 
         * If triggerOnChange is set to true, the on change event is triggered if
         * and only if one value is passed.
         * 
         * @param {Array} selectValues
         * @param {Boolean} triggerOnChange
         */
        select: function(selectValues, triggerOnChange) {
            if(!$.isArray(selectValues)) {
                selectValues = [selectValues];
            }

            for (var i = 0; i < selectValues.length; i++) {
                var value = selectValues[i];

                if (value === null || value === undefined) {
                    continue;
                }

                var $option = this.getOptionByValue(value);
                var $checkbox = this.getInputByValue(value);

                if($option === undefined || $checkbox === undefined) {
                    continue;
                }
                
                if (!this.options.multiple) {
                    this.deselectAll(false);
                }
                
                if (this.options.selectedClass) {
                    $checkbox.closest('li')
                        .addClass(this.options.selectedClass);
                }

                $checkbox.prop('checked', true);
                $option.prop('selected', true);
                
                if (triggerOnChange) {
                    this.options.onChange($option, true);
                }
            }

            this.updateButtonText();
            this.updateSelectAll();
        },

        /**
         * Clears all selected items.
         */
        clearSelection: function () {
            this.deselectAll(false);
            this.updateButtonText();
            this.updateSelectAll();
        },

        /**
         * Deselects all options of the given values.
         * 
         * If triggerOnChange is set to true, the on change event is triggered, if
         * and only if one value is passed.
         * 
         * @param {Array} deselectValues
         * @param {Boolean} triggerOnChange
         */
        deselect: function(deselectValues, triggerOnChange) {
            if(!$.isArray(deselectValues)) {
                deselectValues = [deselectValues];
            }

            for (var i = 0; i < deselectValues.length; i++) {
                var value = deselectValues[i];

                if (value === null || value === undefined) {
                    continue;
                }

                var $option = this.getOptionByValue(value);
                var $checkbox = this.getInputByValue(value);

                if($option === undefined || $checkbox === undefined) {
                    continue;
                }

                if (this.options.selectedClass) {
                    $checkbox.closest('li')
                        .removeClass(this.options.selectedClass);
                }

                $checkbox.prop('checked', false);
                $option.prop('selected', false);
                
                if (triggerOnChange) {
                    this.options.onChange($option, false);
                }
            }

            this.updateButtonText();
            this.updateSelectAll();
        },
        
        /**
         * Selects all enabled & visible options.
         *
         * If justVisible is true or not specified, only visible options are selected.
         *
         * @param {Boolean} justVisible
         * @param {Boolean} triggerOnSelectAll
         */
        selectAll: function (justVisible, triggerOnSelectAll) {
            justVisible = (this.options.enableCollapsibleOptGroups && this.options.multiple) ? false : justVisible;
            
            var justVisible = typeof justVisible === 'undefined' ? true : justVisible;
            var allCheckboxes = $("li input[type='checkbox']:enabled", this.$ul);
            var visibleCheckboxes = allCheckboxes.filter(":visible");
            var allCheckboxesCount = allCheckboxes.length;
            var visibleCheckboxesCount = visibleCheckboxes.length;
            
            if(justVisible) {
                visibleCheckboxes.prop('checked', true);
                $("li:not(.divider):not(.disabled)", this.$ul).filter(":visible").addClass(this.options.selectedClass);
            }
            else {
                allCheckboxes.prop('checked', true);
                $("li:not(.divider):not(.disabled)", this.$ul).addClass(this.options.selectedClass);
            }
                
            if (allCheckboxesCount === visibleCheckboxesCount || justVisible === false) {
                $("option:not([data-role='divider']):enabled", this.$select).prop('selected', true);
            }
            else {
                var values = visibleCheckboxes.map(function() {
                    return $(this).val();
                }).get();
                
                $("option:enabled", this.$select).filter(function(index) {
                    return $.inArray($(this).val(), values) !== -1;
                }).prop('selected', true);
            }
            
            if (triggerOnSelectAll) {
                this.options.onSelectAll();
            }
        },

        /**
         * Deselects all options.
         * 
         * If justVisible is true or not specified, only visible options are deselected.
         * 
         * @param {Boolean} justVisible
         */
        deselectAll: function (justVisible) {
            justVisible = (this.options.enableCollapsibleOptGroups && this.options.multiple) ? false : justVisible;
            justVisible = typeof justVisible === 'undefined' ? true : justVisible;
            
            if(justVisible) {              
                var visibleCheckboxes = $("li input[type='checkbox']:not(:disabled)", this.$ul).filter(":visible");
                visibleCheckboxes.prop('checked', false);
                
                var values = visibleCheckboxes.map(function() {
                    return $(this).val();
                }).get();
                
                $("option:enabled", this.$select).filter(function(index) {
                    return $.inArray($(this).val(), values) !== -1;
                }).prop('selected', false);
                
                if (this.options.selectedClass) {
                    $("li:not(.divider):not(.disabled)", this.$ul).filter(":visible").removeClass(this.options.selectedClass);
                }
            }
            else {
                $("li input[type='checkbox']:enabled", this.$ul).prop('checked', false);
                $("option:enabled", this.$select).prop('selected', false);
                
                if (this.options.selectedClass) {
                    $("li:not(.divider):not(.disabled)", this.$ul).removeClass(this.options.selectedClass);
                }
            }
        },

        /**
         * Rebuild the plugin.
         * 
         * Rebuilds the dropdown, the filter and the select all option.
         */
        rebuild: function() {
            this.$ul.html('');

            // Important to distinguish between radios and checkboxes.
            this.options.multiple = this.$select.attr('multiple') === "multiple";

            this.buildSelectAll();
            this.buildDropdownOptions();
            this.buildFilter();

            this.updateButtonText();
            this.updateSelectAll(true);
            
            if (this.options.disableIfEmpty && $('option', this.$select).length <= 0) {
                this.disable();
            }
            else {
                this.enable();
            }
            
            if (this.options.dropRight) {
                this.$ul.addClass('pull-right');
            }
        },

        /**
         * The provided data will be used to build the dropdown.
         */
        dataprovider: function(dataprovider) {
            
            var groupCounter = 0;
            var $select = this.$select.empty();
            
            $.each(dataprovider, function (index, option) {
                var $tag;
                
                if ($.isArray(option.children)) { // create optiongroup tag
                    groupCounter++;
                    
                    $tag = $('<optgroup/>').attr({
                        label: option.label || 'Group ' + groupCounter,
                        disabled: !!option.disabled
                    });
                    
                    forEach(option.children, function(subOption) { // add children option tags
                        $tag.append($('<option/>').attr({
                            value: subOption.value,
                            label: subOption.label || subOption.value,
                            title: subOption.title,
                            selected: !!subOption.selected,
                            disabled: !!subOption.disabled
                        }));
                    });
                }
                else {
                    $tag = $('<option/>').attr({
                        value: option.value,
                        label: option.label || option.value,
                        title: option.title,
                        class: option.class,
                        selected: !!option.selected,
                        disabled: !!option.disabled
                    });
                    $tag.text(option.label || option.value);
                }
                
                $select.append($tag);
            });
            
            this.rebuild();
        },

        /**
         * Enable the multiselect.
         */
        enable: function() {
            this.$select.prop('disabled', false);
            this.$button.prop('disabled', false)
                .removeClass('disabled');
        },

        /**
         * Disable the multiselect.
         */
        disable: function() {
            this.$select.prop('disabled', true);
            this.$button.prop('disabled', true)
                .addClass('disabled');
        },

        /**
         * Set the options.
         *
         * @param {Array} options
         */
        setOptions: function(options) {
            this.options = this.mergeOptions(options);
        },

        /**
         * Merges the given options with the default options.
         *
         * @param {Array} options
         * @returns {Array}
         */
        mergeOptions: function(options) {
            return $.extend(true, {}, this.defaults, this.options, options);
        },

        /**
         * Checks whether a select all checkbox is present.
         *
         * @returns {Boolean}
         */
        hasSelectAll: function() {
            return $('li.multiselect-all', this.$ul).length > 0;
        },

        /**
         * Updates the select all checkbox based on the currently displayed and selected checkboxes.
         */
        updateSelectAll: function(notTriggerOnSelectAll) {
            if (this.hasSelectAll()) {
                var allBoxes = $("li:not(.multiselect-item):not(.filter-hidden) input:enabled", this.$ul);
                var allBoxesLength = allBoxes.length;
                var checkedBoxesLength = allBoxes.filter(":checked").length;
                var selectAllLi  = $("li.multiselect-all", this.$ul);
                var selectAllInput = selectAllLi.find("input");
                
                if (checkedBoxesLength > 0 && checkedBoxesLength === allBoxesLength) {
                    selectAllInput.prop("checked", true);
                    selectAllLi.addClass(this.options.selectedClass);
                    this.options.onSelectAll(true);
                }
                else {
                    selectAllInput.prop("checked", false);
                    selectAllLi.removeClass(this.options.selectedClass);
                    if (checkedBoxesLength === 0) {
                        if (!notTriggerOnSelectAll) {
                            this.options.onSelectAll(false);
                        }
                    }
                }
            }
        },

        /**
         * Update the button text and its title based on the currently selected options.
         */
        updateButtonText: function() {
            var options = this.getSelected();
            
            // First update the displayed button text.
            if (this.options.enableHTML) {
                $('.multiselect .multiselect-selected-text', this.$container).html(this.options.buttonText(options, this.$select));
            }
            else {
                $('.multiselect .multiselect-selected-text', this.$container).text(this.options.buttonText(options, this.$select));
            }
            
            // Now update the title attribute of the button.
            $('.multiselect', this.$container).attr('title', this.options.buttonTitle(options, this.$select));
        },

        /**
         * Get all selected options.
         *
         * @returns {jQUery}
         */
        getSelected: function() {
            return $('option', this.$select).filter(":selected");
        },

        /**
         * Gets a select option by its value.
         *
         * @param {String} value
         * @returns {jQuery}
         */
        getOptionByValue: function (value) {

            var options = $('option', this.$select);
            var valueToCompare = value.toString();

            for (var i = 0; i < options.length; i = i + 1) {
                var option = options[i];
                if (option.value === valueToCompare) {
                    return $(option);
                }
            }
        },

        /**
         * Get the input (radio/checkbox) by its value.
         *
         * @param {String} value
         * @returns {jQuery}
         */
        getInputByValue: function (value) {

            var checkboxes = $('li input', this.$ul);
            var valueToCompare = value.toString();

            for (var i = 0; i < checkboxes.length; i = i + 1) {
                var checkbox = checkboxes[i];
                if (checkbox.value === valueToCompare) {
                    return $(checkbox);
                }
            }
        },

        /**
         * Used for knockout integration.
         */
        updateOriginalOptions: function() {
            this.originalOptions = this.$select.clone()[0].options;
        },

        asyncFunction: function(callback, timeout, self) {
            var args = Array.prototype.slice.call(arguments, 3);
            return setTimeout(function() {
                callback.apply(self || window, args);
            }, timeout);
        },

        setAllSelectedText: function(allSelectedText) {
            this.options.allSelectedText = allSelectedText;
            this.updateButtonText();
        }
    };

    $.fn.multiselect = function(option, parameter, extraOptions) {
        return this.each(function() {
            var data = $(this).data('multiselect');
            var options = typeof option === 'object' && option;

            // Initialize the multiselect.
            if (!data) {
                data = new Multiselect(this, options);
                $(this).data('multiselect', data);
            }

            // Call multiselect method.
            if (typeof option === 'string') {
                data[option](parameter, extraOptions);
                
                if (option === 'destroy') {
                    $(this).data('multiselect', false);
                }
            }
        });
    };

    $.fn.multiselect.Constructor = Multiselect;

    $(function() {
        $("select[data-role=multiselect]").multiselect();
    });

}(window.jQuery);

</script>
</body>
</html>

