<?php
$start_time = microtime();
include_once("includes/common.php.inc");
include_once("includes/database.php.inc");
#$url_base = "http://209.20.80.108/chart/";
$url_base = "https://cpp1.marketrendspremium.com/chart/";
$local_url_base = "http://127.0.0.1/charting/";

//init defaults
$da     = 0; //combo dual axes - location comparison
$tt   	= 0;
$mid   	= 0;   //metric id
$sid  	= 0;  //span type id
$rows   = 0;
$gid    = 0;
$ftid   = 1;
$gty    = 3;
$mode   = 1;
$cmode  = 0;        //comparison mode (new)
$range  = '0';       //time range in years (new)
$lc     = '1|1000'; //locations (new)
$t      = 0;
$l      = 0;
$lid    = 1000;
$ltid   = 1;
$end_date = '';     //end_time (new)
$lgloc  = 'top';
$width  = WIDTH;
$height = HEIGHT;
$printmode = 0;

$show_legend = false;
$show_subheaders = false;

//fetch database data
$facet_types = get_facet_types();
$facet_values = get_facet_values();

if (!empty($_GET)) {
  foreach($_GET as $key=>$val) {
    $$key = $val;
  }
} else {
exit;
}

if ($printmode != 0) {
  $url_base = $local_url_base;
}

//legends
if (!($lgloc == 'top' || $lgloc == 'right' || $lgloc == 'bottom')) {
  $lgloc = 'top';
}

if ($rid <= 0  || $rid > 405) {
  exit; //fake report
}

//fid's to array
$fid_array = array();
if (!empty($fid)) {                           //get values
  $fid = str_replace(' ', '', $fid);           //strip extra spaces
  if ($fid[strlen($fid) - 1] == ',') {        //remove trailing comma
    $fid = substr($fid, 0, strlen($fid) - 1);
  }
  $fid_array = get_clean_fids($fid, $ftid);       //cleaned array result
  $fid = implode(',', $fid_array);                //cleaned comma separated fids
}

//add fid=1000 to use in stack bar
if (($gid == 4) || ($gid == 5)) {
   $fid_array = array_pad($fid_array, -(count($fid_array) + 1), 1000);
   $fid = implode(',', $fid_array);
}


//rid's to array
$rid_array = array();
if (!empty($rid)) {                           //get values
  $rid = str_replace(' ', '', $rid);           //strip extra spaces
  if ($rid[strlen($rid) - 1] == ',') {        //remove trailing comma
    $rid = substr($rid, 0, strlen($rid) - 1);
  }
  $rid_array = explode(',', $rid);

  if (count($rid_array) > 1) {                 //its a multi metrics rid set, do extra filtering
    foreach ($rid_array as $idx=>$val) {
      //check for extra metrics outside our accepted parameter
	 if (empty($report_details[$val]))
        unset($rid_array[$idx]);               //unset it
    }
  }
}

//ranges's to array
$range_array = array();
if (strlen($range)) {                               //get values
  $range = str_replace(' ', '', $range);           //strip extra spaces
  if ($range[strlen($range) - 1] == ',') {        //remove trailing comma
    $range = substr($range, 0, strlen($range) - 1);
  }
  $range_array = explode(',', $range);
  if (empty($range_array)) {                    //never allow empty
    $range_array[] = 0;
  } else {
    arsort($range_array, SORT_NUMERIC);          //sequence everything
  }
} else {
  exit;                        // Halt code. There is range parameter
}

//recheck default data or data after cleanup
if (empty($fid)) {          //set defaults for fid
  $fid_array[] = 1000;
  $fid = implode(',', $fid_array);
}

//recheck default data or data after cleanup
if (empty($rid)) {          //set defaults for rid
  $rid_array[] = 1;
  $rid = implode(',', $rid_array);
}


//sanity check
foreach($rid_array as $ridx=>$rval) {
  if (empty($report_details[$rval])) {
    unset($rid_array[$ridx]);
  }
}

//reverse for rtid
if (count($rid_array) == 0) {
  print 'Invalid report type.';
  exit;
}
 else {
  $rtid = $report_details[$rid_array[0]]['report'];
}

//check if custom colors are given
if (!empty($cc)) {
  $cc = str_replace(' ', '', $cc); //strip extra spaces
  $colors_array = explode(',', $cc);
}
else {
  $colors_array = $default_colors;
}
if ($mode != 4) {
  for ($i = 0; $i < count($colors_array); $i++) {
    if ($colors_array[$i][0] != '#') {
      $colors_array[$i] = '#' . $colors_array[$i];
    }
  }
}

//define column names for gauges
$col_name = '';
$len = count($rid_array);
$cnt = 0;
foreach($rid_array as $r_val) {
  $col_name .= $report_details[$r_val]['column'];
  if ($cnt < $len - 1) {
    $col_name .= ',';
  }
  $cnt++;
}

//set location for location comparison
if ($cmode == LOCATION_COMPARISON) { //location comparison
  $loc_array = get_facet_names($fid, $ftid);
  $location = $facet_types_extras[$ftid]['by'] . ': ' . $loc_array[$fid_array[0]];
} else {
  if ($ltid != 5) {
    $lid = get_true_location_id($lid); //resolve lid
    //$lid = location_alias_to_id($lid);
    $location = get_location_value_description($lid);
  }
  else {
    if (strlen((string)$lid ) < 5)
            $location = 'ZIP: ' . str_pad($lid, 5, "0", STR_PAD_LEFT);
	else
			$location = 'ZIP: ' . $lid;
  }
}

$d = false; //debug mode
$graph_name = $graph_types_values[$gid];


//tmp is label/ title
if ($mode < 3) {
  $d = (isset($debug) && $debug);
  $tmp = ($len > 1 ? $reports[$rtid] : $report_details[$rid]['title']) . $report_labels[$mid][$sid]['label'] . ($cmode != LOCATION_COMPARISON ? ' | ' . $location : '');
	if ($gid == 6) {
			$tmp = $location . '<br>' . $report_details[$rid]['title'];
	}
} elseif ($mode == 7) {    //mode 7 = dashboard view
    if ($gid == 6) {
	   $tmp = $report_details[$rid]['title'];
	 }
} else {
  $tmp = ($len > 1 ? $reports[$rtid] : $report_details[$rid]['title']) . $report_labels[$mid][$sid]['label'] . ($cmode != LOCATION_COMPARISON ? ' - ' . $location : '');
 }



