<?php

function PropComparer($a, $b)
{
	if (($a->type == "MEASUREMENT") && ($b->type != "MEASUREMENT"))
		return -1;
	else
	{
		if (($b->type == "MEASUREMENT") && ($a->type != "MEASUREMENT"))
			return 1;	
	}
	
	if ($a->name > $b->name)
		return 1;
	else
	{
		if ($a->name == $b->name)
			return 0;		
	}
	return -1;
}

$allassets = array();
$assetset = array();

if (isset($_REQUEST['points']))
{
	$dashname = "Pinned Values (Live)";	
	unset($_REQUEST['id']);
	$plist = explode(',',$_REQUEST['points']);
	foreach($plist as $pp)
	{
		$bits = explode(':',$pp);
		$assetset[] = $pp[0]+0;
	}
}

if (isset($_REQUEST['id']))
{
	$id = $_REQUEST['id'];
	$assetset[] = $id;
	
	//$ass = new Asset($id);
	$tp = $id;
	if (isset($allassets[$tp]))
		$ass = $allassets[$tp];
	else
	{
		$ass = new Asset($tp);				
		$allassets[$tp] = $ass;
	}	
	
	$dashname = $ass->name;
	
	if (isset($_REQUEST['property']))
	{
		$allprops = Properties::GetAllProperties();
		foreach($allprops as $px)
		{
			if ($px->id == $_REQUEST['property'])
			{
				$human = $px->name;
				$bits = explode(' - ',$px->name);
				if (count($bits) > 1)
				{
					$human = $bits[1].' '.$bits[0];
				}
				$dashname .= ' '.$human;
				break;
			}
		}
	}
	if (isset($_REQUEST['properties']))
	{
		$allprops = Properties::GetAllProperties();
		$myprops = explode(',',$_REQUEST['properties']);
		$anyvs = false;
		foreach($allprops as $px)
		{
			if (in_array($px->id,$myprops))
			{
				$human = $px->name;
				$bits = explode(' - ',$px->name);
				if (count($bits) > 1)
				{
					$human = $bits[1].' '.$bits[0];
				}
				if ($anyvs == false)
					$anyvs = true;
				else
					$dashname .= " vs ";
				$dashname .= ' '.$human;
				break;
			}
		}
	}
	
	if ((!isset($_REQUEST['range'])) || ($_REQUEST['range'] == 'live'))
	{
		$dashname .= ' (Live)';		
	}
	else
	{
		$dashname .= ' (History)';
	}
	
	if (!isset($_REQUEST['regen']))
	{
		$med = $ass->GetMedia();
		foreach($med as $md)
		{
			$name = $md->localpath;
			if ($name == $dashname.".dash")
			{
				$activefolder = $sitefolder.'/media/assets/'.$id.'/'.$md->localpath;
				$structure = file_get_contents($activefolder);
				return;
			}
			if ($name == "default.dash")
			{
				$activefolder = $sitefolder.'/media/assets/'.$id.'/'.$md->localpath;
				$structure = file_get_contents($activefolder);
				return;
			}
		}
	}
	
	if (isset($_REQUEST['navigate']))
	{
		//$structure = '{ "name": "Dashboard Menu", "origin": "/", "panels": [ { "name": "Menu", "style": "dashlist", "points": [],"x": 0, "y": 0, "w": 3,"h": 6 } ] }';
		//return;
	}
	
	$specificasset = $id;
}

$clusternames = array();

