<?php

function opt_bar_graph($name) {

$show_setting = opt_settings($name);

if($_GET['hide_graph']==1) 
	{ 
	
		opt_settings($name,'hide'); 
		
		return 0;
	
	}

elseif($show_setting=='show' || $show_setting=='' || $_GET['show_graph']==1)
	{			
		
		opt_settings($name,'show');
		
		return 1;
		
	}
	
	
	
}

function opt_graph_dropdown() {
	
		unset($options);
		
		$track_by = opt_graph_time_group();
		
		$options[0]['name'] = 'Hours';
		$options[0]['value'] = 'hour';
		$options[1]['name'] = 'Days';
		$options[1]['value'] = 'day';
		$options[2]['name'] = 'Months';
		$options[2]['value'] = 'month';
		
		$output = opt_dropdown('page_count',$options,$track_by,$class='','onChange="window.location=\''.opt_url('track_by=').'&track_by=\'+this.value"');
		
		return $output;
		
}

function opt_graph_time_group() {
	
	$date_range = opt_settings('date_range_type');
	
	
	if(!empty($_GET['track_by'])) {

		if($_GET['track_by']=='hour' ||$_GET['track_by']=='day' || $_GET['track_by']=='month') { return $_GET['track_by'];	} else { return 'day'; }
		
	} elseif($date_range=='Today' || $date_range=='Yesterday') {
		
		return 'hour';
		
	} elseif($date_range=='ThisYear') {
		
		return 'month';
		
	} elseif($date_range=='Custom') {	
				
	  $start_date_array = explode('/',opt_settings('start_date'));
	  $end_date_array = explode('/',opt_settings('end_date'));
	  
	  $time_1 = mktime(0,0,0,$start_date_array[0],$start_date_array[1],$start_date_array[2]);
	  $time_2 = mktime(23,59,59,$end_date_array[0],$end_date_array[1],$end_date_array[2]);
	  
	  if(($time_2 - $time_1) <= 86400) {
		  
		  return 'hour';
		  
	  } elseif(($time_2 - $time_1) >= 31536000) {
		  
		  return 'month'; 
		  
	  } elseif(!empty($_GET['track_by'])) { if($_GET['track_by']=='hour' ||$_GET['track_by']=='day' || $_GET['track_by']=='month') { return $_GET['track_by'];	} else { return 'day'; } }	
		
	} else {  return 'day';  }	
	
}


function opt_line_graph($name,$options,$time_created,$query,$order_by,$limit)
{  
	global $wpdb;
	$output = '';

	$track_by = opt_graph_time_group();

	$query = str_replace($limit,'',$query);
	
	
	if($track_by=='day') { $group_by = 'GROUP BY DATE('.$time_created.')'; }
	elseif($track_by=='hour') {  $group_by = 'GROUP BY DATE('.$time_created.'), HOUR('.$time_created.')'; }
	elseif($track_by=='month') { $group_by = 'GROUP BY MONTH('.$time_created.')'; }
	
	$query = str_replace($order_by,$group_by.' ORDER BY '.$time_created.' ASC ',$query);
	
	$distinct_id = str_replace('time_created','id',$time_created);
	
	$query =  preg_replace('/SELECT/', 'SELECT COUNT(DISTINCT '.$distinct_id.') as total_count,', $query, 1);
	
	$query = str_replace('GROUP BY id','',$query);
	
	$data_points = $wpdb->get_results($query);
	
	foreach($data_points as $data)
		{
			if($track_by=='day') { $start_date = mktime(0,0,0,date('n',strtotime($data->time_created)),date('j',strtotime($data->time_created)),date('Y',strtotime($data->time_created))); }
			elseif($track_by=='hour') { $start_date = mktime(date('H',strtotime($data->time_created)),0,0,date('n',strtotime($data->time_created)),date('j',strtotime($data->time_created)),date('Y',strtotime($data->time_created))); }
			elseif($track_by=='month') { $start_date = mktime(0,0,0,date('n',strtotime($data->time_created)),1,date('Y',strtotime($data->time_created))); }
		
			$date_difference = $start_date - $previous_date;
			
			if($track_by=='day' && $date_difference > 86400) { $date_increment = 86400;	}
			elseif($track_by=='hour' && $date_difference > 3600) { $date_increment = 3600;	}
			elseif($track_by=='month' && $date_difference > 2764800) { $date_increment = 2764800;	}
			else { $date_increment = ''; }
			
			if($date_increment != '' && $previous_date!='') {	
					
				while($previous_date < $start_date) {
				
					$previous_date = $previous_date + $date_increment;
					
					if($previous_date < $start_date) {
					
					$output .= '['. $previous_date*1000 .',0],';
					
					}
					
				}
					
				}
			else
				{
					$previous_date = $start_date;						
				}
		
			$output .= '['. $start_date*1000 .','.$data->total_count.'],';
				
			
			
			
		}
		opt_line_graph_js($name,$options,$track_by,rtrim($output,','));

	
}