//resolve special characters from Association locations
$tmp = htmlentities($tmp);
$tmp = html_entity_decode($tmp, ENT_NOQUOTES, 'UTF-8');

if (isset($title_only) && $title_only) {
  echo $tmp;
  exit;
}

$end_time = validate_end_time($end_date);
$facet_names = array();
$final_list = array();


//The POC for reporting generation
$sub_height_trim = 0;
$fid_count = count($fid_array);

$tmp_facet_names = get_facet_names($fid, $ftid);
if ($fid_count == 1) {
  if ($cmode == TIME_COMPARISON ||  $cmode == LOCATION_COMPARISON) {
    $show_legend = true;
  }
  if ($fid != 1000) {
    $show_subheaders = true;
    $sub_height_trim = 15;
     if ($cmode < TIME_COMPARISON) {
      if (count($rid_array) == 1)
	     $subheader = $facet_types_extras[$ftid]['by'];
	  else
	  $subheader = $facet_types_extras[$ftid]['by'] . ': ' . implode($tmp_facet_names);

    } else {
      $subheader = $location;
    }
  }
} else {
  $show_subheaders = true;
  $sub_height_trim = 15;
  $subheader = $facet_types_extras[$ftid]['by'];
  $show_legend = true;
}

switch ($cmode) {
  case TIME_COMPARISON :
    $max_grains = $report_spans[$sid]['grains_per_year'];
    if ($gty != 'ytd' && $gty > $max_grains) {
      $gty = $max_grains;                      //if granularity is greater than a year, force is down to a max grans for each sid
    }

    $n = count($range_array);
    $tmp_array = $colors_array;
    for ($i = 0; $i < count($range_array); $i++) {
      $colors_array[$i] = $tmp_array[($n - 1) - $i];
    }

    $fid = $fid_array[0]; // use the first value in case of a multiple select, ignore the rest
	$column = $report_details[$rid_array[0]]['column'];
    $final_list = get_datasets_by_time_comparison($column, $fid, $gty, $range_array, $lid, $ltid, $end_time, $sid);

    // Get the selected facet name and insert it into the title
    $tmp_facet_names = get_facet_names($fid, $ftid);
    if ($mode != 2) {
      $tmp_facet_name = array_shift(get_facet_names($fid, $ftid));
      $tmp = str_replace(array(' | ',' - '), array(", $tmp_facet_name | ", ", $tmp_facet_name - "), $tmp);
    }
    else {
      $subheader = $facet_types_extras[$ftid]['by'] . ': ' . implode($tmp_facet_names);
    }

    $start_date = $final_list[0]['time_period'];
    $end_date   = $final_list[count($final_list) - 1]['time_period'];

    foreach($range_array as $r) {
        $new_end_date   = generate_new_end_time($end_date, $r * 12);
        $new_start_date = generate_new_end_time($start_date, $r * 12);
        $nd = custom_date_legend($new_start_date);
        $ed = custom_date_legend($new_end_date);
        $facet_names[] = $nd . " to " . $ed;

    }
  break;
  case LOCATION_COMPARISON :
    //$fid = 1000; // always use the ALL fid for this type of comparison, bypass everything else
    $fid = $fid_array[0]; // use the first value in case of a multiple select, ignore the rest
    $column = $report_details[$rid_array[0]]['column'];
    $lc_array = array();

    if (!empty($lc)) {
      $lc = str_replace(' ', '', $lc);
      if ($lc[strlen($lc) - 1] == ',') {
        $lc = substr($lc, 0, strlen($lc) - 1);
      }

      if (!empty($lc)) {
        $lc_tmp = explode(',', $lc);

        foreach($lc_tmp as $val) {

          $lc_tmp = explode('|', $val);

		  if ($da == 1) {
		    if ($lc_tmp[0] != 5) {
                $tmp_loc_name = get_location_types($lc_tmp[0]) . ': ' . htmlentities(get_location_value_description(get_true_location_id($lc_tmp[1])));
                $tmp_loc_name = html_entity_decode($tmp_loc_name, ENT_NOQUOTES, 'UTF-8');
            } else {
			    if (strlen($lc_tmp[1]) < 5)
                   $tmp_loc_name = 'ZIP: ' . str_pad($lc_tmp[1], 5, '0', STR_PAD_LEFT);
				else
				   $tmp_loc_name = 'ZIP: ' . $lc_tmp[1];
            }
		  } else {
			if ($lc_tmp[0] != 5) {
				$tmp_loc_name = htmlentities(get_location_value_description(get_true_location_id($lc_tmp[1])));
				$tmp_loc_name = html_entity_decode($tmp_loc_name, ENT_NOQUOTES, 'UTF-8');
          } else {
				if (strlen($lc_tmp[1]) < 5)
                   $tmp_loc_name = 'ZIP: ' . str_pad($lc_tmp[1], 5, '0', STR_PAD_LEFT);
				else
				   $tmp_loc_name = 'ZIP: ' . $lc_tmp[1];
            }
		  }
          $facet_names[] = $tmp_loc_name; //resolve lid
          $lc_array[] = $lc_tmp;
        }
      } else {
        exit;
      }
    }  else {
      echo 'Location comparison parameter <i>(lc)</i> must not be empty.'; exit;
    }
    $final_list = get_datasets_by_location_comparison_mid($column, $fid, $gty, $lc_array, $end_time, $sid, $mid);
  break;
  default :
    $final_list = get_datasets_mid($col_name, $fid, $ftid, $gty, $lid, $ltid, $end_time, $d, $sid, $mid);
	if (($gid == 4) || ($gid == 5)) {
	    if ($len > 1) {
			echo "Invalid report";
			exit;
		} else {
         $facet_names = get_facet_names_stack($fid, $ftid);
		 }
	 } else {
		if ($len > 1) {
			$facet_names = metrics_to_facets($rid_array);
		}
		else {
			$facet_names = get_facet_names($fid, $ftid);
		}
	}
  break;
}