if (isset($_REQUEST['origin']))
{
	
	$mode = "generic";
	$id = $_REQUEST['origin'];
	$propset = explode(',',$_REQUEST['propertyid']);
	$rel = $_REQUEST['related'];
	$depth = $_REQUEST['depth'];
	if ($depth == 'X')
		$depth = FALSE;
	
	$toprocess = array();
	$toprocess[] = $id;
	
	$leading = $id;
	
	$counter = 0;
	$processed = array();
	if (isset($_REQUEST['all']))
	{
		while(count($toprocess) > 0)
		{
			//Wander upstream to find the ideal origin point, if available...
			$tp = array_pop($toprocess);
			$leading = $tp;
			if (in_array($tp,$processed)) continue;
			$processed[] = $tp;
						
			if (isset($allassets[$tp]))
				$asx = $allassets[$tp];
			else
			{
				$asx = new Asset($tp);				
				$allassets[$tp] = $asx;
			}
			if(isset($asset[$tp]['relationships'][$rel]))
			{
				foreach($asset[$tp]['relationships'][$rel] as $k)
				{
					if ($k['upstream'] == true)
					{					
						$toprocess[] = $k['target'];
					}
				}
			}
			$counter++;
			if ($depth !== FALSE) 
			{
				if ($counter >= $depth)
				{
					break;
				}
			}
		}
		$toprocess = array();
		$toprocess[] = $leading;
		
		if ($depth !== FALSE) $depth *= 2;
	}
	
	$counter = 0;
	$processed = array();
	$assetset = array();	
	while(count($toprocess) > 0)
	{
		$tp = array_pop($toprocess);
		if (in_array($tp,$processed)) continue;
		$processed[] = $tp;
		
		if (isset($allassets[$tp]))
			$asx = $allassets[$tp];
		else
		{
			$asx = new Asset($tp);				
			$allassets[$tp] = $asx;
		}
		if ($asx->type != 1)
			$assetset[] = $tp;
		if(isset($asset[$tp]['relationships'][$rel]))
		{
			foreach($asset[$tp]['relationships'][$rel] as $k)
			{
				if ($k['upstream'] == false)
				{					
					$toprocess[] = $k['target'];
				}
			}
		}		
		
		$counter++;
		if ($depth !== FALSE) 
		{
			if ($counter >= $depth)
			{
				break;
			}
		}
	}
		
	$tp = $assetset[0];
	//$ass = new Asset($assetset[0]);
	if (isset($allassets[$tp]))
		$ass = $allassets[$tp];
	else
	{
		$ass = new Asset($tp);				
		$allassets[$tp] = $ass;
	}
	
	$allrels = Relationships::GetAllRelationships();
	foreach($allrels as $rx)
	{
		if ($rx->id == $rel)
		{
			$relname = $rx->name;
			break;
		}
	}	
	$dashname = $relname." from ".$ass->name.' (Live)';
}

if (isset($_REQUEST['property']))
{
	$pid = filter_var($_REQUEST['property'],FILTER_VALIDATE_INT);
	if ($pid !== FALSE)
	{
		$propset[] = $pid;
	}	
}

if (isset($_REQUEST['properties']))
{
	$pid = $_REQUEST['properties'];
	if ($pid !== FALSE)
	{
		$props = explode(',',$pid);
		foreach($props as $p)
		{
			$propset[] = $p;
		}		
	}	
}

if (isset($_REQUEST['zoom']))
{
	$zoom = $_REQUEST['zoom'];
	if ($zoom > 0)
	{
		$toprocess = array();
		for($x=0;$x<$zoom;$x++)
		{
			$toprocess[] = array();
		}
		foreach($assetset as $ast)
		{
			$toprocess[0][] = $ast;
		}
		
		for($x=0;$x<$zoom;$x++)
		{
			foreach($toprocess[$x] as $ast)
			{
				$sql = "SELECT childasset FROM assetrelationships WHERE parentasset=".$ast.' AND relationship=2';
				try
				{
					$query = $db->query($sql);	
					
					$values = array();
					$validassets = array();
					while($row = $query->fetch(PDO::FETCH_ASSOC)) 
					{
						if (!in_array($row['childasset'],$assetset))
						{
							$assetset[] = $row['childasset'];
							$toprocess[$x+1][] = $row['childasset'];
						}
					}
				}
				catch(e)
				{
				}
			}
		}
		
		$dashname .= " + Children";
	}
	//print_r($assetset);
	//exit();
}

$overallstyle = "barchart";
$analogstyle = 'barchart';
$discretestyle = 'text';

$clustering = true;
if (isset($_REQUEST['style']))
{
	$overallstyle = $_REQUEST['style'];
	if ($overallstyle != "barchart")
	{
		$clustering = false;
	}
	if ($overallstyle == "gauge")
	{
		$itemwidth = 2;
		$itemheight = 2;
	}
}

$range = FALSE;
if (isset($_REQUEST['range']))
{
	$range = $_REQUEST['range'];
	$analogstyle = 'line';
	$discretestyle = 'discrete';
	$overallstyle = 'line';
}

$sorted = array();
$clusters = array();
$namestyle = "property";

$stripname = "";
$savespaceforlinks = true;