function opt_line_graph_js($name,$options,$track_by,$data)
{	

if(opt_settings($name)=='show' && $data!='') {
	
?>


<script type="text/javascript">

	jQuery(function () {
    var d1 = { data: [<?php echo  $data  ; ?>], <?php echo  $options  ; ?>};
		
	var options = {
				series: { lines: { show: true, lineWidth: 4 }, points: { show: true } },               
               	grid: { hoverable: true },
                yaxis: { min: 0, minTickSize: 1 },
				legend: {show: false},
			   
			   <?php if($track_by=='day') { ?>
			   
			    xaxis: { mode: "time", minTickSize: [1, "day"], timeformat: "%m/%d/%y"	}
			   
			   <?php } elseif($track_by=='hour') { ?>
			   
			    xaxis: { mode: "time",	minTickSize: [1, "hour"], timeformat: "%H:%M%p %m/%d/%y"	}
			   			   
			   <?php } elseif($track_by=='month') { ?>
			   
			    xaxis: { mode: "time", minTickSize: [1, "month"], timeformat: "%b %y" }
			   
			   <?php } ?>
    };
	
    jQuery.plot(jQuery("#placeholder"), [d1], options);
    function showTooltip(x, y, contents) {
        jQuery('<div id="tooltip">' + contents + '</div>').css( {
            position: 'absolute',
            display: 'none',
            top: y - 15,
            left: x + 10,
            border: '1px solid #add',
            padding: '4px',
            'background-color': '#eff',
            opacity: 0.90
        }).appendTo("body").fadeIn(50);
    }


    var previousPoint = null;
    jQuery("#placeholder").bind("plothover", function (event, pos, item) 	
	{
        jQuery("#x").text(pos.x);
        jQuery("#y").text(pos.y);

            if (item) 
				{
					
                if (previousPoint != item.dataIndex)
					{
						previousPoint = item.dataIndex;
						
			   <?php if($track_by=='day') { ?>
			   
						jQuery("#tooltip").remove();
						var date = new Date(item.datapoint[0] + 86400000);		
						var month = date.getMonth() + 1;
						var day = date.getDate();	
						var hour = date.getHours();
						var x = month + "/" + day + "/" + date.getFullYear() ,
							y = item.datapoint[1].toFixed(0);
						
						showTooltip(item.pageX, item.pageY,
									y + " " + item.series.label + " on " + x);			   
			   
			   
			   <?php } elseif($track_by=='hour') { ?>
			   
						jQuery("#tooltip").remove();
						var date = new Date(item.datapoint[0] + 86400000);		
						var month = date.getMonth() + 1;
						var day = date.getDate();	
						var hour = date.getHours();
						var x = hour + ":00 " + month + "/" + day + "/" + date.getFullYear() ,
							y = item.datapoint[1].toFixed(0);
						
						showTooltip(item.pageX, item.pageY,
									y + " " + item.series.label + " during " + x);					   
			   
	   
			   <?php } elseif($track_by=='month') { ?>
			   
						jQuery("#tooltip").remove();
						var date = new Date(item.datapoint[0] + 86400000);		
						var month = date.getMonth() + 1;
						var x = month + "/" + date.getFullYear() ,
							y = item.datapoint[1].toFixed(0);
						
						showTooltip(item.pageX, item.pageY,
									y + " " + item.series.label + " during " + x);		
			   
			   
			   
			   <?php } ?>
					}
            	}
            else 
				{
					jQuery("#tooltip").remove();
					previousPoint = null;            
            	}
				
	});
	
});
	
  </script>


<?php
}

}