//print '<pre>';
//print_r($final_list);
//print '</pre>';

//percentage against all computation (stack bar)
foreach($final_list as $id=>$val) {
	if (($gid == 4) || ($gid == 5)) {

		foreach($val as $idx => $val_val) {
		   if ($idx != 'time_period') {
			   if (empty($val['All']) || $val['All'] == 0) {
					$val[$idx] = 0;
			   } else {
					$all = $val['All'];
					if ($idx != 'All') {
						$cur = $val[$idx];
						$val[$idx] = number_format(($cur / $all) * 100, 1);
				   }
			    }
			}
		}
        unset($val['All']); //remove all (fid=1000) on final list array
		$final_list[$id] = $val;
	}
}


$rows = count($final_list);
$ld = 1;
if ($rows > 12) { //used to limit x-axis titles display in order to avoid overlap
  $ld = $rows / 12;
}

if ($mode == 3) {
  $url = 'http://' . $_SERVER['HTTP_HOST'] . str_replace('mode=3', 'mode=2', $_SERVER['REQUEST_URI']);
  $url .= '&printmode=1';

  header("Content-Description: File Transfer");
  header("Cache-Control: public; must-revalidate, max-age=0");
  header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
  header("Last-Modified: " . gmdate('D, d m Y H:i:s') . " GMT");
  header("Content-Type: application/force-download");
  header("Content-Type: application/octec-stream", false);
  header("Content-Type: application/download", false);
  header("Content-Transfer-Encoding: binary");
  header('Content-Disposition: attachment; filename="' . $tmp . '";');
  header("Content-Type: application/pdf", false);
  system($wkhtmltopdf_path . ' "' . $url . '" -', $_output);

  echo $_output;
  exit;
}

//getting the minimal and maximum value
$min_value = 1000000000; //start with the highest improbable value to find the smallest one
$max_value = -1000000000;          //start with the lowest possible value to find the largest one
foreach($final_list as $list) {
  $i = 0;
  foreach($list as $id=>$val) {
    if ($i != 0) {
      if($val > $max_value) $max_value = $val;
      if ($val < $min_value) $min_value = $val;
    }
    $i++;
  }
}

//print "$min_value/$max_value";
$max_value *= 10000;
$min_value *= 10000;

//$min_value -= ($min_value * .50);
$min_p = strlen(abs($min_value)) - 1;
$max_p = strlen(abs($max_value)) - 1;

$min_value = (floor($min_value/pow(10, $min_p))*pow(10, $min_p));
$max_value = (ceil($max_value/pow(10, $max_p - 1))*pow(10, $max_p - 1));
$pre_cuts = $max_value - $min_value;
$cuts      = ($max_value - $min_value) / 4;
$precision = strlen((string)$cuts) - 1;
$max_value = $min_value + 4 * $cuts;

$cuts /= 10000;
$max_value /= 10000;
$min_value /= 10000;


//PNG
if ($mode == 4) {
  if ($gid != 6) {
//	$url = 'http://' . $_SERVER['HTTP_HOST'] . str_replace('mode=4', 'mode=2', $_SERVER['REQUEST_URI']);
	$url = 'http://127.0.0.1' . str_replace('mode=4', 'mode=2', $_SERVER['REQUEST_URI']);
  } else {
//     $url = 'http://' . $_SERVER['HTTP_HOST'] . str_replace('mode=4', 'mode=7', $_SERVER['REQUEST_URI']);
     $url = 'http://127.0.0.1' . str_replace('mode=4', 'mode=7', $_SERVER['REQUEST_URI']);
  }
  $url .= '&printmode=2';
  $temp_file = sys_get_temp_dir() . '/' . time() . '.png';
  header('Content-Type: image/png');
  header('Content-Disposition: inline; filename="' . $tmp . '.png";');
  system($wkhtmltoimage_path . ' --format png --quality 70 --width ' . $width . ' "' . $url . '" ' . $temp_file);
  fpassthru(fopen($temp_file, 'r'));
  unlink($temp_file);
  exit;
}

	if (($gid == 4) || ($gid == 5)) {
		$prefix = $report_units[$rtid][1]['prefix'];
		$suffix = $report_units[$rtid][1]['suffix'];
	} elseif ($tt) {
		$prefix = $report_units[$rtid][0]['prefix'];
		$suffix = $report_units[$rtid][0]['suffix'];
    } else {
		$prefix = $report_units[$rtid][$mid]['prefix'];
		$suffix = $report_units[$rtid][$mid]['suffix'];
	}

if ($mode == 5 || $mode == 6) {
  //csv mode
	$csv_array = array();
	$header[] = iconv('UTF-8', 'ISO-8859-1', $tmp);
	$ftr = (defined('FOOTER') ? trim(FOOTER) : '©2010 RealEstate Business Intelligence, an MRIS Company.');
	if ($mode == 5) {          //convert for csv output, keep original for xls output
		$ftr = iconv('UTF-8', 'ISO-8859-1', $ftr);
	}

	$footer[] = $ftr;
	$head[] = 'Date'; //csv header

	foreach($facet_names as $k=>$v) {
		$head[] = $v;
	}

	$month_count = 1;
	foreach($final_list as $k=>$v) {
		$x = 0;
		foreach($v as $v_idx=>$v_val) {
			if ($x == 0) {
				if ($cmode == 1) {
					$v['time_period'] = custom_date_month($v_val);  //
				} else {
					$v['time_period'] = custom_date($v_val); //custom_date
				}
			} else {
				if ($mode == 5) {
					if($suffix == '%') {
						$v[$v_idx] = $prefix . number_format($v_val,2) . $suffix;
					} else {
						$v[$v_idx] = $prefix . number_format($v_val) . $suffix;
					}
				} else {
            $v[$v_idx] = $v_val;
          }
				}
      $x++;
    }
    $month_count++;
    $final_list[$k] = $v;
	}


//reverse order from most recent descending
  $final_list = array_reverse($final_list);

  $csv_array[] = $header;

  $freezeStart = 5;
  if ($fid != '1000') { //subheader blues
    $header_ftid[] = $facet_types_extras[$ftid]['by'];
    $freezeStart = 6;
    $csv_array[] = $header_ftid;
  }
  $csv_array[] = $footer;
  $csv_array[] = array();
  $csv_array[] = $head;
  $csv_array = array_merge($csv_array, $final_list);

  if ($mode == 5) {
    function outputCSV($data) {
      $outstream = fopen("php://output", 'w');
      function __outputCSV(&$vals, $key, $filehandler) {
        fputcsv($filehandler, $vals, ',', '"');
      }
      array_walk($data, '__outputCSV', $outstream);
      fclose($outstream);
    }

    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $tmp . '.csv"');
    outputCSV($csv_array);
    exit;
  }

  if ($mode == 6) {
    export_array_to_excel($csv_array, 'Sheet 1', $tmp . '.xls', $freezeStart, $prefix, $suffix, count($fid_array) + 1);
  }
}

