示例#1
0
// Clear out cloned field
//dump($querySelects);
if ($Type[1] == 'mysqlfunc') {
    $type = $Config['_mathMysqlFunc'][$Field];
    if ($type == '_custom') {
        if (!empty($Config['_mathMysqlCustomFunc'][$Field])) {
            $type = str_replace('()', '', $Config['_mathMysqlCustomFunc'][$Field]);
        }
    }
    //dump($_SERVER['fieldMath'][$Field]);
    if ($Config['_mathMysqlFunc'][$Field] == 'sumtotal') {
        $type = 'count';
        $_SERVER['fieldMath'][$Field] = 0;
    }
    $fieldSett = $Field;
    if (!empty($Config['_CloneField'][$Field])) {
        if (!empty($Config['_CloneField'][$Config['_CloneField'][$Field]['Master']])) {
            $fieldSett = dr_findCloneParent($Field, $Config['_CloneField'], $querySelects);
        } else {
            $fieldSett = $Config['_CloneField'][$Field]['Master'];
        }
        if (strpos($fieldSett, '.') === false) {
            $fieldSett = 'prim.`' . $fieldSett . '`';
        }
    }
    if ($type != '_custom') {
        $querySelects[$Field] = $type . '(`' . $fieldSett . '`)';
    } else {
        $querySelects[$Field] = $fieldSett;
    }
}
示例#2
0
function dr_BuildReportGrid($EID, $Page = false, $SortField = false, $SortDir = false, $Format = false, $limitOveride = false, $wherePush = false, $getOverride = false)
{
    // get element
    $Element = getelement($EID);
    $Config = $Element['Content'];
    if (!empty($Config['_customFooterJavaScript']) && empty($Format)) {
        $_SESSION['dataform']['OutScripts'] .= "\n            " . stripslashes_deep($Config['_customFooterJavaScript']) . "\n        ";
    }
    if (!empty($getOverride)) {
        parse_str($getOverride, $_GET);
    }
    //Filters will be picked up via Session value
    // Set Vars
    if (empty($Page)) {
        $Page = 1;
    }
    if (!empty($Format)) {
        // XML Output
        if (strtolower($Format) == 'xml') {
            $apiOut = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
            $apiOut .= "    <entries>\n";
        }
        //json output
        if (strtolower($Format) == 'json') {
            $jsonIndex = 0;
            $apiOutput = array();
            $apiOutput['page'] = $Page;
            $apiOutput['totalpages'] = '';
            $apiOutput['totalentries'] = '';
            $apiOutput['entrycount'] = '';
            $apiOutput['entries'] = array();
        }
        if (strtolower($Format) == 'pdf') {
            $pdfIndex = 0;
            $apiOutput = array();
            if (!empty($_SESSION['reportFilters'][$EID])) {
                $apiOutput['filters'] = $_SESSION['reportFilters'][$EID];
            }
        }
    }
    //global $ReportReturn;
    $ReportReturn = '';
    if (empty($Config['_main_table'])) {
        return 'No Table Selected';
    }
    $queryJoin = '';
    $queryJoins = array();
    $queryWhere = array();
    $queryLimit = '';
    $querySelects = array();
    $WhereTag = '';
    $groupBy = '';
    $orderStr = '';
    $countSelect = '';
    $countLimit = 'LIMIT 1';
    $isModal = 'false';
    if (!empty($Config['_popupTypeView'])) {
        if ($Config['_popupTypeView'] == 'modal') {
            $isModal = true;
        }
    }
    // Setup Totals Fields
    if (!empty($Config['_TotalsField'])) {
        foreach ($Config['_TotalsField'] as $key => $Field) {
            if (!empty($Config['_TotalsFieldTitle'][$key])) {
                $Title = str_replace(' ', '', ucwords($Config['_TotalsFieldTitle'][$key]));
            } else {
                $Title = $Field . 'Total';
            }
            //if($Config['_TotalsFieldLocation'][$key] == 'inline'){
            $Config['_Field'][$Title] = 'totals_' . $Config['_TotalsFieldType'][$key];
            $Config['_IndexType'][$Title] = 'index_show';
            $Config['_Justify'][$Title] = $Config['_TotalsFieldJustify'][$key];
            //}else{
            $Config['_TotalsFields'][$Title][$Config['_TotalsFieldType'][$key]] = 0;
            //}
            // Create easy sorting array
            $Config['_TotalsFields'][$Title]['Type'] = $Config['_TotalsFieldType'][$key];
            $Config['_TotalsFields'][$Title]['Grouping'] = $Config['_TotalsGroupingField'][$key];
            $Config['_TotalsFields'][$Title]['Location'] = $Config['_TotalsFieldLocation'][$key];
            $Config['_TotalsFields'][$Title]['Function'] = $Config['_TotalsFieldFunction'][$key];
            $Config['_TotalsFields'][$Title]['Prefix'] = $Config['_TotalsFieldPrefix'][$key];
            $Config['_TotalsFields'][$Title]['Suffix'] = $Config['_TotalsFieldSuffix'][$key];
            $Config['_TotalsFields'][$Title]['PrimField'] = $Field;
            //dump($Config['_TotalsFieldTitleWidth']);
            if (!empty($Config['_TotalsFieldTitleWidth'][$key])) {
                $Config['_WidthOverride'][$Title] = $Config['_TotalsFieldTitleWidth'][$key];
            }
            if (!empty($Config['_TotalsFieldCaption'][$key])) {
                $Config['_TotalsFields'][$Title]['Caption'] = $Config['_TotalsFieldCaption'][$key];
            }
            $Config['_TotalsFields'][$Title]['Title'] = $Title;
            unset($Title);
        }
        //unset($Config['_TotalsFieldType']);
        //unset($Config['_TotalsFieldLocation']);
        //unset($Config['_TotalsFieldTitle']);
        //unset($Config['_TotalsField']);
    }
    if (!empty($Page)) {
        $_SESSION['report_' . $EID]['LastPage'] = $Page;
    } else {
        if (empty($_SESSION['report_' . $EID]['LastPage']) || $_SESSION['report_' . $EID]['LastPage'] == 'undefined') {
            $_SESSION['report_' . $EID]['LastPage'] = 1;
        }
        $Page = $_SESSION['report_' . $EID]['LastPage'];
    }
    if (!empty($SortDir)) {
        $_SESSION['report_' . $EID]['SortDir'] = $SortDir;
    }
    if (!empty($SortField)) {
        $_SESSION['report_' . $EID]['SortField'] = $SortField;
    }
    //setup Field Types
    foreach ($Config['_Field'] as $Field => $Type) {
        if (empty($Type)) {
            //$querySelects[$Field] = $Field;
        }
        // explodes to:
        // [0] = Field plugin dir
        // [1] = Field plugin type
        $Config['_Field'][$Field] = explode('_', $Type);
    }
    //SetupHeaders
    // Start Table
    // Check for template
    $customClass = '';
    if (!empty($Config['_ListTableClass'])) {
        $customClass = $Config['_ListTableClass'];
    }
    $tableClass = 'class="data_report_Table ' . $customClass . '"';
    if (is_admin()) {
        $tableClass = 'class="widefat data_report_Table_admin ' . $customClass . '"';
    }
    $ReportReturn .= '<table width="100%" border="0" cellspacing="0" cellpadding="4" ' . $tableClass . ' id="data_report_' . $EID . '" style="cursor:default;">';
    //Start Headers Row
    //$ReportReturn .= '<caption>'.$Config['_ReportTitle'].'</caption>';
    $ReportReturn .= '<thead>';
    $ReportReturn .= '<tr>';
    foreach ($Config['_IndexType'] as $Field => $Type) {
        //echo 'ping';
        //Seperate Index/Display Types
        $Config['_IndexType'][$Field] = explode('_', $Type);
        // Totals Location check to see if field is inline or not.
        $Location = 'inline';
        if (!empty($Config['_TotalsFields'][$Field]['Location'])) {
            $Location = $Config['_TotalsFields'][$Field]['Location'];
        }
        if ($Config['_IndexType'][$Field][1] == 'show' && ($Location == 'inline' || $Location == 'headerinline' || $Location == 'footerinline') && empty($wherePush)) {
            //Set Widths
            $Direction = 'ASC';
            if (key_exists('SortDir', $_SESSION['report_' . $EID])) {
                if ($_SESSION['report_' . $EID]['SortDir'] == 'ASC') {
                    $Direction = 'DESC';
                }
            }
            $sortClass = 'report_header';
            if (key_exists('SortFIeld', $_SESSION['report_' . $EID])) {
                if ($_SESSION['report_' . $EID]['SortField'] == $Field) {
                    $sortClass = 'sorting_' . $_SESSION['report_' . $EID]['SortDir'];
                }
            }
            // set the column Title
            $fieldTitle = $Field;
            if (!empty($Config['_TotalsFields'][$Field]['Title'])) {
                $fieldTitle = $Config['_TotalsFields'][$Field]['Title'];
            }
            if (empty($Config['_WidthOverride'][$Field])) {
                $Config['_WidthOverride'][$Field] = '';
            }
            $ReportReturn .= '<th nowrap="nowrap" scope="col" width="' . ($Config['_WidthOverride'][$Field] == '' ? '{{width_' . $Field . '}}px' : $Config['_WidthOverride'][$Field] . 'px') . '" ';
            if (!empty($Config['_Sortable'][$Field])) {
                $ReportReturn .= 'onclick="dr_sortReport(\'' . $EID . '\', \'' . $Field . '\', \'' . $Direction . '\');" class="' . $sortClass . '"';
            }
            $ReportReturn .= '>';
            if (!empty($Config['_FieldTitle'][$Field])) {
                $ReportReturn .= '<span>' . $Config['_FieldTitle'][$Field] . '</span>';
            } else {
                $ReportReturn .= '<span>' . df_parseCamelCase($fieldTitle) . '</span>';
            }
            $ReportReturn .= '</th>';
            // Preset the selects from query
            $querySelects[$Field] = $Field;
            // 'prim.`' . $Field . '`';
            // Set average width and min width
            $minWidth[$Field] = strlen($fieldTitle) * 8;
            $AvrageWidth[$Field] = array();
            $AvrageWidth[$Field][] = $minWidth[$Field];
        }
        if (!empty($wherePush)) {
            $querySelects[$Field] = $Field;
            //'prim.`' . $Field . '`';
        }
    }
    // Add the return field to select
    if (!empty($Config['_ReturnFields'])) {
        //$querySelects[$Config['_ReturnFields'][0]] = 'prim.'.$Config['_ReturnFields'][0];
        foreach ($Config['_ReturnFields'] as $Field) {
            $newField = '_return_' . $Field;
            $querySelects[$newField] = $Field;
            //'prim.`' . $Field . '`';
        }
    }
    if (empty($Config['_Show_popup'])) {
        if (!empty($Config['_Show_Edit']) && empty($Config['_ItemViewPage']) || !empty($Config['_Show_Delete']) || !empty($Config['_Show_View']) || !empty($Config['_Show_Edit'])) {
            $ShowActionPanel = true;
        }
        if (!empty($ShowActionPanel)) {
            $ReportReturn .= '<th scope="col">';
            $ReportReturn .= 'Action';
            $ReportReturn .= '</th>';
        }
    }
    $ReportReturn .= '</tr>';
    $ReportReturn .= '</thead>';
    // End Headers setup
    // Build Query
    // field type filters
    $joinIndex = 'a';
    foreach ($Config['_Field'] as $Field => $Type) {
        //set filter for auto values
        if ($Type[0] == 'hidden') {
            if (!empty($_SESSION['reportFilters'][$EID][$Field])) {
                if ($WhereTag == '') {
                    $WhereTag = " WHERE ";
                }
                $queryWhere[] = "prim.`" . $Field . "` = '" . $_SESSION['reportFilters'][$EID][$Field] . "'";
            }
        }
        // Run Filters that have been set through each field type
        if (file_exists(WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/' . $Type[0] . '/queryfilter.php')) {
            include WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/' . $Type[0] . '/queryfilter.php';
        }
        if (!empty($_SESSION['reportFilters'][$EID]['_keywords'])) {
            if ($WhereTag == '') {
                $WhereTag = " WHERE ";
            }
            $keyField = 'prim.`' . $Field . '`';
            $preWhere[] = $keyField . " LIKE '%" . $_SESSION['reportFilters'][$EID]['_keywords'] . "%' ";
        }
        //}
        $joinIndex++;
    }
    // combine keyword search if there are any
    if (!empty($preWhere)) {
        $queryWhere[] = '(' . implode(' OR ', $preWhere) . ')';
    }
    if (!empty($wherePush)) {
        if ($WhereTag == '') {
            $WhereTag = " WHERE ";
        }
        foreach ($wherePush as $wField => $wVal) {
            $queryWhere[] = 'prim.`' . $wField . '` = \'' . $wVal . '\'';
        }
    }
    // create Query Selects and Where clause string
    $querySelects = dr_processQuery($Config, $querySelects);
    if (!empty($_SESSION['reportFilters'][$EID]['_keywords'])) {
        if ($WhereTag == '') {
            $WhereTag = " WHERE ";
        }
        foreach ($querySelects as $Key => $Field) {
            if (!empty($Config['_IndexType'][$Field][0])) {
                echo $Field . '<br />';
                $preWhere[] = $Field . " LIKE '%" . $_SESSION['reportFilters'][$EID]['_keywords'] . "%' ";
                // explode and serach parts
                $parts = explode(',', $_SESSION['reportFilters'][$EID]['_keywords']);
                foreach ($parts as $Part) {
                    $preWhere[] = $Field . " LIKE '%" . trim($Part) . "%' ";
                }
                // explode and serach parts
                $parts = explode(', ', $_SESSION['reportFilters'][$EID]['_keywords']);
                foreach ($parts as $Part) {
                    $preWhere[] = $Field . " LIKE '%" . trim($Part) . "%' ";
                }
            }
        }
    }
    //vardump($Config['_CloneField']);    //vardump($querySelects);
    $preSelects = array();
    foreach ($querySelects as $AS => $selectField) {
        $preSelects[] = $selectField . ' AS `' . $AS . '`';
    }
    $querySelect = implode(", \n", $preSelects);
    $queryWhere = implode(' AND ', $queryWhere);
    // create sort fields
    if (!empty($Config['_SortField'])) {
        if (key_exists('SortFields', $_SESSION['report_' . $EID]) && !empty($querySelects[$_SESSION['report_' . $EID]['SortField']])) {
            $orderStr = 'ORDER BY `' . $_SESSION['report_' . $EID]['SortField'] . '` ' . $_SESSION['report_' . $EID]['SortDir'];
        } else {
            $orderStr = 'ORDER BY prim.`' . $Config['_SortField'] . '` ' . $Config['_SortDirection'] . '';
        }
    }
    // create joins and on
    $pattern = 'prim.`(__[a-zA-Z0-9]+)`';
    preg_match_all('/' . $pattern . '/s', $queryJoin, $matches);
    foreach ($matches[0] as $key => $Match) {
        $queryJoin = str_replace($Match, $querySelects[$matches[1][$key]], $queryJoin);
    }
    // Build the grouping if ther are any
    if (is_array($groupBy)) {
        $preGroup = array();
        foreach ($groupBy as $groupField => $preField) {
            if (!empty($querySelects[$groupField])) {
                $preGroup[] = $querySelects[$groupField];
            } else {
                if (strpos($preField, '.') === false) {
                    $preField = 'prim.' . $preField . '';
                }
                $preGroup[] = $preField;
            }
        }
        $groupBy = 'GROUP BY (' . implode('),(', $preGroup) . ')';
        $countLimit = '';
        $entryCount = true;
        //add totals selects to count
        if (is_array($countSelect)) {
            $countSelect = ',' . implode(',', $countSelect);
        }
    }
    // Build WHERES - prim.clones
    $pattern = 'prim.`(__[a-zA-Z0-9]+)`';
    preg_match_all('/' . $pattern . '/s', $queryWhere, $matches);
    foreach ($matches[0] as $key => $Match) {
        if (!empty($querySelects['_sourceid_' . $matches[1][$key]])) {
            $queryWhere = str_replace($Match, $querySelects['_sourceid_' . $matches[1][$key]], $queryWhere);
        } else {
            $replace = dr_findCloneParent($matches[1][$key], $Config['_CloneField'], $querySelects);
            if (strpos($replace, '.') === false) {
                $replace = 'prim.`' . $replace . '`';
            }
            $queryWhere = str_replace($Match, $replace, $queryWhere);
        }
    }
    //return;
    // Totals Query & Results
    //dump($querySelects);
    if (!empty($Config['_CloneField'][$Config['_ReturnFields'][0]])) {
        $countSelect = dr_findCloneParent($Config['_ReturnFields'][0], $Config['_CloneField'], $querySelects);
    } else {
        $countSelect = $Config['_ReturnFields'][0];
    }
    if (strpos($countSelect, '.') === false) {
        $countSelect = 'prim.`' . $countSelect . '`';
    }
    // get done queries
    global $wpdb;
    //dump($Queries);
    // Custom WHERE
    $customWhere = '';
    if (!empty($Config['_useCustomWhere'])) {
        if ($WhereTag == '') {
            $WhereTag = " WHERE ";
        }
        $preWhere = '';
        foreach ($Config['_customWHERE'] as $cwhere) {
            if (!empty($queryWhere)) {
                $queryWhere = '(' . $queryWhere . ')';
                $preWhere .= ' ' . $cwhere['_Req'] . ' ';
            }
            $preWhere .= '(' . $cwhere['_Where'] . ')';
        }
        $queryWhere .= $preWhere;
    }
    $CountQuery = "SELECT count(" . $countSelect . ") as Total FROM `" . $Config['_main_table'] . "` AS prim \n " . $queryJoin . " \n " . $WhereTag . " \n " . $queryWhere . " \n " . $groupBy . "\n\n " . $countLimit . ";";
    $CountResult = mysql_query($CountQuery);
    if (!empty($entryCount)) {
        // Countr Rows
        while ($prCount = mysql_fetch_assoc($CountResult)) {
            $preCount[] = $prCount['Total'];
        }
        if (!empty($preCount)) {
            $Count['TotalEntries'] = array_sum($preCount);
            unset($prCount);
            unset($preCount);
        } else {
            $Count['TotalEntries'] = 0;
        }
        $Count['Total'] = mysql_num_rows($CountResult);
    } else {
        // get Count entry
        if (!empty($CountResult)) {
            $Count = mysql_fetch_assoc($CountResult);
            mysql_free_result($CountResult);
        } else {
            $Count = 0;
        }
    }
    if (!empty($limitOveride) && $limitOveride != 'full') {
        $Config['_Items_Per_Page'] = $limitOveride;
    }
    if (!empty($_SESSION['report_' . $EID]['limitOveride'])) {
        $Config['_Items_Per_Page'] = floatval($_SESSION['report_' . $EID]['limitOveride']);
    }
    if (!empty($Config['_Items_Per_Page'])) {
        $TotalPages = ceil($Count['Total'] / $Config['_Items_Per_Page']);
        $Start = $Page * $Config['_Items_Per_Page'] - $Config['_Items_Per_Page'];
        $Offset = $Config['_Items_Per_Page'];
        if ($Page > 0) {
            if ($Page > $TotalPages) {
                $Page = $TotalPages;
                $Start = $Page * $Config['_Items_Per_Page'] - $Config['_Items_Per_Page'];
                if ($Start < 0) {
                    $Start = 1;
                }
            }
            $queryLimit = " LIMIT " . $Start . ", " . $Offset . " ";
            //$Limit = "";
        }
    }
    if (strtolower($Format) == 'pdf' && $limitOveride != false) {
        if ($limitOveride = 'full') {
            $queryLimit = '';
        }
    }
    if (empty($Config['_Items_Per_Page'])) {
        $queryLimit = '';
    }
    if (!empty($Format)) {
        // XML Output
        if (strtolower($Format) == 'xml') {
            $apiOut .= "    <page>" . $Page . "</page>\n";
            $apiOut .= "    <totalpages>" . $TotalPages . "</totalpages>\n";
            $apiOut .= "    <totalentries>" . $Count['Total'] . "</totalentries>\n";
        }
        //json output
        if (strtolower($Format) == 'json') {
            $apiOutput['totalpages'] = $TotalPages;
            $apiOutput['totalentries'] = $Count['Total'];
        }
    }
    // Select Query
    //$Query = "SELECT count(b.Country) as TotalCountry, ".$querySelect." FROM `".$Config['_main_table']."` AS prim \n ".$queryJoin." \n ".$WhereTag." \n ".$queryWhere."\n GROUP BY b.Country \n ".$orderStr." \n ".$queryLimit.";"
    if (!empty($Config['_useListTemplate']) && empty($Format)) {
        $Media = $Element;
        ob_start();
        $Query = dr_BuildReportGrid($EID, $Page, $SortField, $SortDir, 'sql', $limitOveride, $wherePush);
        //$WrapperEl = 'div';
        if (!empty($Config['_TemplateWrapper'])) {
            $WrapperEl = $Config['_TemplateWrapper'];
        }
        $Wrapperclasses = '';
        if (!empty($Config['_TemplateClass'])) {
            $Wrapperclasses = $Config['_TemplateClass'];
        }
        if (!empty($Config['_TemplateWrapper'])) {
            echo '<' . $WrapperEl . ' id="reportPanel_' . $Media['ID'] . '" class="interfaceWrapper ' . $Wrapperclasses . '">';
        }
        include 'templatemode.php';
        if (!empty($Config['_TemplateWrapper'])) {
            echo '</' . $WrapperEl . '>';
        }
        return ob_get_clean();
    }
    $Query = "SELECT " . $querySelect . " FROM `" . $Config['_main_table'] . "` AS prim \n " . $queryJoin . " \n " . $WhereTag . " \n " . $queryWhere . "\n " . $groupBy . " \n " . $orderStr . " \n " . $queryLimit . ";";
    if (strtolower($Format) == 'data') {
        $dtaRes = mysql_query($Query);
        $Data = mysql_fetch_assoc($dtaRes);
        return $Data;
    }
    if (!empty($Config['_UserQueryOveride']) && !empty($Config['_QueryOveride'])) {
        $Query = $Config['_QueryOveride'];
        preg_match('/(LIMIT [ 0-9]+,[ 0-9]+)/', $Query, $Limits);
        if (!empty($Limits[0])) {
            $Query = str_replace($Limits[0], $queryLimit, $Query);
        } else {
            $Query .= $queryLimit;
        }
    }
    //vardump($Query);
    // Wrap fields with ``
    //foreach($querySelects as $Field=>$FieldValue){
    // echo $Field.' = '.$FieldValue.'<br />';
    //   $Query = str_replace('.'.$Field, '.`'.$Field.'`', $Query);
    //}
    if (!empty($Config['_UseCustomQuery']) && !empty($Config['_ManualQuery'])) {
        $Query = $Config['_ManualQuery'];
        preg_match('/(LIMIT [ 0-9]+,[ 0-9]+)/', $Query, $Limits);
        if (!empty($Limits[0])) {
            $Query = str_replace($Limits[0], $queryLimit, $Query);
        } else {
            $Query .= $queryLimit;
        }
    }
    //echo $Query;
    $QueryHash = md5($Query);
    $_SESSION['queries'][$EID] = $Query;
    if (!empty($Queries[$QueryHash])) {
        $Result = $Queries[$QueryHash];
        mysql_data_seek($Result, 0);
    } else {
        $Result = mysql_query($Query);
        $Queries[$QueryHash] = $Result;
    }
    $_SESSION['queries'][$EID] = $Query;
    //echo $Query;
    if (strtolower($Format) == 'sql') {
        return $Query;
    }
    if (!empty($exitNotice)) {
        return;
        //'<div id="'.$EID.'_wrapper"></div>';
    }
    $Result = $wpdb->get_results($Query, ARRAY_A);
    // Run View Processes
    if (!empty($Config['_ViewProcessors'])) {
        foreach ($Config['_ViewProcessors'] as $viewProcess) {
            if (empty($_GET['format_' . $EID])) {
                //ignore on export
                if (file_exists(DB_TOOLKIT . 'data_report/processors/' . $viewProcess['_process'] . '/functions.php')) {
                    include_once DB_TOOLKIT . 'data_report/processors/' . $viewProcess['_process'] . '/functions.php';
                    $func = 'pre_process_' . $viewProcess['_process'];
                    $Result = $func($Result, $viewProcess, $Config, $EID);
                    if (empty($Result)) {
                        return;
                    }
                }
            }
            //if(file_exists($viewProcess['_process']))
        }
    }
    //pre_process_
    //$Result = mysql_query($Query);
    if (!empty($Config['_chartOnly'])) {
        return '<div id="chart_' . $ChartID . '" style="height:' . $height . 'px;"></div>';
        //$ReportReturn;
    }
    // Build Rows
    $ReportReturn .= '<tbody>';
    // Row number Increment
    $rowIndex = 1;
    // Set Row Style
    $Row = 'odd';
    // add in inline editing
    if (!empty($Config['_InlineEdit'])) {
        $_SESSION['dataform']['OutScripts'] .= "\n\t\t\tjQuery('.inlineedit').bind('change', function(t){\n\t\t\t\tajaxCall('df_inlineedit', this.id, jQuery(this).attr('ref'), this.value, function(f){\n\t\t\t\t\tif(f != '1'){\n\t\t\t\t\t\tdf_dialog(f, jQuery(this).attr('ref'), '0');\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\t//alert(this.id+' - '+jQuery(this).attr('ref')+' - '+this.value);\n\t\t\t});\n\t\t";
    }
    if (!empty($Result)) {
        if (!empty($Format)) {
            // XML Output
            if (strtolower($Format) == 'xml') {
                $apiOut .= "    <entrycount>" . count($Result) . "</entrycount>\n";
            }
            //json output
            if (strtolower($Format) == 'json') {
                $apiOutput['entrycount'] = count($Result);
            }
        }
        //while($row = mysql_fetch_assoc($Result)) {
        foreach ($Result as $row) {
            // Switch Row Style
            //$Row = dais_rowswitch($Row);
            //$Row = report_rowswitch($Row);
            $Row = grid_rowswitch($Row);
            // foreach column
            $SelectedRow = '';
            if (!empty($Config['_ReturnFields'][0])) {
                if (!empty($_GET[$Config['_ReturnFields'][0]])) {
                    if ($row['_return_' . $Config['_ReturnFields'][0]] == $_GET[$Config['_ReturnFields'][0]]) {
                        if (!empty($Config['_Show_Edit'])) {
                            $SelectedRow = 'highlight';
                        }
                        $HighlightIndex = true;
                    }
                }
            }
            $ReportReturn .= '<tr class="' . $Row . ' itemRow_' . $EID . ' ' . $SelectedRow . '  report_entry" ref="' . $row['_return_' . $Config['_ReturnFields'][0]] . ' highlight" id="row_' . $EID . '_' . $rowIndex . '" >';
            // API Output
            if (!empty($Format)) {
                // XML Output
                if (strtolower($Format) == 'xml') {
                    $apiOut .= "    <entry>\n";
                }
                // json Output
                if (strtolower($Format) == 'json') {
                    $apiOutput['entries'][$jsonIndex] = array();
                }
                if (strtolower($Format) == 'pdf') {
                    //$apiOutput[$jsonIndex][] = array();
                    if (!empty($_SESSION['reportFilters'][$EID])) {
                        //$apiOutput['filters'] = array();
                    }
                }
            }
            $ColumnCounter = 0;
            //vardump($Config);
            // action panels
            // Edit Functions if no popup
            $actionPanels = '';
            if (!empty($ShowActionPanel)) {
                $ViewLink = '';
                $ActionWidth = 16;
                if (!empty($Config['_Show_View'])) {
                    $ActionWidth = $ActionWidth + 16;
                    $ViewLink .= "<span style=\"cursor:pointer;\" onclick=\"df_loadEntry('" . $row['_return_' . $Config['_ReturnFields'][0]] . "', '" . $EID . "', " . $isModal . "); return false;\"><img src=\"" . WP_PLUGIN_URL . "/db-toolkit/data_report/css/images/magnifier.png\" width=\"16\" height=\"16\" alt=\"View\" title=\"View\" border=\"0\" align=\"absmiddle\" /></span>";
                    if (!is_admin()) {
                        if (!empty($Config['_ItemViewPage'])) {
                            $ReportVars = array();
                            foreach ($Config['_ReturnFields'] as $ReportReturnField) {
                                $ReportVars[$ReportReturnField] = urlencode($row['_return_' . $ReportReturnField]);
                            }
                            // Get permalink
                            $PageLink = get_permalink($Config['_ItemViewPage']);
                            $Location = parse_url($PageLink);
                            if (!empty($Location['query'])) {
                                $PageLink = str_replace('?' . $Location['query'], '', $PageLink);
                                parse_str($Location['query'], $gets);
                                $PageLink = $PageLink . '?' . htmlspecialchars_decode(http_build_query(array_merge($gets, $ReportVars)));
                            } else {
                                $PageLink = $PageLink . '?' . htmlspecialchars_decode(http_build_query($ReportVars));
                            }
                            $ViewLink = "<a href=\"" . $PageLink . "\"><img src=\"" . WP_PLUGIN_URL . "/db-toolkit/data_report/css/images/magnifier.png\" width=\"16\" height=\"16\" alt=\"View\" title=\"View\" border=\"0\" align=\"absmiddle\" /></a>";
                        }
                    }
                }
                if (!empty($Config['_Show_Edit'])) {
                    $ActionWidth = $ActionWidth + 16;
                    if ($ViewLink != '') {
                        $ViewLink .= " ";
                    }
                    $ViewLink .= '<span style="cursor:pointer;" onclick="dr_BuildUpDateForm(\'' . $EID . '\', \'' . $row['_return_' . $Config['_ReturnFields'][0]] . '\');"><img src="' . WP_PLUGIN_URL . '/db-toolkit/data_report/edit.png" width="16" height="16" alt="Edit" title="Edit" border="0" align="absmiddle" /></span>';
                }
                if (!empty($Config['_Show_Delete_action'])) {
                    $ActionWidth = $ActionWidth + 16;
                    if ($ViewLink != '') {
                        $ViewLink .= " ";
                    }
                    if (!empty($_GET)) {
                        $hasQuery = build_query($_GET);
                    } else {
                        $hasQuery = false;
                    }
                    $ViewLink .= '<span style="cursor:pointer;" onclick="dr_deleteItem(\'' . $EID . '\', \'' . $row['_return_' . $Config['_ReturnFields'][0]] . '\',\'' . $hasQuery . '\');"><img src="' . WP_PLUGIN_URL . '/db-toolkit/data_report/delete.png" width="16" height="16" alt="Delete" title="Delete" border="0" align="absmiddle" /></span>';
                }
                //vardump($Config);
                $PreReportReturn = '<td class="' . $Row . ' action" width="' . $ActionWidth . '" scope="col" style="text-align:center;overflow:hidden;">';
                $PreReportReturn .= $ViewLink;
                //'Edit | View';
                $PreReportReturn .= '</td>';
                $actionPanels .= $PreReportReturn;
            }
            // Show Action Panels on left
            //$ReportReturn .= $actionPanels;
            foreach ($Config['_IndexType'] as $Field => $Type) {
                //foreach ($row as $Field => $Data) {
                if ($Type[1] === 1) {
                    break;
                }
                if (isset($row[$Field])) {
                    $Data = $row[$Field];
                } else {
                    $Data = '';
                }
                if (!empty($Config['_IndexType'][$Field][1])) {
                    if ($Config['_IndexType'][$Field][1] == 'show') {
                        $outData = $Data;
                        /// Capture value for Totals
                        if (!empty($Config['_TotalsFields'][$Field]['Type'])) {
                            switch ($Config['_TotalsFields'][$Field]['Type']) {
                                case 'count':
                                    //echo $Field.' = '.$Config['_TotalsFields'][$Field][$Config['_TotalsFields'][$Field]['Type']].'+1<br />';
                                    $Config['_TotalsFields'][$Field][$Config['_TotalsFields'][$Field]['Type']] = $Count['TotalEntries'];
                                    break;
                                case 'sum':
                                    //echo $Field.' = '.$Config['_TotalsFields'][$Field][$Config['_TotalsFields'][$Field]['Type']].' + '.$outData.'<br />';
                                    $Config['_TotalsFields'][$Field][$Config['_TotalsFields'][$Field]['Type']] = $Config['_TotalsFields'][$Field][$Config['_TotalsFields'][$Field]['Type']] + $outData;
                                    break;
                                case 'avg':
                                    //echo $Field.' = '.$Config['_TotalsFields'][$Field][$Config['_TotalsFields'][$Field]['Type']].' + '.$outData.'<br />';
                                    $Config['_TotalsFields'][$Field][$Config['_TotalsFields'][$Field]['Type']] = $Config['_TotalsFields'][$Field][$Config['_TotalsFields'][$Field]['Type']] + $outData;
                                    break;
                            }
                        }
                        if (function_exists($Config['_Field'][$Field][0] . '_processValue')) {
                            $processFunc = $Config['_Field'][$Field][0] . '_processValue';
                            //						Value  field type
                            $outData = $processFunc($Data, $Config['_Field'][$Field][1], $Field, $Config, $EID, $row);
                        }
                        // Capture columns average width for ato widths
                        $AvrageWidth[$Field][] = strlen($outData) * 8;
                        // Apply keyword Fitler Highlight
                        if (!empty($_SESSION['reportFilters'][$EID]['_keywords'])) {
                            //$outData = str_replace($_SESSION['reportFilters'][$EID]['_keywords'], '<strong>'.$_SESSION['reportFilters'][$EID]['_keywords'].'</strong>', $outData);
                            //$outData = str_replace(ucwords($_SESSION['reportFilters'][$EID]['_keywords']), '<strong>'.ucwords($_SESSION['reportFilters'][$EID]['_keywords']).'</strong>', $outData);
                            //$outData = str_replace(strtoupper($_SESSION['reportFilters'][$EID]['_keywords']), '<strong>'.strtoupper($_SESSION['reportFilters'][$EID]['_keywords']).'</strong>', $outData);
                            //$outData = str_replace(strtolower($_SESSION['reportFilters'][$EID]['_keywords']), '<strong>'.strtolower($_SESSION['reportFilters'][$EID]['_keywords']).'</strong>', $outData);
                        }
                        // set row output
                        //Check if field is in totals and is allowed inline
                        $Location = 'inline';
                        if (!empty($Config['_TotalsFields'][$Field]['Location'])) {
                            $Location = $Config['_TotalsFields'][$Field]['Location'];
                        }
                        if ($Location == 'inline' || $Location == 'headerinline' || $Location == 'footerinline') {
                            // selection highlighting (experimental)
                            $sortClass = '';
                            if (key_exists('SortField', $_SESSION['report_' . $EID]) && $_SESSION['report_' . $EID]['SortField'] == $Field) {
                                $sortClass = 'column_sorting_' . $_SESSION['report_' . $EID]['SortDir'];
                            }
                            $itemID = uniqid('');
                            // Add Reload Highlighting
                            $LiveHighlight = '';
                            $ReportReturn .= '<td class="' . $Row . ' ' . $sortClass . ' ' . $LiveHighlight . '" scope="col" id="' . $itemID . '" ref="itemRow_' . $EID . '" width="' . ($Config['_WidthOverride'][$Field] == '' ? '{{width_' . $Field . '}}px' : $Config['_WidthOverride'][$Field] . 'px') . '" style="text-align:' . $Config['_Justify'][$Field] . '; ">';
                            //inline editing
                            if (!empty($Config['_InlineEdit'][$Field])) {
                                $Req = 'inlineedit';
                                $FieldSet = $Config['_Field'][$Field];
                                //$ReportReturn .= WP_PLUGIN_DIR.'/db-toolkit/data_form/fieldtypes/'.$FieldSet[0].'/input.php';
                                ob_start();
                                $Defaults[$Field] = $row['_sourceid_' . $Field];
                                include WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/' . $FieldSet[0] . '/conf.php';
                                include WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/' . $FieldSet[0] . '/input.php';
                                $ReportReturn .= ob_get_clean();
                            } else {
                                $PreReportReturn = '';
                                // Make View Item Link If page is set
                                if (is_admin()) {
                                    //vardump($Config);
                                    if (!empty($Config['_ItemViewInterface'])) {
                                        // Create return link
                                        $ReportVars = array();
                                        foreach ($Config['_ReturnFields'] as $ReportReturnField) {
                                            $ReportVars[$ReportReturnField] = urlencode($row['_return_' . $ReportReturnField]);
                                        }
                                        // Get permalink
                                        // interface admin.php?page=Database_Toolkit&renderinterface=dt_intfc4c04c77ed928a
                                        if ($_GET['page'] != 'dbt_builder') {
                                            if (!empty($Config['_SetDashboard'])) {
                                                $Interface = get_option($EID);
                                                $app = get_option('_' . $Interface['_Application'] . '_app');
                                                if (!empty($app['landing'])) {
                                                    $pageLoc = 'app_' . $Interface['_Application'];
                                                } else {
                                                    $pageLoc = $EID;
                                                }
                                                if (!empty($app['docked'])) {
                                                    $PageLink = 'admin.php?page=' . $pageLoc . '&sub=' . $Config['_ItemViewInterface'] . '&' . htmlspecialchars_decode(http_build_query($ReportVars));
                                                } else {
                                                    $PageLink = 'admin.php?page=dbt_builder&renderinterface=' . $Config['_ItemViewInterface'] . '&' . htmlspecialchars_decode(http_build_query($ReportVars));
                                                }
                                            } else {
                                                $PageLink = 'admin.php?page=' . $_GET['page'] . '&sub=' . $Config['_ItemViewInterface'] . '&' . htmlspecialchars_decode(http_build_query($ReportVars));
                                            }
                                        } else {
                                            $PageLink = 'admin.php?page=dbt_builder&renderinterface=' . $Config['_ItemViewInterface'] . '&' . htmlspecialchars_decode(http_build_query($ReportVars));
                                        }
                                        $PreReportReturn .= "<a href=\"" . $PageLink . "\">";
                                    }
                                } else {
                                    if (!empty($Config['_ItemViewInterface']) && !empty($Config['_targetInterface'])) {
                                        // Create return link
                                        $url = !empty($_SERVER['HTTPS']) ? "https://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] : "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
                                        $url = strtok($url, '?');
                                        $ReportVars = array();
                                        foreach ($Config['_ReturnFields'] as $ReportReturnField) {
                                            $ReportVars[$ReportReturnField] = urlencode($row['_return_' . $ReportReturnField]);
                                        }
                                        // Get permalink
                                        // interface admin.php?page=Database_Toolkit&renderinterface=dt_intfc4c04c77ed928a
                                        $op = '?';
                                        if (strpos($url, '?') !== false) {
                                            $op = '&';
                                        }
                                        $sendString = htmlspecialchars_decode(http_build_query($ReportVars));
                                        $PageLink = $url . $op . $sendString;
                                        //$sendString = implode('&', $ReturnFields);
                                        //$PreReportReturn .= '<a id href="#'.$Config['_ItemViewInterface'].'" onclick="dr_pushResult(\''.$Config['_ItemViewInterface'].'\', \''.$sendString.'\'); return false;">'.$outData.'</a>';
                                        $PreReportReturn .= "<a href=\"" . $PageLink . "\" onclick=\"dr_pushResult('" . $Config['_ItemViewInterface'] . "', '" . $sendString . "'); return false;\" >";
                                        //$PreReportReturn .= "<a href=\"" . $PageLink . "\">";
                                    }
                                    if (!empty($Config['_ItemViewPage'])) {
                                        // Create return link
                                        $ReportVars = array();
                                        foreach ($Config['_ReturnFields'] as $ReportReturnField) {
                                            $ReportVars[$ReportReturnField] = urlencode($row['_return_' . $ReportReturnField]);
                                        }
                                        // Get permalink
                                        $PageLink = get_permalink($Config['_ItemViewPage']);
                                        $Location = parse_url($PageLink);
                                        if (!empty($Location['query'])) {
                                            $PageLink = str_replace('?' . $Location['query'], '', $PageLink);
                                            parse_str($Location['query'], $gets);
                                            $PageLink = $PageLink . '?' . htmlspecialchars_decode(http_build_query(array_merge($gets, $ReportVars)));
                                        } else {
                                            $PageLink = $PageLink . '?' . htmlspecialchars_decode(http_build_query($ReportVars));
                                        }
                                        $PreReportReturn .= "<a href=\"" . $PageLink . "\" >";
                                    }
                                }
                                $ReturnFields = array();
                                if (is_array($Config['_ReturnFields'])) {
                                    foreach ($Config['_ReturnFields'] as $ReturnField) {
                                        $ReturnFields[] = $ReturnField . '=' . urlencode($row['_return_' . $ReturnField]);
                                    }
                                }
                                //$ReturnMix = implode('&', $ReturnFields);
                                //$PreReportReturn .= '<a href="'.getdocument($_GET['PageData']['ID']).'#'.$ReturnMix.'">'.stripslashes($outData).'</a>';
                                // CREATE redirect pushing
                                if (!empty($Config['_layoutTemplate']['_Fields'][$Field])) {
                                    if (!empty($outData)) {
                                        $before = $Config['_layoutTemplate']['_Fields'][$Field]['_before'];
                                        $after = $Config['_layoutTemplate']['_Fields'][$Field]['_after'];
                                        foreach ($row as $repField => $repValue) {
                                            $before = str_replace('{{' . $repField . '}}', $repValue, $before);
                                            $after = str_replace('{{' . $repField . '}}', $repValue, $after);
                                        }
                                        $PreReportReturn .= $before;
                                    }
                                }
                                $PreReportReturn .= $outData;
                                if (!empty($Config['_layoutTemplate']['_Fields'][$Field])) {
                                    if (!empty($outData)) {
                                        $PreReportReturn .= $after;
                                    }
                                }
                                // API Output
                                if (!empty($Format)) {
                                    // XML Output
                                    if (strtolower($Format) == 'xml') {
                                        if (!is_integer($outData)) {
                                            $apiOut .= "        <" . $Field . "><![CDATA[" . stripslashes($outData) . "]]></" . $Field . ">\n";
                                        } else {
                                            $apiOut .= "\t<" . $Field . ">" . stripslashes($outData) . "</" . $Field . ">\n";
                                        }
                                    }
                                    // json Output
                                    if (strtolower($Format) == 'json') {
                                        $apiOutput['entries'][$jsonIndex][$Field] = $outData;
                                        //echo $outData;
                                    }
                                    // PDF output
                                    if (strtolower($Format) == 'pdf') {
                                        $apiOutput[$pdfIndex][$Field] = stripslashes($outData);
                                        if (!empty($_SESSION['reportFilters'][$EID][$Field])) {
                                            $apiOutput['filters'][$Field][stripslashes($outData)] = stripslashes($outData);
                                        }
                                    }
                                }
                                // Close link
                                if (!empty($Config['_ItemViewPage'])) {
                                    $PreReportReturn .= "</a>";
                                }
                                if (!empty($Config['_ItemViewInterface'])) {
                                    $PreReportReturn .= "</a>";
                                }
                                if (!empty($Config['_ItemViewInterface']) && !empty($Config['_targetInterface'])) {
                                    $PreReportReturn .= "</a>";
                                }
                            }
                            $ReportReturn .= $PreReportReturn;
                            if (!empty($Config['_Show_popup'])) {
                                if ($ColumnCounter === 0) {
                                    // Add inline actions
                                    $ViewLink = '';
                                    $ActionWidth = 16;
                                    if (!empty($Config['_Show_View'])) {
                                        $ActionWidth = $ActionWidth + 16;
                                        $ViewLink['view'] = "<a href=\"#\" onclick=\"return false;\"><span style=\"cursor:pointer;\" onclick=\"df_loadEntry('" . $row['_return_' . $Config['_ReturnFields'][0]] . "', '" . $EID . "', " . $isModal . "); return false;\">View</span></a>";
                                        if (is_admin()) {
                                            if (!empty($Config['_ItemViewInterface'])) {
                                                $ReportVars = array();
                                                foreach ($Config['_ReturnFields'] as $ReportReturnField) {
                                                    $ReportVars[$ReportReturnField] = urlencode($row['_return_' . $ReportReturnField]);
                                                }
                                                // Get permalink
                                                // check if its in a menu
                                                $inf = get_option($Config['_ItemViewInterface']);
                                                if (empty($inf['_ItemGroup']) && empty($inf['_interfaceName'])) {
                                                    $PageLink = 'admin.php?page=dbt_builder&renderinterface=' . $Config['_ItemViewInterface'] . '&' . htmlspecialchars_decode(http_build_query($ReportVars));
                                                } else {
                                                    $PageLink = 'admin.php?page=' . $Config['_ItemViewInterface'] . '&' . htmlspecialchars_decode(http_build_query($ReportVars));
                                                }
                                                $ViewLink['view'] = "<a href=\"" . $PageLink . "\">View</a>";
                                            }
                                        } else {
                                            if (!empty($Config['_ItemViewPage'])) {
                                                $ReportVars = array();
                                                foreach ($Config['_ReturnFields'] as $ReportReturnField) {
                                                    $ReportVars[$ReportReturnField] = urlencode($row['_return_' . $ReportReturnField]);
                                                }
                                                // Get permalink
                                                $PageLink = get_permalink($Config['_ItemViewPage']);
                                                $Location = parse_url($PageLink);
                                                if (!empty($Location['query'])) {
                                                    $PageLink = str_replace('?' . $Location['query'], '', $PageLink);
                                                    parse_str($Location['query'], $gets);
                                                    $PageLink = $PageLink . '?' . htmlspecialchars_decode(http_build_query(array_merge($gets, $ReportVars)));
                                                } else {
                                                    $PageLink = $PageLink . '?' . htmlspecialchars_decode(http_build_query($ReportVars));
                                                }
                                                $ViewLink['view'] = "<a href=\"" . $PageLink . "\">View</a>";
                                            }
                                        }
                                    }
                                    if (!empty($Config['_Show_Edit'])) {
                                        $ActionWidth = $ActionWidth + 16;
                                        $ViewLink['edit'] = '<a href="#" onclick="return false;"><span style="cursor:pointer;" onclick="dr_BuildUpDateForm(\'' . $EID . '\', \'' . $row['_return_' . $Config['_ReturnFields'][0]] . '\');">Edit</span></a>';
                                    }
                                    if (!empty($Config['_Show_Delete_action'])) {
                                        $ActionWidth = $ActionWidth + 16;
                                        $ViewLink['delete'] = '<a href="#" onclick="return false;"><span style="cursor:pointer;" class="delete" onclick="dr_deleteItem(\'' . $EID . '\', \'' . $row['_return_' . $Config['_ReturnFields'][0]] . '\');">Delete</span></a>';
                                    }
                                    //vardump($Config);
                                    //$PreReportReturn = '<td class="'.$Row.' action" width="'.$ActionWidth.'" scope="col" style="text-align:center;overflow:hidden;">';
                                    $ReportReturn .= '<div class="row-actions">' . implode(' | ', $ViewLink) . '</div>';
                                    //'Edit | View';
                                    //$PreReportReturn .= '</td>';
                                    //$ReportReturn .= $PreReportReturn;
                                }
                            }
                            $ReportReturn .= '</td>';
                        }
                    }
                }
                $ColumnCounter++;
            }
            // API Output
            if (!empty($Format)) {
                // XML Output
                if (strtolower($Format) == 'xml') {
                    $apiOut .= "    </entry>\n";
                }
                // json Output
                if (strtolower($Format) == 'json') {
                    $jsonIndex++;
                }
                //PDF Output
                if (strtolower($Format) == 'pdf') {
                    $pdfIndex++;
                }
            }
            // Show Action Panelson right
            $ReportReturn .= $actionPanels;
            $ReportReturn .= '</tr>';
            // Increment row index
            $rowIndex++;
        }
    }
    //echo mysql_error();
    // Close off Table end content
    $ReportReturn .= '</tbody>';
    $ReportReturn .= '</table>';
    // Make Scripts for deleting and select
    if (empty($Config['_Feature_Selectable_Rows'])) {
        $_SESSION['dataform']['OutScripts'] .= "\n\t\tjQuery('#data_report_" . $EID . " .report_entry').bind('click', function(){\n\t\t\tjQuery(this).toggleClass(\"highlight\");\n\t\t});\n\t";
    }
    // Footer
    //TODO: really need to clean up this templating. to much repetition
    if (!empty($Config['_Show_Footer'])) {
        $First = 1;
        $Prev = $Page - 1;
        $Next = $Page + 1;
        $Last = $TotalPages;
        if ($Prev <= 0) {
            $Prev = 1;
        }
        if ($Next > $TotalPages) {
            $Next = $TotalPages;
        }
        if (empty($Page)) {
            $Page = 1;
        }
        //Page Index display
        $toPos = $Page * $Offset;
        if ($toPos > $Count['Total']) {
            $toPos = $Count['Total'];
        }
        $pageLink = '';
        if (!empty($_SERVER['QUERY_STRING'])) {
            $pageLink = $_SERVER['QUERY_STRING'] . '&';
        }
        //$ReportReturn .= '<div style="padding:3px;" class="list_row3">';
        $ReportReturn .= '<div style="padding:3px;" class="tablenav bottom">';
        //Total pages display
        $ReportReturn .= '<div class="tablenav-pages">';
        // Check if there are any entries
        if ($Count['Total'] == 0) {
            $nothingFound = 'Nothing Found';
            if (!empty($Config['_NoResultsText'])) {
                $nothingFound = $Config['_NoResultsText'];
            }
            $ReportReturn .= '<span class="displaying-num">' . $nothingFound . '</span>';
        } else {
            $footerPrefix = $Start + 1 . ' - ' . $toPos . ' of ';
            if (empty($Config['_Items_Per_Page'])) {
                $footerPrefix = '';
            }
            $ReportReturn .= '<span class="displaying-num">' . $footerPrefix . $Count['Total'] . ' Items</span>';
        }
        //$ReportReturn .= '<div class="reportFooter_totals">';
        if ($TotalPages > 1) {
            //$ReportReturn .= '<div class="fbutton" onclick="dr_goToPage('.$EID.', '.$First.');"><div><img src="'.WP_PLUGIN_DIR.'/db-toolkit/data_report/images/resultset_first.png" width="16" height="16" alt="First" align="absmiddle" /></div></div>';
            $ReportReturn .= '<a href="?' . $pageLink . 'npage=1" title="Go to the first page" class="first-page" onclick="dr_goToPage(\'' . $EID . '\', 1); return false;">&laquo;</a>';
            $ReportReturn .= '<a href="?' . $pageLink . 'npage=' . $Prev . '" title="Go to the previous page" class="prev-page" onclick="dr_goToPage(\'' . $EID . '\', ' . $Prev . '); return false;">&lsaquo;</a>';
            $ReportReturn .= '<span class="paging-input"> ' . $Page . ' of <span class="total-pages">' . $TotalPages . ' </span></span>';
            $ReportReturn .= '<a href="?' . $pageLink . 'npage=' . $Next . '" title="Go to the next page" class="next-page" onclick="dr_goToPage(\'' . $EID . '\', ' . $Next . '); return false;">&rsaquo;</a>';
            $ReportReturn .= '<a href="?' . $pageLink . 'npage=' . $TotalPages . '" title="Go to the last page" class="last-page" onclick="dr_goToPage(\'' . $EID . '\', ' . $TotalPages . '); return false;">&raquo;</a>';
            //$ReportReturn .= '<div class="fbutton" onclick="dr_goToPage('.$EID.', '.$Last.');"><div><img src="'.WP_PLUGIN_DIR.'/db-toolkit/data_report/images/resultset_last.png" width="16" height="16" alt="Last" align="absmiddle" /></div></div>';
        }
        $ReportReturn .= '<br class="clear"></div>';
        $ReportReturn .= '</div>';
    }
    //query
    if (is_admin()) {
        if (!empty($_GET['debug'])) {
            //$ReportReturn .= '<div id="'.$EID.'_queryDebug" class="button" style="cursor:pointer; width:100px; text-align: center;" onclick="jQuery(\'#'.$EID.'_queryDebug_panel\').toggle();">Show Query</div>';
            $ReportReturn .= '<div id="' . $EID . '_queryDebug_panel" style="display:block;">';
            $ReportReturn .= '<textarea style="width:99%; height:200px;">' . $CountQuery . '</textarea><br />';
            $ReportReturn .= '<textarea style="width:99%; height:200px;">' . $Query . '</textarea><br />';
            $ReportReturn .= 'ERRORS: ' . mysql_error();
            //$ReportReturn .= '</div>';
        }
    }
    //dump($Config);
    // Create Header and Footer Totals
    if (!empty($Config['_TotalsFields'])) {
        if (!empty($Format)) {
            // XML Output
            if (strtolower($Format) == 'xml') {
                //$apiOut .= "		</entry>\n";
            }
            // json Output
            if (strtolower($Format) == 'json') {
                //	$jsonIndex++;
            }
            //PDF Output
            if (strtolower($Format) == 'pdf') {
                //	$pdfIndex++;
                $apiOutput['Totals'] = array();
                //$apiOutput = array();
                //$apiOutput['
            }
        }
        $header = '<div class="list_row1">';
        $footer = '<div class="list_row2">';
        $hcount = 0;
        $fcount = 0;
        foreach ($Config['_TotalsFields'] as $Field => $TotalsSet) {
            //dump($TotalsSet);
            if ($TotalsSet['Location'] == 'headerinline') {
                $TotalsSet['Location'] = 'header';
            }
            if ($TotalsSet['Location'] == 'footerinline') {
                $TotalsSet['Location'] = 'footer';
            }
            $box = '<div class="stuffbox" style="width:{{width_' . $TotalsSet['Location'] . '}}%; float:left;">';
            if (!empty($TotalsSet['Title'])) {
                $Title = df_parseCamelCase($TotalsSet['Title']);
            }
            $OutValue = round($TotalsSet[$TotalsSet['Type']], 2);
            if ($TotalsSet['Function'] == 'VAT') {
                $OutValue = totals_vat($OutValue);
            }
            if ($TotalsSet['Function'] == 'AddVAT') {
                $OutValue = totals_addvat($OutValue);
            }
            $Title = df_parseCamelCase($Field);
            $Caption = ' ';
            if (!empty($TotalsSet['Caption'])) {
                $Caption = $TotalsSet['Caption'];
            }
            /// Outputs
            if (!empty($Format)) {
                // XML Output
                if (strtolower($Format) == 'xml') {
                    //	$apiOut .= "		</entry>\n";
                }
                // json Output
                if (strtolower($Format) == 'json') {
                    //	$jsonIndex++;
                }
                //PDF Output
                if (strtolower($Format) == 'pdf') {
                    $apiOutput['Totals'][$Title] = $TotalsSet['Prefix'] . $OutValue . $TotalsSet['Suffix'] . ' ' . $Caption;
                }
            }
            $box .= '<h3>' . $Title . '</h3>';
            $box .= '<div class="inside"><h1>' . $TotalsSet['Prefix'] . $OutValue . $TotalsSet['Suffix'] . '</h1></div>';
            $box .= '<div class="inside">' . $Caption . '</div>';
            $box .= '</div>';
            if (!empty(${$TotalsSet}['Location'])) {
                ${$TotalsSet}['Location'] .= $box;
            }
            switch ($TotalsSet['Location']) {
                case 'header':
                    $hcount++;
                    break;
                case 'footer':
                    $fcount++;
                    break;
            }
        }
        $header .= '<div style="clear:both;"></div></div>';
        $footer .= '<div style="clear:both;"></div></div>';
    }
    if (!empty($hcount)) {
        if ($hcount >= 1) {
            $header = str_replace('{{width_header}}', 100 / $hcount - 3, $header);
        }
    }
    if (!empty($fcount)) {
        if ($fcount >= 1) {
            $footer = str_replace('{{width_footer}}', 100 / $fcount - 3, $footer);
        }
    }
    // Run Final Totals Functions on return data
    if (!empty($GLOBALS['Totals'][$EID])) {
        foreach ($GLOBALS['Totals'][$EID] as $Key => $Output) {
            $Total = $Config['_TotalsFields'][$Output['Field']][$Config['_TotalsFields'][$Output['Field']]['Type']];
            if (!empty($GLOBALS['TotalsAverages'][$EID][$Output['Field']]['PreAverage'])) {
                if (empty($AverageBar)) {
                    //foreach$Output['PreAverage']
                    $avT = 0;
                    foreach ($GLOBALS['TotalsAverages'][$EID][$Output['Field']]['PreAverage'] as $val) {
                        $avT = $avT + $val;
                    }
                    $AverageBar = ceil($avT / count($GLOBALS['TotalsAverages'][$EID][$Output['Field']]['PreAverage']));
                }
                $Total = $AverageBar;
            }
            $func = 'totals_' . $Output['Function'];
            $newValue = $func($Output['Value'], $Total);
            $ReportReturn = str_replace($Key, $newValue, $ReportReturn);
        }
    }
    // Set Auto Widths to Averages
    if (!empty($AvrageWidth)) {
        foreach ($AvrageWidth as $Field => $Value) {
            $Tmp = 0;
            foreach ($Value as $Num) {
                $Tmp = $Tmp + $Num;
            }
            $Av = ceil($Tmp / count($Value));
            if (!empty($minWidth[$Field])) {
                if ($Av < $minWidth[$Field]) {
                    $Av = $minWidth[$Field];
                }
            }
            $Av = '';
            $ReportReturn = str_replace('width="{{width_' . $Field . '}}px"', $Av, $ReportReturn);
        }
    }
    //dump($Config);
    //echo $Query;
    // API Output
    if (!empty($Format)) {
        // XML Output
        if (strtolower($Format) == 'xml') {
            return $apiOut . "\n\t</entries>";
        }
        // json Output
        if (strtolower($Format) == 'json') {
            //$apiOutput;
            //vardump($apiOutput);
            return json_encode($apiOutput);
        }
        // PDF Output
        if (strtolower($Format) == 'pdf') {
            //$apiOutput;
            return $apiOutput;
        }
    }
    return do_shortcode($ReportReturn);
}