<?php
function fn_relationship_c($aql)
{
	$data = $aql->Consume(1);
	
	$rels = Relationships::GetAllRelationships();
	
	$propshortlist = array();	
	$bing = array();
	
	//$allprops = Properties::GetAllProperties();
	if ($data[0]->islist == true)
		$propset = $data[0]->value;
	else
		$propset = array($data[0]->value);
	
	$targetscore = count($propset);
	
	$perfect = FALSE;
	
	$any = false;
	foreach($rels as $pr)
	{
		$bing[$pr->id] = 0;
		foreach($propset as $psx)
		{			
			if (strpos(strtolower($pr->name),strtolower($psx)) !== FALSE)
			{	
				$any = true;
				$bing[$pr->id]++;
				if (strtolower($pr->name) == strtolower($psx))
					$perfect = $pr;
			}
		}
	}
	
	$dir = "";	
	
	if ($any == false)
	{
		foreach($rels as $pr)
		{
			$bing[$pr->id] = 0;	
			foreach($propset as $psx)
			{			
				//print_r($pr);
				if (strpos(strtolower($pr->upname),strtolower($psx)) !== FALSE)
				{						
					#echo 'Found '.$pr->upname;
					$any = true;
					$bing[$pr->id]++;
					$dir = "down";
					if (strtolower($pr->upname) == strtolower($psx))
						$perfect = $pr;
				}
				if (strpos(strtolower($pr->downname),strtolower($psx)) !== FALSE)
				{	
					#echo 'Found '.$pr->downname;
					$any = true;
					$bing[$pr->id]++;
					$dir = "up";
					if (strtolower($pr->downname) == strtolower($psx))
						$perfect = $pr;
				}
			}
		}
	}
	
	foreach($bing as $k => $v)
	{
		if ($v == $targetscore)
		{
			$propid = $k;			
			$propshortlist[] = $k;
		}
	}
	
	if ($perfect !== FALSE)
	{
		echo 'Perfect Match!';
		$propshortlist = array($perfect->id);
	}
	
	//print_r($propshortlist);
	
	$a = new AQLStackElement();
	$a->typename = "rellist";
	$a->islist = true;
	$a->value = $propshortlist;
	array_push($aql->stack,$a);
	
	if ($dir != "")
	{
		$a = new AQLStackElement();
		$a->typename = "const";
		$a->islist = false;
		$a->value = $dir;
		array_push($aql->stack,$a);
	}
	
}
