<?php

/*
  MailBeez Automatic Trigger Email Campaigns
  http://www.mailbeez.com

  Copyright (c) 2010, 2011 MailBeez

  inspired and in parts based on
  Copyright (c) 2003 osCommerce

  Released under the GNU General Public License
 */

require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/dashboardbeez_analytics.php');

class dashboard_beez_o_graph extends dashboardbeez_analytics
{

    var $code;
    var $module;
    var $title;
    var $description;
    var $sort_order;
    var $enabled = false;


    function __construct()
    {
        parent::__construct();
        $this->code = 'dashboard_beez_o_graph';
        $this->module = 'dashboard_beez_o_graph';
        $this->version = '3.0'; // float value
        $this->required_mb_version = 2.99;
        $this->title = mh_lng('MAILBEEZ_DASHBOARD_BEEZ_O_GRAPH_TITLE');
        $this->description = mh_lng('MAILBEEZ_DASHBOARD_BEEZ_O_GRAPH_DESC');
        $this->description_image = '../../common/images/icon_ma_64.png';
        $this->icon = '../../common/images/icon_ma.png';
        //$this->removable = false; // can't be removed
        $this->enabled = mh_cfg('MAILBEEZ_DASHBOARD_BEEZ_O_GRAPH_STATUS') == 'True';
        $this->removable = false; // can't be removed
        $this->hidden = false;

        $this->status_key = 'MAILBEEZ_DASHBOARD_BEEZ_O_GRAPH_STATUS';
        $this->documentation_root = 'https://www.mailbeez.com/documentation/dashboardbeez/';
        $this->documentation_key = $this->module;

        $this->admin_action_plugins_path = MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'dashboardbeez/'; // default-path to include admin action plugins from
        $this->admin_action_plugins = '';

        $this->sort_order = mh_cfg('MAILBEEZ_DASHBOARD_BEEZ_O_GRAPH_SORT_ORDER');
        // set cache reference
        $this->set_selected_module(mh_get('selected_module'));
        $this->set_selected_campaign(mh_get('selected_campaign'));
        $this->set_selected_campaign_item(mh_get('selected_campaign_item'));
        $this->set_date_frame(mh_get('selected_startdate'), mh_get('selected_enddate'));
        $this->_set_cache_id();

    }