//make colors
if ($gid == 6) {
	$colors = 'colors:[';
	for($i = 0; $i < 2; $i++) {
		$colors .= '"' . $colors_array[$i] . '",';
	}
	$colors = substr_replace($colors, "", -1);
	$colors .= ']';
} else {
	$colors = 'colors:[';
	for($i = 0; $i < count($facet_names); $i++) {
		$colors .= '"' . $colors_array[$i] . '",';
	}
	$colors = substr_replace($colors, "", -1);
	$colors .= ']';
}

$chart_title = ($mode > 1 ? $tmp : "");
$chart_legend = '
      legend: "' . $lgloc . '",
      legendTextStyle: {color: "#777777", fontName: "Arial", fontSize: 11.5},
';


#css facet computations
$max_facet_length = 0;
foreach($facet_names as $facet) {
  if (strlen($facet) > $max_facet_length) {
    $max_facet_length = strlen($facet);
  }
}

//determine categories and series
$categories = array();
$categories = 'categories:[';
$series = 'series:[';
$series_array = array();
$series_index = 1;


foreach($facet_names as $f_idx=>$facet_name) {
  $series_array[$series_index++] = array('name' => $facet_name, 'data' => '');
}

$mc = count($final_list);  //month count
$step_interval = 1;

if ($sid == 0 && $mc > 12) {
   if ($mc < 18 != 0) {
		$step_interval = floor($mc / 12);
	} else {
		$step_interval = ceil($mc / 12);
	}
}

if ($sid == 1 && $mc >= 14) {
	$step_interval = floor($mc / 8);
}

if ($width < 500) {
  $step_interval *= 2;
}


//$comma_count = 0;
$table_content = '';
if ($gid == 1) {
  $final_list = array_reverse($final_list);
}

foreach($final_list as $fl_id=>$fl_val) {
  $date = '';
  $i = 0;
  $table_content .= '<tr class="facet_values' . (($fl_id % 2 == 1) ? ' even' : '') . '"><td>' . ($fl_id + 1) . '</td>';
  foreach($fl_val as $vid=>$val) {

	if ($i == 0) {
      switch ($cmode) {
        case 0 :
            $date = custom_date($val);
        break;
        case 1 :
          $date = custom_date_month($val);
        break;
        case 2 :
          $date = custom_date($val);
        break;
        case 3 :
            $date = custom_date($val);
      }
      $table_content .= '<td>' . $date . '</td>';
      $categories .= '"' . $date . '",';
	  $comma = 0;

    } else {
      if ($gid == 1) {
        $table_content .= '<td>' . $prefix . number_format($val, ($rid == 9 ? 2 : 0)) . $suffix . '</td>';
      } else {
          $series_array[$i]['data'] .= $val . ',';
      }
    }
    $i++;
  }//foreach
  $table_content .= '</tr>';
}//foreach

  $categories .= ']';

$slen = count($series_array);

if (($gid == 4) || ($gid == 5)) {

	foreach($series_array as $series_value) {
	 $data = substr_replace($series_value['data'], "", -1);
		$series .= '{
          name: "' . $series_value['name'] . '",
          data: [' . $data . ']
        },' . "\n";
    }
 $series = substr_replace($series, "", -2);
 }  elseif ($da == 1) {
     foreach($series_array as $series_value) {
	  $data = substr_replace($series_value['data'], "", -1);

	  if ($series_value == end($series_array)) {
		$series .= '{
          name: "' . $series_value['name'] . '",
          data: [' . $data . '],
          type: "line",
		  yAxis: 1
        },' . "\n";
	  } else {
		$series .= '{
          name: "' . $series_value['name'] . '",
          data: [' . $data . '],
          type: "column"
        },' . "\n";
	 }
    }
    $series = substr_replace($series, "", -2);
 } else {
	foreach($series_array as $series_value) {

	    $data = substr_replace($series_value['data'], "", -1);
		$series .= '{
          name: "' . $series_value['name'] . '",
          data: [' . $data . '],
          marker: {
            symbol: "circle"
          }
        },' . "\n";
   }
   $series = substr_replace($series, "", -2);
}



$series .= ']';

$dateArr = substr($categories, 12);
$dateArr1 = str_getcsv($dateArr, ',', '"', ']');
$remove_last = array_pop($dateArr1);


$tt_array = array();
if (!empty($tt)) {
  $tt = str_replace(' ', '', $tt);
  if ($tt[strlen($tt) - 1] == ',') {
    $tt = substr($tt, 0, strlen($tt) - 1);
  }
  $tt_array = explode(',', $tt);
}

if (empty($tt)) {
  $tt_array[] = 0;
  $tt = implode(',', $tt_array);
}