function opt_bar_graph_js($name,$items,$ticks,$in_clicks,$out_clicks,$conversions,$visitors,$impressions,$income,$expense) {


if($ticks!='' && opt_settings($name)=='show') {
	
?>	
<script type="text/javascript">
jQuery(document).ready(function () {
	
	
    function currencyFormatter(v, axis) {
        return  v.toFixed(2);
    }
	
    var d1_1 = [<?php echo  rtrim($in_clicks,',')  ; ?>]; 
    var d1_2 = [<?php echo  rtrim($out_clicks,',')  ; ?>]; 
    var d1_3 = [<?php echo  rtrim($conversions,',')  ; ?>]; 
    var d1_4 = [<?php echo  rtrim($visitors,',')  ; ?>]; 
    var d1_5 = [<?php echo  rtrim($impressions,',')  ; ?>];
    var d1_6 = [<?php echo  rtrim($expense,',')  ; ?>]; 
    var d1_7 = [<?php echo  rtrim($income,',')  ; ?>]; 
 	
    var data1 = [
	<?php if($in_clicks!='')  { ?>
        {
            label: "Optins",
            data: d1_1,
            bars: {
                show: true,
                barWidth: 0.1,
                fill: true,
                lineWidth: 0,
                order: 1,
                fillColor:  "#02ad47"
            },
			color:"#02ad47"
        },
	<?php } if($out_clicks!='') { ?>	
        {
            label: "OptinLink Clicks",
            data: d1_2,
            bars: {
                show: true,
                barWidth: 0.1,
                fill: true,
                lineWidth: 0,
                order: 2,
                fillColor:  "#62accb"
            },
			color:"#62accb"
        },
	<?php } if($conversions!='') { ?>	
        {
            label: "OptinLink Views",
            data: d1_3,
            bars: {
                show: true,
                barWidth: 0.1,
                fill: true,
                lineWidth: 0,
                order: 3,
                fillColor:  "#215a72"
            },
			color:"#215a72"
        },
	<?php } if($visitors!='') { ?>	
        {
            label: "Form Closes",
            data: d1_4,
            bars: {
                show: true,
                barWidth: 0.1,
                fill: true,
                lineWidth: 0,
                order: 4,
                fillColor:  "#d34422"
            },
			color:"#d34422"
        },
	<?php } if($impressions!='') { ?>	
        {
            label: "Visitors",
            data: d1_5,
            bars: {
                show: true,
                barWidth: 0.1,
                fill: true,
                lineWidth: 0,
                order: 5,
                fillColor:  "#ff8103"
            },
			color:"#ff8103"
        },
	<?php } if($expense!='') { ?>	
        {
            label: "Expense",
            data: d1_6,
            bars: {
                show: true,
                barWidth: 0.1,
                fill: true,
                lineWidth: 0,
                order: 6,
                fillColor:  "#AA0000"
            },
           color:  "#AA0000", 
		   yaxis: 2
        },
	<?php }  if($expense!='') { ?>	
        {
            label: "Income",
            data: d1_7,
            bars: {
                show: true,
                barWidth: 0.1,
                fill: true,
                lineWidth: 0,
                order: 7,
                fillColor:  "#008800"
            },
           color:  "#008800", 
		   yaxis: 2
        }
	 <?php } ?>
	
    ];
 
 	var options = {
        xaxis: {
            min: -0.5,
			max:<?php echo  $items  ; ?>.5,
            tickSize: 1,
			ticks: [<?php echo  rtrim($ticks,',')  ; ?>],
            tickLength: 0
        },
        yaxes: [{ min: 0, minTickSize: 1 },
			{ minTickSize: 0, tickFormatter: currencyFormatter,  position: "right" }],
        grid: {
            hoverable: true,
            clickable: false,
            borderWidth: 1
        },
        legend: {
            show: false
        },
        series: {
            shadowSize: 0
        }
	}
 
    function showTooltip(x, y, contents, z) {
        jQuery('<div id="flot-tooltip">' + contents + '</div>').css({
            top: y - 20,
            left: x - 90,
            'border-color': z,
        }).appendTo("body").show();
    }
	
	
  	var previousPoint = null;
    jQuery("#placeholder").bind("plothover", function (event, pos, item) 	
	{
        jQuery("#x").text(pos.x);
        jQuery("#y").text(pos.y);

            if (item) 
				{
					
                if (previousPoint != item.dataIndex)
					{
						previousPoint = item.dataIndex;
			   
						jQuery("#tooltip").remove();
						
						if(item.series.label=='Income' || item.series.label=='Expense') { y = '<?php echo  WPMT_CURRENCY_SYMBOL ?>'+item.datapoint[1].toFixed(2); }
						else { y = item.datapoint[1].toFixed(0); }
						
						
							
						
						showTooltip(item.pageX, item.pageY,
									y + " " + item.series.label);			   
			   
					}
            	}
            else 
				{
					jQuery("#tooltip").remove();
					previousPoint = null;            
            	}
				
	});
	

    function showTooltip(x, y, contents) {
        jQuery('<div id="tooltip">' + contents + '</div>').css( {
            position: 'absolute',
            display: 'none',
            top: y,
            left: x + 20,
            border: '1px solid #add',
            padding: '4px',
            'background-color': '#eff',
            opacity: 0.90
        }).appendTo("body").fadeIn(50);
    }
 
 	
    var choiceContainer = jQuery("#choices");
	
    jQuery.each(data1, function(key, val) {
		
        choiceContainer.append('<a class="opt_header_link" style="line-height:10px; font-size:14px;  margin-top:1px;"><input type="checkbox" name="' + key + '" checked="checked" id="id' + key + '" style="vertical-align:middle;">' + '<label for="id' + key + '" style="margin-left:4px; font-weight:bold; color:'+ val.color +'; vertical-align:middle;">'  + val.label  + '</label></a>');
	
    });
	
    choiceContainer.find("input").click(plotAccordingToChoices);
	
	   
    function plotAccordingToChoices() 
	{
        var data = [];

        choiceContainer.find("input:checked").each(function () {
            var key = jQuery(this).attr("name");
            if (key && data1[key])
			{
				data.push(data1[key]);				
			}
				
        });

        if (data.length > 0) {
				
				jQuery("#overview").bind("plotselected", function (event, ranges) {
					plot.setSelection(ranges);
				});
				
	
   				var plot = jQuery.plot(jQuery("#placeholder"), data, options);
				
		}
    }

   plotAccordingToChoices();

});
</script>
 
<?php	

	}
	
}



?>