//echo 'Getting Properties...';
if ((isset($_REQUEST['points'])) || (count($assetset) == 1) || ($zoom > 0))
{	
	//$ass = new Asset($assetset[0]);
	if (!isset($_REQUEST['points']))
	{
		//echo 'Loading...';
		$final = array();
		
		foreach($assetset as $tp)
		{				
			if (isset($allassets[$tp]))
				$ass = $allassets[$tp];
			else
			{
				$ass = new Asset($tp);				
				$allassets[$tp] = $ass;
			}
			$props = $ass->GetProperties();	

			$fx = array();	
			foreach($props as $px)
			{
				if (count($propset) > 0)
				{
					if (!in_array($px->id,$propset))
					{
						continue;
					}
				}
				$fx[] = $px;		
			}
			
			$ass->GetValues($fx);
			foreach($fx as $f)
			{
				if ($px->origintype == "template")
				{
					$px->origin = $tp;
				}
				if ($f->altorigin == 0)
					$f->altorigin = $tp;
				$final[] = $f;
			}
			
		}
		/*$tp = $assetset[0];
		if (isset($allassets[$tp]))
			$ass = $allassets[$tp];
		else
		{
			$ass = new Asset($tp);				
			$allassets[$tp] = $ass;
		}
		$props = $ass->GetProperties();	

		$final = array();	
		foreach($props as $px)
		{
			if (count($propset) > 0)
			{
				if (!in_array($px->id,$propset))
				{
					continue;
				}
			}
			$final[] = $px;		
		}
		
		$ass->GetValues($final);*/
	}
	else
	{		
		if (isset($_REQUEST['points']))
		{
			$pointset = explode(',',$_REQUEST['points']);
			foreach($pointset as $ps)
			{
				$bits = explode(':',$ps);
				$bits[1] = 0+$bits[1];
				$ast = 0+$bits[0];
				$ass = new Asset($ast);
				$props = $ass->GetLocalProperties();			
				$ass->GetValues($props);
				foreach($props as $px)
				{
					if ($px->id == $bits[1])
					{
						if ($px->origintype == "template")
						{
							$px->origin = $ast;
						}
						$final[] = $px;
						break;
					}
				}
				$props = array();
			}
		}		
	}
	
	
	$finalfinal = array();
	foreach($final as $ff)
	{
		//print_r($ff->value);
		if (isset($ff->value['_dynamics']))
		{
			$finalfinal[] = $ff;
		}
	}
	
	$final = $finalfinal;
	
	//print_r($final);
	//exit();
	
	$totalchildren = 0;
	if (count($final) == 0)
	{		
		if (isset($asset[$ass->id]['relationships'][2]))
		{
			foreach($asset[$ass->id]['relationships'][2] as $r)
			{
				if ($r['upstream'] == false)
				{		
					$totalchildren++;
					if ($totalchildren > 5)
					{
						$final = [];
						break;
					}
					
					$tp = $r['target'];
					//echo 'Taking a look at '.$tp;
					if (isset($allassets[$tp]))
						$asx = $allassets[$tp];
					else
					{
						$asx = new Asset($tp);				
						$allassets[$tp] = $asx;
					}
					//echo 'Adding Items From '.$asx->name;
					$props = $asx->GetLocalProperties();	
					$asx->GetValues($props);		

					//$final = array();	
					foreach($props as $px)
					{
						if (count($propset) > 0)
						{
							if (!in_array($px->id,$propset))
							{
								continue;
							}
						}
						if ($px->origintype == "template")
						{
							$px->origin = $r['target'];
							$px->origintype = "local";
						}
						//echo 'Adding '.$px->name.' from '.$asx->name.'<br/>';
						$final[] = $px;								
					}
				}
			}						
		}	

		$finalfinal = array();
		foreach($final as $ff)
		{			
			if (isset($ff->value['_dynamics']))
			{
				$finalfinal[] = $ff;
			}
		}
		
		$final = $finalfinal;				
	}
	
	$historylayout = false;
	
	usort($final,"PropComparer");	
	
	//print_r($final);
	
	foreach($final as $px)
	{
		//print_r($propset);
		if (count($propset) > 0)
		{
			$namestyle = "property";
			if (!in_array($px->id,$propset))
			{
				continue;
			}
		}		
		
		$style = "";
		$node = "";
		$value = 0;
		$min = 0;
		$max = 0;
		$units = "";
		$base = explode(' - ',$px->name)[0];	
		
		switch($px->type)
		{
			case 'MEASUREMENT':
				$style = $analogstyle;//'barchart';
				$node = 'measurement';
				$min = $px->value['min'];
				$max = $px->value['max'];
				$units = $px->value['units'];
				break;
			case 'ENUM':
				$style = $discretestyle;
				$node = 'value';
				$min = 0;
				$max = 5;
				$units = '';
				break;
			case 'STATUS':
				$style = $discretestyle;
				$node = 'state';
				$min = 0;
				$max = 5;
				$units = '';
				break;
			case 'LOOKUP':
				$style = $discretestyle;
				$node = 'text';
				$min = 0;
				$max = 5;
				$units = '';
				break;
		}		
		
		//echo '//Panel Style: '.$style."\r\n";
		if ($style == "") continue;
		
		if (!isset($_REQUEST['points']))
		{
			if ($px->origintype == "template") 
			{
				if ($px->altorigin == 0)
					$px->origin = $id;
				else
					$px->origin = $px->altorigin;
			}
		}
		
		$itm = array();		
		$itm['style'] = $style;
		$itm['min'] = $min;
		$itm['max'] = $max;
		$itm['node'] = $node;		
		$itm['units'] = $units;
		$itm['name'] = $px->name;
		$itm['title'] = $px->name;		
		if ($px->origin != $id)
		{
			//echo 'Unexpected Origin: '.$px->origin;
			//$asn = new Asset($px->origin);
			$tp = $px->origin;
			if (isset($allassets[$tp]))
				$asn = $allassets[$tp];
			else
			{
				$asn = new Asset($tp);				
				$allassets[$tp] = $asn;
			}
			$itm['title'] = $asn->name.' - '.$px->name;		
		}
		
		$itm['value'] = $px->value[$node];
		$itm['origin'] = $px->origin;
		//print("Setting Origin: ".$px->origin);
		$itm['propid'] = $px->id;
		
		$title = $ass->name;
		
		if (count($propset) > 0)
		{
			foreach($allprops as $pl)
			{
				if (in_array($pl->id,$propset))
				{
					$bitx = explode(' - ',$pl->name);
					if (count($bitx) == 2)
						$title .= ' '.$bitx[1].' '.$bitx[0];
					else
						$title .= ' '.$pl->name;
				}
			}
		}
		
		$scalerange = floor(sqrt($max - $min));
		
		//$cluster = $base.'_'.$style.'_'.$min.'-'.$max.'_'.$units;
		$cluster = $style.'_'.$base.'_'.$scalerange.'_'.$units;
		if (count($propset) > 0)
		{
			$cluster = $base.'_'.$style;
		}
		
		$clustered = false;
		switch($style)
		{
			case 'discrete':
			case 'line':
			case 'barchart':
				$clustered = $clustering;
				break;
		}
		
		if ($clustered == false)
			$cluster .= '_'.count($clusters);
		
		if (!isset($clusters[$cluster]))
		{
			$clusters[$cluster] = array();
		}
		$clusters[$cluster][] = $itm;
		
		$sorted[$px->name.'_'.$px->type.'_'.$px->name.'_'.$px->origin] = $px;
	}		
	//print_r($clusters);
}
else
{
	
	//Try to find all matching properties across the assets.
	$namestyle = "asset";
	$savespaceforlinks = false;
	
	$alist = implode(',',$assetset);
	$plist = implode(',',$propset);	
	$sql = "SELECT assetid,value FROM assetvalues WHERE propertyid IN (".$plist.") AND assetid IN (".$alist.")";
	$query = $db->query($sql);	
	
	$values = array();
	$validassets = array();
	while($row = $query->fetch(PDO::FETCH_ASSOC)) 
	{
		$validassets[] = $row['assetid'];
		$values[$row['assetid']] = explode('|',$row['value'])[0];
	}
	
	$sql = "SELECT assetid FROM datalinks WHERE propertyid IN (".$plist.") AND assetid IN (".$alist.")";
	$query = $db->query($sql);
	
	while($row = $query->fetch(PDO::FETCH_ASSOC)) 
	{		
		if (!in_array($row['assetid'],$validassets))
			$validassets[] = $row['assetid'];
	}
	
	$historylayout = false;	
	//Sort properties by name and style...
	$itemindex = 0;
	
	$hits = array();
	
	foreach($propset as $pset)
	{
		foreach($allprops as $px)
		{
			if ($pset == $px->id)
			{
				$values = $px->GetDefault();				
				$style = $analogstyle;
				if ($px->type == "MEASUREMENT")
				{
					$min = $values[2];
					$max = $values[3];
					$node = "measurement";
					$units = $values[1];		
					$historylayout = true;					
				}
				else
				{
					$style = $discretestyle;
					$node = "value";
					$units = "";
					$min = 0;
					$max = 9;
				}
				break;
			}
		}
		
		$allassets = array();
		
		$primerels = [];
		
		if (count($validassets) > 0)
		{
			if (!in_array($assetset[0],$validassets)) {
				//OK - let's see if we can find an existing relationship between these assets...						
				$linked = array();
				$touched = array();		
				foreach($validassets as $vl)
				{
					//$asx = new Asset($vl);
					$tp = $vl;
					if (isset($allassets[$tp]))
						$asx = $allassets[$tp];
					else
					{
						$asx = new Asset($tp);				
						$allassets[$tp] = $asx;
					}
					//$allassets[$vl] = $asx;			
				}
				$vl = $validassets[0];
				$rellist = array();
				$topmost = array();
				foreach(array_keys($asset[$vl]['relationships']) as $k)
				{				
					if (($k == 2) || ($k == 3)) continue;
					$rellist[] = $k;
					$linked[] = TRUE;
					$touched[] = array($vl);
					$topmost[] = FALSE;
				}
				
				for($x=1;$x<count($validassets);$x++)
				{			
					for($r=0;$r<count($rellist);$r++)
					{				
						$foundhit = false;
						$rid = $rellist[$r];
						
						//Find Other Assets In Relationship...
						$tch = array();
						$toprocess = array($validassets[$x]);
						$loops = 0;
						while(count($toprocess) > 0)
						{
							$loops++;
							if ($loops > 200) 
							{
								echo 'Infinite Loop!';
								break;
							}
							$tp = array_pop($toprocess);
							if (in_array($tp,$tch)) continue;
							$tch[] = $tp;
							if (!isset($allassets[$tp]))
							{
								$allassets[$tp] = new Asset($tp);
							}
							if (!isset($asset[$tp]['relationships'][$rid])) continue;
							foreach($asset[$tp]['relationships'][$rid] as $rl)
							{						
								if (in_array($rl['target'],$validassets))
								{								
									$foundhit = true;
									//echo 'Hit from '.$tp.' to '.$rl['target'].' on '.$rid;
									if (in_array($tp,$validassets))
									{
										if (!in_array($rid,$primerels))
											$primerels[] = $rid;
									}
									break;
								}
								if ((!in_array($rl['target'],$tch)) && (!in_array($rl['target'],$toprocess)))
								{								
									$toprocess[] = $rl['target'];
								}
							}
							if ($foundhit == true) break;
						}
						
						if ($foundhit == false)
						{
							//Abandon processing of this relationship...
							unset($rellist[$r]);
							$rellist = array_values($rellist);
							$r--;	
							if ($r < 0) $r = 0;
							if (count($rellist) == 0)
							{
								//echo 'Leaving...';
								break;
							}
						}
					}
				}
							
				if (count($rellist) > 0)
				{			
					$rx = $rellist[0];
					foreach($rellist as $r)
					{
						if (in_array($r,$primerels))
						{
							$rx = $r;
							break;
						}
					}
					//print_r($primerels);
					//echo 'All assets share '.$rx.' in common. Re-sorting.';
					$newassetset = array();
					
					//Work upwards...
					$highest = $validassets[0];
					$touched = array();
					$working = array($validassets[0]);
					while(count($working) > 0)
					{					
						$active = array_pop($working);					
						if (in_array($active,$touched)) continue;
						if (in_array($active,$validassets)) $highest = $active;
						$touched[] = $active;
						if (!isset($allassets[$active]))
						{
							$allassets[$active] = new Asset($active);
						}
						foreach($asset[$active]['relationships'][$rx] as $rp)
						{
							if ($rp['upstream'] == false) continue;
							if (!in_array($rp['target'],$touched))
							{
								if (!in_array($rp['target'],$working))
								{
									$working[] = $rp['target'];
								}
							}
						}
					}
					
					//OK, now that we have the highest item, work back down...
					$newassetset = array();
					$touched = array();
					$working = array($highest);
					while(count($working) > 0)
					{					
						$active = array_pop($working);					
						//print("Working Down From ".$active);
						if (in_array($active,$touched)) continue;
						if (in_array($active,$validassets)) 
						{
							$newassetset[] = $active;
						}
						$touched[] = $active;
						if (!isset($allassets[$active]))
						{
							$allassets[$active] = new Asset($active);
						}
						foreach($asset[$active]['relationships'][$rx] as $rp)
						{
							if ($rp['upstream'] == true) continue;
							if (!in_array($rp['target'],$touched))
							{
								if (!in_array($rp['target'],$working))
								{								
									$working[] = $rp['target'];
								}
							}
						}
					}
					
					if (count($validassets) == count($newassetset))
					{
						$assetset = $newassetset;				
					}				
				}
			}
			
			$touched = array();
		
			foreach($assetset as $vl)
			{
				if (!in_array($vl,$validassets)) continue;
				$npiece = explode(' - ',$px->name);
				$base = $npiece[0];
				$humanname = $base;
				if (count($npiece) > 1)
				{
					$humanname = $npiece[1].' '.$npiece[0];
				}
							
				$itemindex++;
				
				$stripname = $px->name;
				
				$itm = array();
				$itm['style'] = $style;
				$itm['min'] = $min;
				$itm['max'] = $max;
				$itm['node'] = $node;		
				$itm['units'] = $units;
				if (!isset($allassets[$vl]))
				{
					$allassets[$vl] = new Asset($vl);
				}
				$asx = $allassets[$vl];		
				$itm['name'] = $asx->name;
				$itm['title'] = $asx->name;			
				
				$itm['value'] = 0;
				if (isset($values[$vl]))
					$itm['value'] = $values[$vl];
				$itm['origin'] = $vl;
				$itm['propid'] = $px->id;					
				
				$finalname = $px->name;
				
				$cluster = $style.'_'.$base.'_'.$min.'-'.$max.'_'.$units;
				if (($clustering == false) || ($style == $discretestyle))
				{
					$finalname = $asx->name.' '.$px->name;
					$base = str_pad($itemindex, 5, '0', STR_PAD_LEFT).$base;
					$cluster = $style.'_'.$base.'_'.$min.'-'.$max.'_'.$units;
					
				}			
				
				//echo $cluster.'<br/>';
				
				if (!isset($clusters[$cluster]))
				{
					$clusters[$cluster] = array();
				}
				$clusters[$cluster][] = $itm;
				
				$clusternames[$cluster] = $finalname;
				
				$sorted[$px->name.'_'.$px->type.'_'.$px->name.'_'.$vl] = $px;
			}
		}
	}
}