//compute for % Change
if ($cmode == 2) {
    $tooltip_m =  get_datasets_by_location_comparison_mid($column, $fid, $gty, $lc_array, $end_time, $sid, 1);
    $tooltip_y =  get_datasets_by_location_comparison_mid($column, $fid, $gty, $lc_array, $end_time, $sid, 2);
    if ($mid > 0) {
      $tooltip_o = get_datasets_by_location_comparison_mid($column, $fid, $gty, $lc_array, $end_time, $sid, 0); //get original value
    }
} else {
    $tooltip_m = get_datasets_mid($col_name, $fid, $ftid, $gty, $lid, $ltid, $end_time, $d, $sid, 1);
    $tooltip_y = get_datasets_mid($col_name, $fid, $ftid, $gty, $lid, $ltid, $end_time, $d, $sid, 2);
    if ($mid > 0) {
      $tooltip_o = get_datasets_mid($col_name, $fid, $ftid, $gty, $lid, $ltid, $end_time, $d, $sid, 0); //get original value
    }
}

$a_comma_count = 0;
$m_comma_count = 0;
$extra_data = '{';
foreach($final_list as $id=>$value) {
	foreach($tt_array as $val){
		if ($mid > 0) {
			$orig_values = 'lo:{';
			foreach($tooltip_o[$id] as $key=>$facet_value) {
				if ($key == 'time_period') {
					$time_period_o = $facet_value;
					$comma_count = 0;
				}
				else {
					if ($comma_count > 0) {
						$orig_values .= ',';
					}
					$comma_count++;
					$series_name = $series_array[$comma_count]['name'];
					$orig_values .= "\"$series_name\":\"$facet_value\"";
				} //else
			}//foreach
			$orig_values .= '}';
		}

		if ($val == 1) {
			$month_values = 'lm:{';
			foreach($tooltip_m[$id] as $key=>$facet_value) {
				if ($key == 'time_period') {
					$time_period_m = $facet_value;
					$comma_count = 0;
				} else {
					if ($comma_count > 0) {
						$month_values .= ',';
					}
					$comma_count++;
					$series_name = $series_array[$comma_count]['name'];
					$month_values .= "\"$series_name\":\"$facet_value\"";
				} //else
			}//foreach
			$month_values .= '}';

			foreach($dateArr1 as $idx=>$new_date) {
				$time_period_m = generate_new_end_time_period($tooltip_m[$id]['time_period'], $sid);
			}
			$time_period_m = custom_date($time_period_m);
		}
		elseif ($val == 2) {
			$year_values = 'ly:{';
			foreach($tooltip_y[$id] as $key=>$facet_value) {
				if ($key == 'time_period') {
					$time_period_y = $facet_value;
					$comma_count = 0;
				} else {
					if ($comma_count > 0) {
						$year_values .= ',';
					}
					$comma_count++;
					$series_name = $series_array[$comma_count]['name'];
					$year_values .= "\"$series_name\":\"$facet_value\"";
				}
			}//foreach
			$year_values .= '}';

			foreach($dateArr1 as $idx=>$new_date) {
				$time_period_y = generate_new_end_time($tooltip_y[$id]['time_period'], 12, $sid);
			}
			$time_period_y = custom_date($time_period_y);

		}
		elseif ($tt == 3) {
			$month_values = 'lm:{';
			foreach($tooltip_m[$id] as $key=>$facet_value) {
				if ($key == 'time_period') {
					$time_period_m = $facet_value;
					$comma_count = 0;
				} else {
					if ($comma_count > 0) {
						$month_values .= ',';
					}
					$comma_count++;
					$series_name = $series_array[$comma_count]['name'];
					$month_values .= "\"$series_name\":\"$facet_value\"";
				}
			} //foreach
			$month_values .= '}';

			$year_values = 'ly:{';
			foreach($tooltip_y[$id] as $key=>$facet_value) {
				if ($key == 'time_period') {
					$time_period_y = $facet_value;
					$comma_count = 0;
				} else {
					if ($comma_count > 0) {
						$year_values .= ',';
					}
					$comma_count++;
					$series_name = $series_array[$comma_count]['name'];
					$year_values .= "\"$series_name\":\"$facet_value\"";
				}
			} //foreach
			$year_values .= '}';

			foreach($dateArr1 as $idx=>$new_date) {
				$time_period_m = generate_new_end_time_period($tooltip_m[$id]['time_period'], $sid);
				$time_period_y = generate_new_end_time($tooltip_y[$id]['time_period'], 12, $sid);
			}
			$time_period_m = custom_date($time_period_m);
			$time_period_y = custom_date($time_period_y);
        } //elseif

		//extra datas
		$commas = '';
		if ($tt == 3) {
			$commas = ',';
		}

		if ($a_comma_count > 0) {
			$extra_data .= ",\n";
		}
		else {
			$a_comma_count++;
		}

		$m = ''; $m_vals = '';
		if ($tt == 1 || $tt == 3) {
				$m = "labelm:'$time_period_m'" . $commas;
				$m_vals = $month_values . $commas;
		}
		$y = ''; $y_vals = '';
		if ($tt == 2 || $tt == 3) {
				$y = "labely:'$time_period_y'";
				$y_vals = $year_values;
		}
		$o_vals = '';
		if ($mid > 0) {
			$o_vals = ',' . $orig_values;
		}
		$extra_data .= "'$dateArr1[$id]':{" . $m . $y . "," . $m_vals . $y_vals . $o_vals . "}";

  } //foreach
} //foreach
$extra_data .= '}';