    function generateData($refresh = false)
    {
        // return cached value if exists
        // also return if outdated
        if (!$refresh && $cache = $this->read_cache("app", true)) {
            return $cache['value'];
        }


        $exclude_modules_sql = '';

        $selected_module_sql = '';
        $selected_module_iteration_sql = '';
        $selected_campaign_sql = '';

        if ((int)$this->selected_campaign_item > 0) {
            $selected_campaign_sql = " and module = '" . $this->selected_module . "' and iteration='" . (int)$this->selected_campaign_item . "'";
        } elseif ($this->selected_campaign != '') {
            // get iterations for campaign
            $selected_campaign_sql = " and module = '" . $this->selected_module . "' and iteration in (" . $this->selected_campaign_item_ids . ")";
//            echo $selected_campaign_sql;
        } elseif ($this->selected_module != '') {
            $selected_module_sql = " and module = '" . $this->selected_module_base . "' ";
            if ($this->selected_module_iteration_loopstart) {
                $selected_module_iteration_sql = " and iteration >= " . (int)$this->selected_module_iteration_loopstart . " ";
            } elseif ($this->selected_module_iteration) {
                $selected_module_iteration_sql = " and iteration = " . (int)$this->selected_module_iteration . " ";
            }
        }

        // set default startdate
        $start_date = "date_sub(curdate(), interval " . mh_cfg('MAILBEEZ_DASHBOARD_BEEZ_O_GRAPH_PASSED_DAYS_SKIP') . " day)";
        // set default enddate
        $end_date = "";
        // set default enddate
        $reference_time = time();

        if ($this->start_date_db) {
            $start_date = "'$this->start_date_db'";
        }

        if ($this->end_date_db) {
            $end_date = "'$this->end_date_db'";

            // format given in mailbeez_system::convert_realdate_to_db
            list($a_year, $a_month, $a_day) = explode('-',$this->end_date_db) ;

//            $a = strptime($this->end_date_db, '%Y-%m-%d');
//            $timestamp = mktime(0, 0, 0, $a['tm_mon'] + 1, $a['tm_mday'], $a['tm_year'] + 1900);

            $timestamp = mktime(0, 0, 0, (int)$a_month, (int)$a_day, (int)$a_year );

            $reference_time = $timestamp;
        }

        // set default endate
        $timeframe_days = mh_cfg('MAILBEEZ_DASHBOARD_BEEZ_O_GRAPH_PASSED_DAYS_SKIP');

        // todo
        // calculate days between $this->start_date and $this->end_date

        if ($this->start_date_db) {

            $date_start = strtotime($this->start_date_db);
            $date_end = ($this->end_date_db) ? strtotime($this->end_date_db) : time();
            $timeframe_days = floor(($date_end - $date_start) / (60 * 60 * 24));

        }

        $days = array();
        for ($i = 0; $i < $timeframe_days; $i++) {
            // todo - fix calculation for timeframe
            $days[date('Y-m-d', strtotime('-' . $i . ' days', $reference_time))] = 0;
        }

        $days_sent_array = $days;
        $days_bounce_array = $days;
        $days_opened_array = $days;
        $days_clicked_array = $days;
        $days_ordered_array = $days;
        $days_revenue_array = $days;

        $result = false;


        $start_date_tracking_sql = "";
        $start_date_block_sql = "";
        $start_date_revenue_sql = "";
        $end_date_tracking_sql = "";
        $end_date_block_sql = "";
        $end_date_revenue_sql = "";


        $js_array_sent = '';
        $js_array_bounce = '';
        $js_array_open = '';
        $js_array_clicked = '';
        $js_array_revenue = '';
        $js_array_ordered = '';
        $js_array_block = '';

        if ($start_date) {
            $start_date_tracking_sql = " and " . $start_date . " <= t.date_sent";
            $start_date_block_sql = " and " . $start_date . " <= date_block";
            $start_date_revenue_sql = " and " . $start_date . " <= date_record";
        }


        if ($end_date) {
            $end_date_tracking_sql = " and " . $end_date . " >= t.date_sent";
            $end_date_block_sql = " and " . $end_date . " >= date_block";
            $end_date_revenue_sql = " and " . $end_date . " >= date_record";
        }


        $mailbeez_sent_query_sql = "select date_format(t.date_sent, '%Y-%m-%d') as dateday,
                                        count(t.autoemail_id) as sent_count,
                                        SUM(IF(t.bounce_status = 'H' or t.bounce_status = 'S', 1,0)) AS cnt_bounces,
                                        SUM(IF(t.opened > '2000-01-01 00:00:00', 1,0)) AS cnt_opened,
                                        SUM(IF(t.clicked > '2000-01-01 00:00:00', 1,0)) AS cnt_clicked,
                                        SUM(IF(t.ordered > '2000-01-01 00:00:00', 1,0)) AS cnt_ordered
                                        from " . TABLE_MAILBEEZ_TRACKING . " t
                                    where true
                                        " . $start_date_tracking_sql . "
                                        " . $end_date_tracking_sql . "
                                        " . $exclude_modules_sql . "
                                        " . $selected_module_sql . "
                                        " . $selected_module_iteration_sql . "
                                        " . $selected_campaign_sql . "
                                        " . str_replace('simulation', 't.simulation', MAILBEEZ_SIMULATION_SQL) . "
                                        group by dateday";
        $mailbeez_sent_query = mh_db_query($mailbeez_sent_query_sql);
        while ($mailbeez_sent_cnt = mh_db_fetch_array($mailbeez_sent_query)) {
            $result = true;
            $days_sent_array[$mailbeez_sent_cnt['dateday']] = $mailbeez_sent_cnt['sent_count'];
            $days_bounce_array[$mailbeez_sent_cnt['dateday']] = $mailbeez_sent_cnt['cnt_bounces'];
            $days_opened_array[$mailbeez_sent_cnt['dateday']] = $mailbeez_sent_cnt['cnt_opened'];
            $days_clicked_array[$mailbeez_sent_cnt['dateday']] = $mailbeez_sent_cnt['cnt_clicked'];
            $days_ordered_array[$mailbeez_sent_cnt['dateday']] = $mailbeez_sent_cnt['cnt_ordered'];
        }

        if ($result) {
            $days_sent_array = array_reverse($days_sent_array, true);
            $days_bounce_array = array_reverse($days_bounce_array, true);
            $days_opened_array = array_reverse($days_opened_array, true);
            $days_clicked_array = array_reverse($days_clicked_array, true);
            $days_ordered_array = array_reverse($days_ordered_array, true);



            foreach ($days_sent_array as $date => $sent) {
                $js_array_sent .= '[' . (mktime(0, 0, 0, substr($date, 5, 2), substr($date, 8, 2), substr($date, 0, 4)) * 1000) . ', ' . $sent . '],';
            }
            foreach ($days_bounce_array as $date => $bounce) {
                $js_array_bounce .= '[' . (mktime(0, 0, 0, substr($date, 5, 2), substr($date, 8, 2), substr($date, 0, 4)) * 1000) . ', ' . $bounce . '],';
            }
            foreach ($days_opened_array as $date => $opened) {
                $js_array_open .= '[' . (mktime(0, 0, 0, substr($date, 5, 2), substr($date, 8, 2), substr($date, 0, 4)) * 1000) . ', ' . $opened . '],';
            }
            foreach ($days_clicked_array as $date => $clicked) {
                $js_array_clicked .= '[' . (mktime(0, 0, 0, substr($date, 5, 2), substr($date, 8, 2), substr($date, 0, 4)) * 1000) . ', ' . $clicked . '],';
            }
            foreach ($days_ordered_array as $date => $ordered) {
                $js_array_ordered .= '[' . (mktime(0, 0, 0, substr($date, 5, 2), substr($date, 8, 2), substr($date, 0, 4)) * 1000) . ', ' . $ordered . '],';
            }
            if (!empty($js_array_sent)) {
                $js_array_sent = substr($js_array_sent, 0, -1);
            }
            if (!empty($js_array_bounce)) {
                $js_array_bounce = substr($js_array_bounce, 0, -1);
            }
            if (!empty($js_array_open)) {
                $js_array_open = substr($js_array_open, 0, -1);
            }
            if (!empty($js_array_clicked)) {
                $js_array_clicked = substr($js_array_clicked, 0, -1);
            }
            if (!empty($js_array_ordered)) {
                $js_array_ordered = substr($js_array_ordered, 0, -1);
            }


            $js_array_block = '';
            $days_block_array = $days;

            if (($selected_campaign_sql == '')) {

                $mailbeez_block_query_sql = "select date_format(date_block, '%Y-%m-%d') as dateday, count(distinct customers_id) as block_count
                                        from " . TABLE_MAILBEEZ_BLOCK . "
                                    where true
                                        " . $start_date_block_sql . "
                                        " . $end_date_block_sql . "
                                        " . $exclude_modules_sql . "
                                        " . $selected_module_sql . "
                                        
                                        " . MAILBEEZ_SIMULATION_SQL . "
                                        group by dateday";
//echo $mailbeez_block_query_sql; mh_exit();
                $mailbeez_block_query = mh_db_query($mailbeez_block_query_sql);
                while ($mailbeez_block_cnt = mh_db_fetch_array($mailbeez_block_query)) {
                    $days_block_array[$mailbeez_block_cnt['dateday']] = $mailbeez_block_cnt['block_count'];
                }

                $days_block_array = array_reverse($days_block_array, true);

                foreach ($days_block_array as $date => $blocked) {
                    $js_array_block .= '[' . (mktime(0, 0, 0, substr($date, 5, 2), substr($date, 8, 2), substr($date, 0, 4)) * 1000) . ', ' . $blocked . '],';
                }

                if (!empty($js_array_block)) {
                    $js_array_block = substr($js_array_block, 0, -1);
                }
            }


            // module

            $mailbeez_revenue_query_sql = "select date_format(mo.date_record, '%Y-%m-%d') as dateday, sum(ot.value) as revenue_value from
                                (select distinct mto.orders_id, date_record
                                    from " . TABLE_MAILBEEZ_TRACKING_ORDERS . "  mto
                                        left join " . TABLE_MAILBEEZ_TRACKING . " mt on (mto.message_id = mt.message_id)
                                    where true
                                        " . $start_date_revenue_sql . "
                                        " . $end_date_revenue_sql . "
                                        " . $exclude_modules_sql . "
                                        " . $selected_module_sql . "
                                        " . $selected_module_iteration_sql . "
                                        " . $selected_campaign_sql . "                                        
                                    group by mto.orders_id
                                 ) mo
                              join " . TABLE_ORDERS_TOTAL . " ot
                                on (ot.orders_id = mo.orders_id and class='ot_total')
                              where 1
                              group by dateday
                              ";

            $mailbeez_revenue_query = mh_db_query($mailbeez_revenue_query_sql);
            while ($mailbeez_revenue_cnt = mh_db_fetch_array($mailbeez_revenue_query)) {
                $days_revenue_array[$mailbeez_revenue_cnt['dateday']] = $mailbeez_revenue_cnt['revenue_value'];
            }

            $days_revenue_array = array_reverse($days_revenue_array, true);

            foreach ($days_revenue_array as $date => $revenue) {
                $js_array_revenue .= '[' . (mktime(0, 0, 0, substr($date, 5, 2), substr($date, 8, 2), substr($date, 0, 4)) * 1000) . ', ' . $revenue . '],';
            }


            if (!empty($js_array_revenue)) {
                $js_array_revenue = substr($js_array_revenue, 0, -1);
            }

        }

//        echo "not cached";
        $data = array($js_array_sent, $js_array_bounce, $js_array_open, $js_array_clicked, $js_array_ordered, $js_array_block, $js_array_revenue);
        return $this->set_cache($data, 'app'); // session | request | app


    }