ksort($clusters);

$tp = $assetset[0];
if (isset($allassets[$tp]))
	$ass = $allassets[$tp];
else
{
	$ass = new Asset($tp);				
	$allassets[$tp] = $ass;
}
if (!isset($dashtitle))
{
	$title = $ass->name;
}

$showlinks = false;
if (isset($specificasset))
{
	if ((!isset($_REQUEST['range'])) || ($_REQUEST['range'] == 'live'))
	{
		$showlinks = true;
	}
}

$showlinks = false;

$sizes = array();
$rows = 1;
if (count($clusters) == 1)
{
	$x = 0;
	$y = 0;
	if ($showlinks == true)
		$sizes[0] = [0,0,11,6];
	else
		$sizes[0] = [0,0,12,6];
}
else
{
	$indx = 0;
	$x = 0;
	$y = 0;	
	foreach($clusters as $clust)
	{
		$w = 1;
		$h = 3;
		$w = 1 + floor(count($clust)/3);
		switch($clust[0]['style'])
		{
			case 'line':
			case 'discrete':
				$h = 2;
				$w = 12;
				break;
			case 'gauge':
				$w = 3;
				$h = 3;
				break;
			case 'text':
				$w = 3;
				$h = 1;
				break;
		}				
		
		$sizes[$indx] = [$x,$y,$w,$h];		
		$indx++;
		
		if ($h <= 2)
		{
			$y += $h;
			if ($y > (ceil($rows / 2) * 6)-$h)
			{
				$x += $w;
				$y = ($rows-1)*3;
			}			
			if ($x+$w > 12)
			{				
				$x = 0;				
				$rows+=2;
				$y = ($rows-1) * 3;				
			}
		}
		else
		{
			$x+=$w;
			if ($x >= 11)
			{
				$x = 0;
				$y+= $h;
				$rows++;
			}
		}
	}
}