//for gauge chart
if ($gid == 6) {
      if ($mode == 7) {
	    $width = 220;
		$height = 230;
	} elseif ($width >= 500) {
		$height = .75 * $width;
	}

    $max_grains = $report_spans[$sid]['grains_per_year'];
    if ($gty != 'ytd' && $gty > $max_grains) {
      $gty = $max_grains;
    }

    $fid = $fid_array[0]; // use the first value in case of a multiple select, ignore the rest
    $column = $report_details[$rid_array[0]]['column'];
	$range_array = array();
	$r = 4;
	for($i=0; $i<5; $i++) {
	     $range_array[] = $r--;
	}

    $final_list = get_datasets_by_time_comparison($column, $fid, $gty=1, $range_array, $lid, $ltid, $end_date, $sid);

	$list = array();
	foreach($final_list as $id=>$val) {
		foreach($val as $idx=>$val_v){
			if ($idx != 'time_period') {
				if($val_v == null) {
				    $val_v = 0;
				}
				$list[] = $val_v;
			}
		}
	}
    $max_value = list_max($list);
	$min_value = list_min($list);
	$avg_value = list_average($list);
	$avg_val2 = number_format($avg_value, ($rtid <= 3 || $rtid == 5 ? 0 : (strpos($avg_value, '.') ? 1 : 0)), '.', ',');
	$cur_val   = end($list);
	$cur_val2 = number_format($cur_val, (strpos($cur_val, '.') ? 1 : 0), '.', ',');
	$cur_val3 = number_format($cur_val, (strpos($cur_val, '.') ? 1 : 0), '.', '');
	$end_date   = $final_list[count($final_list) - 1]['time_period'];
    $legend = custom_date_legend($end_date);
	$month = custom_date_legend_month($end_date);

    $name_val = $legend . ' (' . $prefix . $cur_val2 . $suffix . ')';
	$name_avg = '5-Yr ' . $month . ' Avg ' . ' (' . $prefix . $avg_val2 . $suffix . ')';
	$name_avg_t = '5-Yr ' . $month . ' Avg ';

	$prefix = $report_units[$rtid][$mid]['prefix'];
	$suffix = $report_units[$rtid][$mid]['suffix'];

	$series_gauge = 'series:[';

		$series_gauge .= '{
          name: "' . $name_val . '",
          data: [' . $cur_val3 . '],
		  dial: {
              backgroundColor: "' . $colors_array[0] . '"
		  }
        }, {
          name: "' . $name_avg . '",
          data: [' . $avg_val2 . '],
          dial: {
              backgroundColor: "none"
		  }
        }'  . "\n";

    $series_gauge .= '],';

   $value_cur = $prefix . $cur_val2 . $suffix;
   $value_avg = $prefix . $avg_val2 . $suffix;
   $tooltip_name_cur = "'$legend: <b>$value_cur</b>'";
   $tooltip_name_avg = "'$name_avg_t: <b>$value_avg</b>'";
   $tooltip_gauge = '{';
   $tooltip_gauge .= "'$name_val':{label:$tooltip_name_cur},'$name_avg':{label:$tooltip_name_avg}";
   $tooltip_gauge .= '}';
}

//print '<pre>';
//print_r($final_list);

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<script type="text/javascript">
  // Prevent error dialogs from displaying -which is the window's normal
  window.onerror = null;

  if(typeof(Object)==='undefined'){
    window.location.reload(true);
  }
  if(typeof(Math)==='undefined'){
    window.location.reload(true);
  }