    function generateOutput($ajax = false, $refresh = false)
    {
        list($js_array_sent, $js_array_bounce, $js_array_open, $js_array_clicked, $js_array_ordered, $js_array_block, $js_array_revenue) = $this->generateData($refresh);


        $label_icon = " <img src='" . mh_cfg('MH_CATALOG_SERVER') . mh_cfg('MH_DIR_WS_CATALOG') . mh_cfg('MH_ROOT_PATH') . "common/images/details.png' width='9' height='9' align='absmiddle' hspace='3' border='0'>";

        $label_icon = addslashes($label_icon);

        $chart_label_block = mh_output_string(MAILBEEZ_DASHBOARD_BEEZ_O_GRAPH_BLOCK_LINK) . $label_icon;
        $chart_label_block_link = mh_href_link(FILENAME_MAILBEEZ, 'module=report_block&app=load_app&app_path=report_block/report_block.php&popup=true' . $this->filterparam);

        $chart_label_sent = mh_output_string(MAILBEEZ_DASHBOARD_BEEZ_O_GRAPH_SENT_LINK) . $label_icon;
        $chart_label_sent_link = mh_href_link(FILENAME_MAILBEEZ, 'module=report_track&app=load_app&app_path=report_track/report_track.php&back=dashboard&popup=true' . $this->filterparam);

        $chart_label_bounce = mh_output_string(MAILBEEZ_DASHBOARD_BEEZ_O_GRAPH_BOUNCE_LINK) . $label_icon;
        $chart_label_bounce_link = mh_href_link(FILENAME_MAILBEEZ, 'module=report_track&app=load_app&app_path=report_track/report_track.php&back=dashboard&filter=bounce&popup=true' . $this->filterparam);

        $chart_label_opened = mh_output_string(MAILBEEZ_DASHBOARD_BEEZ_O_GRAPH_OPENED_LINK) . $label_icon;
        $chart_label_opened_link = mh_href_link(FILENAME_MAILBEEZ, 'module=report_track&app=load_app&app_path=report_track/report_track.php&back=dashboard&filter=opened&popup=true' . $this->filterparam);

        $chart_label_clicked = mh_output_string(MAILBEEZ_DASHBOARD_BEEZ_O_GRAPH_CLICKED_LINK) . $label_icon;
        $chart_label_clicked_link = mh_href_link(FILENAME_MAILBEEZ, 'module=report_track&app=load_app&app_path=report_track/report_track.php&back=dashboard&filter=clicked&popup=true' . $this->filterparam);

        $chart_label_ordered = mh_output_string(MAILBEEZ_DASHBOARD_BEEZ_O_GRAPH_ORDERED_LINK) . $label_icon;
        $chart_label_ordered_link = mh_href_link(FILENAME_MAILBEEZ, 'module=report_track&app=load_app&app_path=report_track/report_track.php&back=dashboard&filter=ordered&popup=true' . $this->filterparam);

        $chart_revenue_link = mh_href_link(FILENAME_MAILBEEZ, 'module=report_track&app=load_app&app_path=report_track/report_track.php&back=dashboard&filter=ordered&popup=true' . $this->filterparam . '&order_time_stamp=');

        $cur_str = mh_price(0);
        $cur_str = preg_replace('/[0-9\.,]/', '', $cur_str);
        $cur_str = (stristr($cur_str, 'eur')) ? 'Eur' : $cur_str;
        //$cur_str = html_entity_decode($cur_str, ENT_QUOTES, 'ISO-8859-1');
        ob_start();
        ?>
        <div id="WidgetTitle"><?php echo mh_lng('MAILBEEZ_DASHBOARD_BEEZ_O_GRAPH_TITLE'); ?></div>
        <div id="WidgetSubTitle"><?php

            if (!$this->start_date_db && !$this->end_date_db && !$this->selected_module) {
                echo sprintf(mh_lng('MAILBEEZ_DASHBOARD_BEEZ_O_GRAPH_DESC'), mh_cfg('MAILBEEZ_DASHBOARD_BEEZ_O_GRAPH_PASSED_DAYS_SKIP'));
            } else {
                echo '&nbsp;';
//                echo "123 " . $this->filterparam;
            }
            ?>
            <?php if (mh_cfg('MAILBEEZ_ANALYTICS_STATUS') == 'False') { ?>
                |
                <?php echo mb_admin_button(mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=config_analytics/admin_application_plugins/confirm.php&popup=true'), mh_lng('MAILBEEZ_ANALYTICS_STATUS_BUTTON'), '', 'popup', 'link', '', 'document', 'iframe width:600 height:500'); ?>
            <?php } ?>
            <div style="position: absolute; top: 30px; right: 15px;"><?php echo $cur_str; ?></div>
        </div>
        <div id="beez_o_meter" style="width: 100%; height: 270px; margin-top: 5px;"></div>
        <script type="text/javascript">
            var plot_beez_o_meter_sent = [<?php echo $js_array_sent ?>];
            var plot_beez_o_meter_bounced = [<?php echo $js_array_bounce ?>];
            var plot_beez_o_meter_opened = [<?php echo $js_array_open ?>];
            var plot_beez_o_meter_clicked = [<?php echo $js_array_clicked ?>];
            var plot_beez_o_meter_ordered = [<?php echo $js_array_ordered ?>];
            var plot_beez_o_meter_block = [<?php echo $js_array_block ?>];
            var plot_beez_o_meter_revenue = [<?php echo $js_array_revenue ?>];
            var bzData = [
                <?php if (mh_cfg('MH_ORDERTRACKER_ENABLED')) { ?>
                {
                    data: plot_beez_o_meter_revenue,
                    bars: {
                        show: true,
                        align: "center",
                        barWidth: 0.8 * 1 * 24 * 60 * 60 * 1000,
                        fill: true,
                        lineWidth: 1
                    },

                    color: '<?php echo mh_cfg('MH_COLOR_GREEN');?>' /*'#abd37f'*/,
                    shadowSize: 0,
                    yaxis: 2

                },
                <?php } ?>
                {
                    label: '<?php echo $chart_label_sent ?>',
                    data: plot_beez_o_meter_sent,
                    lines: {show: true, fill: true, lineWidth: 2},
                    points: {show: true, radius: 1},
                    color: '<?php echo mh_cfg('MH_COLOR_DARKYELLOW');?>',
                    shadowSize: 0,
                    clickable: false
                },
                <?php if (mh_cfg('MH_OPENTRACKER_ENABLED')) { ?>
                {
                    label: '<?php echo $chart_label_opened ?>',
                    data: plot_beez_o_meter_opened,
                    lines: {show: true, fill: false},
                    points: {show: true, radius: 1},
                    color: '<?php echo mh_cfg('MH_COLOR_BLUE');?>' /*'#9ac2df'*/,
                    shadowSize: 0,
                    clickable: false

                },
                <?php } ?>
                <?php if (mh_cfg('MH_CLICKTRACKER_ENABLED')) { ?>
                {
                    label: '<?php echo $chart_label_clicked ?>',
                    data: plot_beez_o_meter_clicked,
                    lines: {show: true, fill: false},
                    points: {show: true, radius: 1},
                    color: '<?php echo mh_cfg('MH_COLOR_ORANGE');?>' /*'#7e9662'*/,
                    shadowSize: 0,
                    clickable: false

                },
                <?php } ?>
                <?php if (mh_cfg('MH_ORDERTRACKER_ENABLED')) { ?>
                {
                    label: '<?php echo $chart_label_ordered ?>',
                    data: plot_beez_o_meter_ordered,
                    lines: {show: true, fill: false},
                    points: {show: true, radius: 1},
                    color: '<?php echo mh_cfg('MH_COLOR_GREEN');?>' /*'#abd37f'*/,
                    shadowSize: 0,
                    clickable: false

                },
                <?php } ?>
                <?php if (mh_cfg('MH_BOUNCEHANDLING_ENABLED')) { ?>
                {
                    label: '<?php echo $chart_label_bounce ?>',
                    data: plot_beez_o_meter_bounced,
                    lines: {show: true, fill: false, lineWidth: 2},
                    points: {show: true, radius: 1},
                    color: '<?php echo mh_cfg('MH_COLOR_PINK');?>' /*'#ece288'*/,
                    shadowSize: 0,
                    clickable: false

                },
                <?php } ?>
                {
                    label: '<?php echo $chart_label_block ?>',
                    data: plot_beez_o_meter_block,
                    lines: {show: true, fill: false, lineWidth: 1},
                    points: {show: true, radius: 1},
                    color: '#9e9e9e',
                    shadowSize: 0
                }


            ];
            var bzOptions = {
                xaxes: [
                    {
                        ticks: 7,
                        mode: 'time'
                    }
                ],
                yaxes: [
                    {
                        min: 0,
                        position: 'left'
                    },
                    {
                        position: 'right',

                        tickFormatter: function (v, axis) {
                            return v + "<?php // echo $cur_str ?>";
                        }

                    }
                ],
                grid: {
                    backgroundColor: {colors: ['#fcfcfc', '#f0f0f0']},
                    hoverable: true,
                    clickable: true,
                    autoHighlight: true,
                    borderColor: '#888',
                    fontFamily: 'Trebuchet MS, Arial'
                },
                legend: {
                    position: 'nw',
                    labelFormatter: function (label, series) {
                        if (label == '<?php echo $chart_label_sent ?>') {
                            return '<a onclick="return openReportPopup(\'<?php echo $chart_label_sent_link; ?>\')" href="<?php echo $chart_label_sent_link; ?>">' + label + '</a>';
                        }
                        if (label == '<?php echo $chart_label_bounce ?>') {
                            return '<a onclick="return openReportPopup(\'<?php echo $chart_label_bounce_link; ?>\')" href="<?php echo $chart_label_bounce_link; ?>">' + label + '</a>';
                        }
                        if (label == '<?php echo $chart_label_opened ?>') {
                            return '<a onclick="return openReportPopup(\'<?php echo $chart_label_opened_link; ?>\')" href="<?php echo $chart_label_opened_link; ?>">' + label + '</a>';
                        }
                        if (label == '<?php echo $chart_label_clicked ?>') {
                            return '<a onclick="return openReportPopup(\'<?php echo $chart_label_clicked_link; ?>\')" href="<?php echo $chart_label_clicked_link; ?>">' + label + '</a>';
                        }
                        if (label == '<?php echo $chart_label_ordered ?>') {
                            return '<a onclick="return openReportPopup(\'<?php echo $chart_label_ordered_link; ?>\')" href="<?php echo $chart_label_ordered_link; ?>">' + label + '</a>';
                        }
                        <?php if ($js_array_block != '') { ?>

                        if (label == '<?php echo $chart_label_block ?>') {
                            return '<a onclick="return openReportPopup(\'<?php echo $chart_label_block_link; ?>\')" href="<?php echo $chart_label_block_link; ?>">' + label + '</a>';
                        }
                        <?php } ?>

                    },
                    backgroundOpacity: 0.05
                }
            };




            <?php if ($refresh) {
            ?>
            jQuery(document).ready(function () {
                jQuery.plot(jQuery("#beez_o_meter"), bzData, bzOptions);
            });
            <?php
            } else {
            if (MH_PLATFORM_GAMBIO >= 2.6) { ?>
            $('body').on('JSENGINE_INIT_FINISHED', function () {
                setTimeout('jQuery.plot(jQuery("#beez_o_meter"), bzData, bzOptions)', 100);
            });
            <?php
            } else {
            ?>
            jQuery(document).ready(function () {
                setTimeout('jQuery.plot(jQuery("#beez_o_meter"), bzData, bzOptions)', 100);
            });
            <?php
            }
            }
            ?>


            function showTooltip(x, y, contents) {
                jQuery('<div id="tooltip">' + contents + '</div>').css({
                    position: 'absolute',
                    display: 'none',
                    top: y + 5,
                    left: x + 15,
                    border: '1px solid #fdd',
                    padding: '2px',
                    backgroundColor: '#fee',
                    fontFamily: 'Arial',
                    fontSize: '10px',
                    opacity: 0.80
                }).appendTo('body').fadeIn(200);
            }

            var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

            var previousPoint = null;
            jQuery('#beez_o_meter').bind('plothover', function (event, pos, item) {
                if (item) {
                    if (previousPoint != item.datapoint) {
                        previousPoint = item.datapoint;

                        jQuery('#tooltip').remove();
                        var x = item.datapoint[0],
                            y = item.datapoint[1],
                            xdate = new Date(x);

                        showTooltip(item.pageX, item.pageY, y + ' for ' + monthNames[xdate.getMonth()] + '-' + xdate.getDate());
                    }
                } else {
                    jQuery('#tooltip').remove();
                    previousPoint = null;
                }
            });


            $("#beez_o_meter").bind("plotclick", function (event, pos, item) {
//               alert("You clicked at " + pos.x + ", " + pos.y);
                // axis coordinates for other axes, if present, are in pos.x2, pos.x3, ...
                // if you need global screen coordinates, they are pos.pageX, pos.pageY

                if (item) {
//                    highlight(item.series, item.datapoint);
                    openReportPopup("<?php echo $chart_revenue_link ?>" + item.datapoint)
                }
            });

        </script>
        <?php
        $output = ob_get_contents();
        ob_end_clean();

        return $output;
    }

    function check()
    {
        return true;
    }

    function install()
    {
        mh_insert_config_value(array('configuration_title' => 'Show MailBeez Beez-O-Graph',
            'configuration_key' => 'MAILBEEZ_DASHBOARD_BEEZ_O_GRAPH_STATUS',
            'configuration_value' => 'True',
            'configuration_description' => 'Do you want to show the MailBeez Beez-O-Graph on the dashboard? (recommended)',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Count this number of past days:',
            'configuration_key' => 'MAILBEEZ_DASHBOARD_BEEZ_O_GRAPH_PASSED_DAYS_SKIP',
            'configuration_value' => '30',
            'configuration_description' => 'number of past days to use for calculation',
            'set_function' => ''
        ));


        mh_insert_config_value(array('configuration_title' => 'Sort order of display.',
            'configuration_key' => 'MAILBEEZ_DASHBOARD_BEEZ_O_GRAPH_SORT_ORDER',
            'configuration_value' => '0',
            'configuration_description' => 'Sort order of display. Lowest is displayed first.',
            'set_function' => ''
        ));
    }


    function keys()
    {
        return array('MAILBEEZ_DASHBOARD_BEEZ_O_GRAPH_PASSED_DAYS_SKIP');
    }

}