if ($rows == 1)
{
	for($x=0;$x<count($sizes);$x++)
	{
		if ($sizes[$x][3] > 2)
			$sizes[$x][3] = 6;
	}
}

if (isset($dashname))
{
	$title = $dashname;
}

function curPageURL() {
	$pageURL = 'http';
	if(isset($_SERVER["HTTPS"]))
	if ($_SERVER["HTTPS"] == "on") {
		$pageURL .= "s";
	}
	$pageURL .= "://";
	
	$query = parse_url($_SERVER["SERVER_NAME"].$_SERVER['REQUEST_URI']);
	$bits = explode('&',$query['query']);
	$final = "";
	foreach($bits as $bt)
	{
		$pieces = explode('=',$bt);
		if ($pieces[0] == 'range') continue;
		if ($final != "") $final .= "&";
		$final .= $bt;
	}
	
	$final = $query['path'].'?'.$final;
	
	//print($final);
	$pageURL .= $final;
		
	return str_replace("&regen=true","",$pageURL);
}

//print_r($clusters);
//exit();

$structure = '{ "name": "'.$title.'", "origin": "'.curPageURL().'",';
if (isset($specificasset))
{	
	$structure .= '"asset": '.$specificasset.',';
}
$structure .= ' "panels":  [';
$first = true;
$indx = 0;
foreach($clusters as $k => $clusterprops)
{
	$proplist = "";
	
	foreach($clusterprops as $pq)
	{		
		$histheight = 2;
	
		$clusterstyle = "live";
		if ($style == "line")
		{
			$clusterstyle = "history";
		}
		
		$title = "";
		$bits = explode(' - ',$pq['name']);
		if ($clustering == true)
		{
			if ($namestyle == "property")
			{
				$title = $bits[0];
			}
			else
			{
				if (count($bits) > 1)
					$title = $bits[1].' '.$bits[0];
			}
		}
		else
		{
			$title = $pq['name'];
		}
		if (isset($clusternames[$k]))
		{
			$title = $clusternames[$k];
		}
		
		if ($proplist != "")
			$proplist .= ",";		
		$proplist .= '{"asset": '.$pq['origin'].', "property": '.$pq['propid'].'}';
	}
	if ($first == true)
		$first = false;
	else
		$structure .= ",";	
	$structure .= '{"name": "'.$title.'","style": "'.$pq['style'].'",';
	
	if ($savespaceforlinks == true)
		$rightedge = 11;
	else
		$rightedge = 12;
	
	if (isset($sizes[$indx]))
	{
		$hht = ($indx * 2);
		if (count($sizes) == 1)
		{
			$histheight = 6;
		}
		if ($historylayout == true)
		{
			if ($histheight < 6) $histheight = 3;
			//echo 'Forcing History Layout';
			$structure .= '"hx": 0,"hy": '.($indx*3).', "hw": '.$rightedge.', "hh": '.$histheight.','.'"x": 0,"y": '.($indx*3).', "w": '.$rightedge.', "h": '.$histheight.',';
		}
		else
			$structure .= '"x": '.$sizes[$indx][0].',"y": '.$sizes[$indx][1].',"w":'.$sizes[$indx][2].',"h": '.$sizes[$indx][3].',"hx": 0,"hy": '.($indx*2).', "hw": '.$rightedge.', "hh": '.$histheight.',';
	}
	if ($stripname != "")
	{
		$structure .= '"strip": "'.$stripname.'",';
	}
		
	$structure .= '"points": ['.$proplist.'] }';
	$indx+= 1;
}

	if ($showlinks == true)
	{
		if ($first == true)
		{
			$structure .= '{"name": "Navigation","style": "dashlist","points": [],"x": 0, "y": 0, "w": 11,"h": 6,"hx": 0,"hy": 0,"hw": 11,"hh": 1 },';
		}
		else
		{
			$structure .= ',';
		}
		$structure .= '{"name": "Links","style": "links","points": [],"x": 11, "y": 0, "w": 1,"h": 6,"hx": 0,"hy": '.($indx * 2).',"hw": 12,"hh": 1 }';
	}
	$structure .= "] }";
	//echo '<!--'.$structure.'-->';
	//exit;
?>