</script>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Cache-Control" content="no-cache" />
<title><?php echo htmlentities($tmp);?></title>
<?php if ($gid == 1) { //Tables
  $div_content = '';
  if ($mode == 2) {
  $div_content .= '<h1 style="font: bold 1.1em Arial,Helvetica,sans-serif; margin:0 0 1em">' . $chart_title;
  	if ($show_subheaders) {
  		$div_content .= '<div style="font: normal 0.8em Arial,Helvetica,sans-serif">' . $subheader . '</div>';
	}
	$div_content .= '</h1>';
  }
  else {
  $div_content .= '
  <div style="width:' . $width . 'px; height:' . $height . 'px; overflow:auto; position: relative;">';
  }
  $div_content .= '<table width="100%" border="0" cellspacing="2" cellpadding="0">';

  //facet names
  $div_content .= '<tr class="facet_names"><td width="20px">&nbsp;</td>';
  $div_content .= '<td width="90px">Month</td>';
  foreach($facet_names as $facet_name) {
    $div_content .= '<td>' . $facet_name . '</td>';
  }
  $div_content .= '</tr>';
  $div_content .= $table_content;
  $div_content .= '</table></div>';
?>
<style type="text/css">
body {
  margin: 0px;
  background-color: #FFF;
}
table {
  /*border: 1px solid #999;*/
  font-family: Arial, Helvetica, sans-serif;
  font-size: 10pt;
  margin: 0px;
  background-color: #EEEEEE;
}
table * {
  padding: 2px;
}
tr:hover {
  background-color:#E7E9f9;
}
tr {
  background-color: #FFFFFF;
}
td {
  text-align: right;
  padding-top: 2px;
  padding-right: 3px;
  padding-bottom: 2px;
  padding-left: 2px;
}
.facet_names td {
  background-color: #FFF;
  font-weight: bold;
  text-align: center;
  padding: 2px 3px;
  background-image: url(image/title-bg.gif);
  background-position: bottom;
  background-repeat: repeat-x;
}
.even {
  background-color:#FAFAFA;
}
</style>
<?php } else { //other charts
  $div_content = 'chart goes here';
?>
<style type="text/css">
body {
  margin: 0px;
  background-color: #FFF;
}
</style>

<?php
  $this_server = $_SERVER['HTTP_USER_AGENT'];
  if( strpos($this_server, 'MSIE 9.0') !== FALSE ){
?>
<script type="text/javascript" src="<?php echo $url_base; ?>js/jquery.1.5.1.min.js"></script>
<?php }else{ ?>
<script type="text/javascript" src="<?php echo $url_base; ?>js/jquery.min.js"></script>
<?php } ?>
<script type="text/javascript" src="<?php echo $url_base; ?>js/highcharts.js"></script>
<?php
  if( $_GET['gid'] == 6 ){
?>
<script type="text/javascript" src="<?php echo $url_base; ?>js/highcharts_more_2.3.5.js"></script>
<script type="text/javascript" src="<?php echo $url_base; ?>js/exporting.js"></script>
<?php } ?>
<script type="text/javascript">
  var chart;

  <?php
    if ($tt) {
      echo "  var tooltip_data = $extra_data;";
    }

  ?>
  <?php if ($gid != 6) {?>
  $(document).ready(function() {
    window.onerror = null;
    if(typeof(Object)==='undefined'){
      window.location.reload(true);
    }

    chart = new Highcharts.Chart({
      <?php
        $subtitle_y = 20;
        $use_webkit_pad = false;
        if (isset($_SERVER['HTTP_USER_AGENT'])) {
          $use_webkit_pad = (strpos($_SERVER['HTTP_USER_AGENT'], 'WebKit') !== FALSE);  //for browsers that use webkit to render svn
        }
        if ($ltid == 3 && $width < 400) { // location type association
          $search = array(' Association', ' Board');
          $replace = array('<br>Association', '<br>Board');
          $chart_title = str_replace($search, $replace, $chart_title);
          $subtitle_y = 32;
        }
      ?>
      chart: {
        renderTo: "chart_div",
		<?php
        if ($width < 400 && $mode > 1 && !$show_subheaders) {
          echo '  marginTop: 40,';
        }
      ?>
        defaultSeriesType: "<?php echo $graph_name;?>"
      },

      title: {
        text: '<div dy="10"><?php echo $chart_title;?></div>',
        floating: false,
        align: 'left',
        style: {
          fontFamily: 'Arial,Helvetica,sans-serif',
          fontSize: "<?php echo ($width > 500 ? '12px' : '11px');?>",
          <?php if ($use_webkit_pad) { ?>
          lineHeight: 14,
          <?php } ?>
          fontWeight: 'bold',
          color: '#000000'
        },
        y: 5    <?php //fix to the top  ?>
      },
      <?php echo $colors;?>,
      xAxis: {
        <?php echo $categories;?>,
        labels: {
          step: <?php echo $step_interval;?>,
          formatter: function() {
            return this.value.replace(" ", "<br/>");
          }
        },
        tickLength: 0
      },
      yAxis: [{
	  	min: <?php echo $min_value;?>,
	  	max: <?php echo $max_value;?>,

      <?php if ($da) {?> //primary y axis
        <?php if ($width >= 500) {?>
		labels: {
          formatter: function() {
            return Highcharts.numberFormat(this.value, <?php echo ($rtid == 4 ? 2 : ($mid > 0 ? 1 : 0));?>, '.', ',');
          }
        },

		title: {
                    text: 'ZIP & City'
        }

	    }, { //secondary y axis
		title: {
                    text: 'County'
        },
		labels: {
            formatter: function() {
                 return Highcharts.numberFormat(this.value, <?php echo ($rtid == 4 ? 2 : ($mid > 0 ? 1 : 0));?>, '.', ',');
              }
        },
		<?php } ?>
			opposite: true,
	 <?php } else {?>
			<?php if ($width >= 500) {?>
        labels: {
          formatter: function() {
            return Highcharts.numberFormat(this.value, <?php echo ($rtid == 4 ? 2 : ($mid > 0 ? 1 : 0));?>, '.', ',');
          }
        },
			<?php } ?>
		title: {
          text: ""
        },
	 <?php } ?>
        plotLines: [{
          value: 0,
          width: 3,
          color: '#000000'
        }]
      }],


      plotOptions: {
        series: {
      <?php if ($printmode) { ?>
          enableMouseTracking: false, //for printing
          shadow: false,               //for printing
          animation: false,            //for printing
          marker: {
            radius: 3
          }
      <?php } ?>
      <?php if ($gty >= 36 || $gid == 3) {  //hide plot points if data size is 3 years or more
          if ($printmode) echo ',';
      ?>
          marker: {
            enabled: false,
            radius: 2,
            states: {
              hover: {
                  enabled: true
              }
            }
          }
        },
        column: {
          borderWidth: 0,

	<?php if (($gid == 4) || ($gid == 5)) {
       if ($printmode) echo ','; ?>
		  stacking: 'normal',
		  <?php if ($gid == 5) { ?>
          dataLabels: {
                        enabled: true,
						align: 'center',
						distance: -1,
                        color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white'
                    }
          <?php } ?>
		<?php } ?>
	       shadow: false
	  <?php } ?>

		}
      },
      <?php echo $series;?>,
      tooltip: {
            <?php
          if ($tt == 1) {
          ?>
			formatter: function() {
				var pref = tooltip_data[this.x].lm[this.series.name] > 0 ? '+' : '';
				return this.series.name + '<br/>' + this.x + ': <b><?php echo $prefix;?>' +
					Highcharts.numberFormat(<?php echo ($mid > 0 ? 'tooltip_data[this.x].lo[this.series.name]' : 'this.y');?>, <?php echo ($rtid == 4 ? 1 : 0);?>, '.', ',') +
								 '<?php echo $suffix;?></b><br/>' +
					'Change from ' + tooltip_data[this.x].labelm + ': <b>' + pref + Highcharts.numberFormat(tooltip_data[this.x].lm[this.series.name], 1) + '%</b>';
			},
           <?php } elseif ($tt == 2) { ?>
			formatter: function() {
				var pref = tooltip_data[this.x].ly[this.series.name] > 0 ? '+' : '';
				return this.series.name + '<br/>' + this.x + ': <b><?php echo $prefix;?>' +
					Highcharts.numberFormat(<?php echo ($mid > 0 ? 'tooltip_data[this.x].lo[this.series.name]' : 'this.y');?>, <?php echo ($rtid == 4 ? 1 : 0);?>, '.', ',') +
								 '<?php echo $suffix;?></b><br/>' +
					'Change from ' + tooltip_data[this.x].labely + ': <b>' + pref + Highcharts.numberFormat(tooltip_data[this.x].ly[this.series.name], 1) + '%</b>';
			},
			<?php } elseif ($tt == 3) { ?>
			formatter: function() {
				var pref = tooltip_data[this.x].lm[this.series.name] > 0 ? '+' : '';
				var pref2 = tooltip_data[this.x].ly[this.series.name] > 0 ? '+' : '';
				return this.series.name + '<br/>' + this.x + ': <b><?php echo $prefix;?>' +
					Highcharts.numberFormat(<?php echo ($mid > 0 ? 'tooltip_data[this.x].lo[this.series.name]' : 'this.y');?>, <?php echo ($rtid == 4 ? 1 : 0);?>, '.', ',') +
								 '<?php echo $suffix;?></b><br/>' +
					'Change from ' + tooltip_data[this.x].labelm + ': <b>' + pref + Highcharts.numberFormat(tooltip_data[this.x].lm[this.series.name], 1) + '%<br/>' +
					'Change from ' + tooltip_data[this.x].labely + ': <b>' + pref2 + Highcharts.numberFormat(tooltip_data[this.x].ly[this.series.name], 1, '.', ',') + '%</b>';
			},
			<?php } else { ?>
			formatter: function() {
				return this.series.name + '<br/>' + this.x + ': <b><?php echo $prefix;?>' + Highcharts.numberFormat(this.y, <?php echo ((($rtid == 4) || ($mid > 0) || ($gid == 4) || ($gid == 5)) ? 1 : 0);?>, '.', ',') + '<?php echo $suffix;?></b>';
        },
		<?php }  ?>
			shared: false
      },
      <?php if ($mode > 1) { ?>
		<?php if ($show_subheaders) { ?>
		subtitle: {
			text: "<?php echo $subheader;?>",
			floating: false,
			align: 'left',
			style: {
				fontFamily: 'Arial,Helvetica,sans-serif',
				fontSize: "<?php echo ($width > 500 ? '12px' : '11px');?>",
				color: '#000000'
			},
			y : <?php echo $subtitle_y;?>
		},
      <?php }
        $footer = defined('FOOTER') ? FOOTER : '©2010 RealEstate Business Intelligence, an MRIS Company.';
        if ($width < 600) {
          $footer = str_replace('.', '<br/>', $footer);
        }
      ?>
      credits: {
        text: "<?php echo $footer;?>",
        href: "",
        position: {
          align: "center",
          y: <?php echo ($width < 600 ? '-18' : '-5'); ?>
        },
        style: {
          fontSize: "<?php echo ($width > 500 ? '11px' : '10px');?>",
//          fontStyle: "italic",
          <?php if ($use_webkit_pad) { ?>
          lineHeight: 14,
          <?php } ?>
          color: '#333333'
        }
      },
      legend: {
        itemStyle: {
          fontFamily: 'Arial,Helvetica,sans-serif',
          fontSize: "<?php echo ($width > 500 ? '10px' : '9px');?>",
          color: '#000000'
        },
        style: {
          padding: 7
        },
        margin: 5,
        y: <?php echo ($width < 600 ? '-15' : '-5'); ?>,
        symbolWidth: 4
      },
      <?php } else { ?>
      credits: {
        enabled: false
      },
      legend: {
        enabled: false
      },
      <?php } ?>
	  exporting: {
         enabled: false
      }
    });
  });

  <?php } else { ?>

  $(document).ready(function() {

	 <?php
      echo "  var tooltip_data = $tooltip_gauge;";
    ?>
     var mywidth = $('#chart_div').width();

    chart = new Highcharts.Chart({
	 chart: {
        renderTo: "chart_div",
        defaultSeriesType: "gauge",
	    plotBackgroundColor: null,
        plotBackgroundImage: null,
        plotBorderWidth: 0,
        plotShadow: false
     },

	   title: {
			text: '<div dy="10"><?php echo $chart_title;?></div>',
			style: {
				fontFamily: 'Arial,Helvetica,sans-serif',
				fontWeight: 'bold',
				fontSize: '12px',
				color: '#000000'
			}
		},

	    pane: {
	        center: ['50%', mywidth/2],
            size: mywidth-20,
            startAngle: -90,
            endAngle: 90,
			background: {
			 backgroundColor: '#FFF',  //gray
                borderWidth: 0,
                outerRadius: '105%',
                innerRadius: '103%' }
        },

		legend: {
            layout: 'vertical'
        },

		yAxis: {
	        min: <?php echo $min_value;?>,
            max: <?php echo $max_value;?>,
            lineWidth: 0,

            minorTickInterval: 'auto',
            minorTickWidth: 0,
            minorTickLength: 0,
            minorTickPosition: 'inside',
            minorTickColor: '#666',


            tickPixelInterval: '20',
            tickWidth: 1,
            tickPosition: 'inside',
            tickLength: (mywidth/20)-1,
            tickColor: '#ffffff',
            labels: {
                step: 4,
                rotation: 'auto',
				distance: -1*((mywidth/10)+10),
			    formatter:function(){
                   if ((Math.abs(this.value) / 10000) > 1){
                       return Highcharts.numberFormat(this.value/1000, 0) + 'k';
                } else {
                    return this.value;
                };
                }
            },

              plotBands: [{
                from: <?php echo $min_value;?>,
                to: <?php echo $avg_value;?>,
				color: '<?php echo $colors_array[1];?>',
				outerRadius: '100%',
                innerRadius: '80%'
            }, {
                from: <?php echo $avg_value;?>,
                to: <?php echo $max_value;?>,
				color: '#cccccc',
				outerRadius: '100%',
				innerRadius: '80%'

            }]
		 },
		  plotOptions: {
		    series: {
              <?php if ($printmode) { ?>
				animation: false            //for printing
			  <?php } ?>
			},

            gauge: {
			    width: 10,
                dataLabels: {
                    enabled: false,
                    borderWidth: 0
                },
                dial: {
                    radius: '110%',
					borderWidth: 1,
                    baseWidth: 8,
                    topWidth: 2,
                    baseLength: '0%', // of radius
                    rearLength: '0%'
                },
				showInLegend: true
            }
        },

		<?php echo $colors;?>,
		<?php echo $series_gauge;?>
		tooltip: {
              formatter: function() {
                  return tooltip_data[this.series.name].label;
              }
        },
		credits: {
              enabled : false
       },
	    exporting: {
			   enabled: false
		}
		});
	});
	<?php } ?>
</script>
<?php if($mode == 2) { ?>
<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-16332683-12']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
<?php } ?>
</head>
<?php } //end if?>
<body>
<div id="chart_div" style="width:<?php echo $width;?>px; height:<?php echo $height;?>px;<?php echo($printmode == 1 ? 'margin: 0 auto;' : '');?>"><?php echo $div_content;?></div>
</body>
<?php
if (($mode < 3) & isset($timelapse)) {
  $end_time = microtime();
  $stime = explode(" ",$start_time);
  $start_time = $stime[1] + $stime[0];

  $etime = explode(" ",$end_time);
  $end_time = $etime[1] + $etime[0];
  $total_time = $end_time - $start_time;
  echo "<!-- html generated in $total_time seconds -->\n";
}
?>
</html>
