EOFC2.php 34.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
<?php

/*
 * The Open Flash Chart 2 Extension is free software. It is released under the terms of the following BSD License.
 * 
 * Copyright © 2009 by Sergei Kuznecov <kuznecov.sg@gmail.com>, SummerCode.ru
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 * 
 *    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer
 *      in the documentation and/or other materials provided with the distribution.
 *    * Neither the name of SummerCode.ru nor the names of its contributors may be used to endorse or promote products derived from
 *      this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENTSHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
 */
 
 /*
  * English Disclaimer:
  * 
  * Open Flash Chart 2 Extension is an Yii framework extension for easy making cool viewing charts on interface of an Yii application
  * 
  * Additional information you could take from
  * http://summercode.ru/blog/10
  * 
  */
 
/*
 * Copyright © 2009 by Сергей Кузнецов <kuznecov.sg@gmail.com>, SummerCode.ru
 * Разрешается повторное распространение и использование как в виде исходного кода, так и в
 * двоичной форме, с изменениями или без, при соблюдении следующих условий:
 * 
 *    * При повторном распространении исходного кода должно оставаться указанное выше
 *      уведомление об авторском праве, этот список условий и последующий отказ от гарантий.
 *    * При повторном распространении двоичного кода должна сохраняться указанная выше
 *      информация об авторском праве, этот список условий и последующий отказ от гарантий в
 *      документации и/или в других материалах, поставляемых при распространении. 
 *    * Ни название SummerCode.ru, ни имена ее сотрудников не могут быть использованы в
 *      качестве поддержки или продвижения продуктов, основанных на этом ПО без
 *      предварительного письменного разрешения. 
 *      
 * ЭТА ПРОГРАММА ПРЕДОСТАВЛЕНА ВЛАДЕЛЬЦАМИ АВТОРСКИХ ПРАВ И/ИЛИ ДРУГИМИ СТОРОНАМИ
 * "КАК ОНА ЕСТЬ" БЕЗ КАКОГО-ЛИБО ВИДА ГАРАНТИЙ, ВЫРАЖЕННЫХ ЯВНО ИЛИ ПОДРАЗУМЕВАЕМЫХ,
 * ВКЛЮЧАЯ, НО НЕ ОГРАНИЧИВАЯСЬ ИМИ, ПОДРАЗУМЕВАЕМЫЕ ГАРАНТИИ КОММЕРЧЕСКОЙ ЦЕННОСТИ И
 * ПРИГОДНОСТИ ДЛЯ КОНКРЕТНОЙ ЦЕЛИ. НИ В КОЕМ СЛУЧАЕ, ЕСЛИ НЕ ТРЕБУЕТСЯ СООТВЕТСТВУЮЩИМ
 * ЗАКОНОМ, ИЛИ НЕ УСТАНОВЛЕНО В УСТНОЙ ФОРМЕ, НИ ОДИН ВЛАДЕЛЕЦ АВТОРСКИХ ПРАВ И НИ ОДНО
 * ДРУГОЕ ЛИЦО, КОТОРОЕ МОЖЕТ ИЗМЕНЯТЬ И/ИЛИ ПОВТОРНО РАСПРОСТРАНЯТЬ ПРОГРАММУ, КАК БЫЛО
 * СКАЗАНО ВЫШЕ, НЕ НЕСЁТ ОТВЕТСТВЕННОСТИ, ВКЛЮЧАЯ ЛЮБЫЕ ОБЩИЕ, СЛУЧАЙНЫЕ,
 * СПЕЦИАЛЬНЫЕ ИЛИ ПОСЛЕДОВАВШИЕ УБЫТКИ, ВСЛЕДСТВИЕ ИСПОЛЬЗОВАНИЯ ИЛИ НЕВОЗМОЖНОСТИ
 * ИСПОЛЬЗОВАНИЯ ПРОГРАММЫ (ВКЛЮЧАЯ, НО НЕ ОГРАНИЧИВАЯСЬ ПОТЕРЕЙ ДАННЫХ, ИЛИ ДАННЫМИ,
 * СТАВШИМИ НЕПРАВИЛЬНЫМИ, ИЛИ ПОТЕРЯМИ ПРИНЕСЕННЫМИ ИЗ-ЗА ВАС ИЛИ ТРЕТЬИХ ЛИЦ, ИЛИ ОТКАЗОМ
 * ПРОГРАММЫ РАБОТАТЬ СОВМЕСТНО С ДРУГИМИ ПРОГРАММАМИ), ДАЖЕ ЕСЛИ ТАКОЙ ВЛАДЕЛЕЦ ИЛИ
 * ДРУГОЕ ЛИЦО БЫЛИ ИЗВЕЩЕНЫ О ВОЗМОЖНОСТИ ТАКИХ УБЫТКОВ.
 * 
 */
 
 /*
 * Russian Disclaimer:
 * 
 * Open Flash Chart 2 Extension
 * 
 * Расширение для Yii которое позволяет просто (небольшим количеством кода) создавать красивые флеш-графики на страницах приложения.
 * 
 * Детальная информация может найдена по адресу: http://summercode.ru/blog/10
 * 
 */

require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'Set.php');
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'String.php');
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'vendor/open-flash-chart.php');

/**
 * Open Flash Chart 2 Extension
 * (based on CakePHP OFC2 helper)
 * 
 * Author: Sergei Kuznecov <kuznecov.sg@gmail.com>
 * 
 */
class EOFC2 extends CComponent
{
	protected $baseUrl = '';
	protected $clientScript = null;
	
	private $chartId = null;
	
	/**
	 * The Vendor OpenFlashChart object.
	 *
	 * @var object
	 */
	public $Chart = null;
	
	/**
	 * The number data to be used to generate the charts.
	 *
	 * @var array
	 */
	public $data = array();
	
	/**
	 * Add JAVASCRIPT CODE to this variable to define the ofc_ready function
	 * that is an auto callback in the OFC vendor. Function is called
	 * when the flash is ready.
	 *
	 * @example $this->Chart->ready = 'alert('ready');';
	 * @var string
	 */
	public $ready = '';
	
	/**
	 * Add JAVASCRIPT CODE to this variable to define the open_flash_chart_data
	 * function that is auto callback in the OFC vendor. Function is called
	 * when the data is beeing loaded.
	 *
	 * @example 'alert('loading');'
	 * @var string
	 */
	public $loading = '';
	
	private $stackColours = array();

	// Default background color
	private $bg_colour = '#ffffff';
	// Default grid color
	private $grid_colour = '#cccccc';
	// Default title style
	private $title_style = '{color:#ee0000;font-size:40px;text-align:left;padding:0 0 15px 30px;}';
	// Default legend style
	private $legend_style = '{font-size:20px;color:#778877}';
	// Tooltip template is stored here at runtime
	private $tooltip = null;
	// Labels path (As per Set::extract) is stored here at runtime
	private $labelsPath = false;
	// Numbers path (Set::extract) is stored here at runtime
	private $numbersPath = null;
	// Default settings, also default parameters for the FlashChart::begin() method
	private $settings = array('width' => 300, 'height' => 200);
	// Default axis ranges
	private $defaultRange = array('x' => array(0, 100, 1), 'y' => array(0, 100, 1));
	// Default scatter chart options
	private $scatter_options = array(
			'x_key' => 'x',
			'y_key' => 'y',
			'colour' => '#aacc99',
			'size' => 3);
	// container for Spoke Labels, null = not used
	private $spoke_labels = null;
	// Default Radar axis
	private $radarAxis = array(
		'max' => 5,
		'steps' => 1,
		'colour' => '#aa2222',
		'grid_colour' => '#cccccc',
		'label_colour' => '#777777'
	);
	
	/**
	 * Publishing assets directory with swf object and js scripts
	 */
	public function publishAssets()
	{
		$dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'assets';
		$this->baseUrl = Yii::app()->getAssetManager()->publish($dir);
	}
	
	/**
	 * Register js scripts in the head of document
	 */
	public function registerClientScripts()
	{
		if ($this->baseUrl === '')
			throw new CException(Yii::t('EOFC2', 'baseUrl must be set. This is done automatically by calling publishAssets()'));
		
		$this->clientScript = Yii::app()->getClientScript();
		
		$this->clientScript->registerScriptFile($this->baseUrl.'/json/json2.js');
		$this->clientScript->registerScriptFile($this->baseUrl.'/swfobject.js');
	}
	
	/**
	 * Initialize the helper and includes the js libraries needed.
	 * Call only once.
	 *
	 * @param array $options valid options are 'prototype'
	 * @example $flashChart->begin();
	 * @example $flashChart->begin(array('prototype'=>true));
	 * @return string Javascript library includes
	 */
	public function begin($options = array())
	{
		$this->Chart   = new open_flash_chart();
		$this->chartId = md5(rand(1, time()));
	}
	
	/**
	 * returns the data array in a json array way.
	 *
	 * @return string
	 */
	public function renderData($type = 'bar', $options = array(), $datasetName = 'default', $chartId = null)
	{
		$options = preg_replace('/\s+/', ' ', $options);
		echo $this->chart($type, $options, $datasetName, $chartId);
	}
	
	/**
	 * Outputs the embeded flash, rendering the charts.
	 * For multiple independent charts around your page, call this multiple times,
	 * using different $chartId
	 *
	 * @param int $width pixel with of flash chart
	 * @param int $height pixel height of flash chart
	 * @param string $chartId name of chart for when using multiple seperate charts
	 * @param string $domId if you wish to target a dom id instead of rendering directly
	 * @return string flashHelper flash embed output
	 */
	public function render($width = null, $height = null, $chartId = null, $domId = false)
	{
		if (!is_null($chartId)) {
			$this->chartId = $chartId;
		}
		
		$this->publishAssets();
		$this->registerClientScripts();
		
		if (!is_null($width)) {
			$this->settings['width'] = $width;
		}
		if (!is_null($height)) {
			$this->settings['height'] = $height;
		}
		
		echo '<script type="text/javascript">/*<![CDATA[*/swfobject.embedSWF("', $this->baseUrl, '/open-flash-chart.swf","chart_', $this->chartId, '","', $this->settings['width'], '","', $this->settings['height'], '","9.0.0","",{"get-data":"get_data_', $this->chartId, '"});/*]]>*/</script><div id="chart_', $this->chartId, '"></div>';
	}
	
	/**
	 * Private method used by the helper to extract the data from the array based on
	 * the numbersPath and cast them to Integer if they are string (as they often are
	 * coming from a cake model.
	 *
	 * @access private
	 * @param string $datasetName The name to be used to associate charts with data
	 * @return array
	 */
	private function getNumbers($datasetName = 'default')
	{
		if ($this->numbersPath[$datasetName] != '{n}')
		{
			$numbers = Set::extract($this->data[$datasetName], $this->numbersPath[$datasetName]);
		}
		else
		{
			$numbers = $this->data[$datasetName];
		}
		
		foreach ($numbers as $key => $value)
		{
			if (is_numeric($value))
			{
				$numbers[$key] = $value + 0;
			}
		}
		return $numbers;
	}
	
	/**
	 * Returns the data array in a json array way.
	 *
	 * @access private
	 * @return string
	 */
	private function data($chartId = null)
	{
		if (!is_null($chartId))
		{
			$this->chartId = $chartId;
		}
		
		return
		'<script type="text/javascript">/*<![CDATA[*/var data_'.$this->chartId.' = ' . $this->Chart->toString() . '; function get_data_' . $this->chartId . '() { return JSON.stringify(data_' . $this->chartId . '); }/*]]>*/</script>';
	}
	
	/**
	 * Add a dataset to be rendered by the helper.  
	 * Always call this method at least once, and you must call it after begin() and 
	 * before axis(), or else you may get errors. This tells the helper what data 
	 * to generate graphs from. You can call it multiple times to put in multiple
	 * datasets. You must call the render method in the same order you set the data.
	 * You can optionally set the extract paths (see cake documentation for 
	 * Set::extract() ) directly with this method or use the specific methods (
	 * setNumbersPath() and setLabelsPath() ).
	 * 
	 * The data can be in any format you want, using the paths to tell the helper
	 * how to find your data. If you give no path, neither here, nor with the above
	 * mentioned methods, it expects the data array to be array(12,32,15,23).
	 *    
	 * @example $flashChart->setData(array(1,5,23,35));
	 * @example $flashChart->setData($users,'/User/age','/User/name');
	 * @example $flashChart->setData($data,'{n}.Event.grade','{n}.Girl.name', 'Girls');
	 * @param array $data
	 * @param string $numbersPath
	 * @param string $labelsPath (if string, this dataset will overwrite any previous label path.)
	 * @param string $datasetName The name to be used to associate charts with data
	 * @param string $chartId Name of chart. Use for seperate charts.
	 */	
	public function setData($data, $numbersPath = '{n}', $labelsPath = false, $datasetName = 'default')
	{
		$this->data[$datasetName] = $data;
		if (is_string($numbersPath))
		{
			$this->numbersPath[$datasetName] = $numbersPath;
		}
		if (is_string($labelsPath))
		{
			if (substr($labelsPath,0,1) == '/')
			{
				$labelsPath = '/'.$datasetName.$labelsPath;
			}
			else
			{
				$labelsPath = $datasetName.'.'.$labelsPath;				
			}
			$this->labelsPath = $labelsPath;
		}
	}
	
	/**
	 * Renders the javascript with data and customization for one graph chart. To be called last, but 
	 * may be called multiple times with different datasetNames for different datasets or different
	 * type (and options) for different display of the same data in the same chart.
	 * What options are valid vary from chart type to chart type, and the helper is set up in such 
	 * a way as to pass the options on to the vendor, therefore letting you use an updated vendor 
	 * without changes to the helper. This also means that the helper doesnt know (or care) what 
	 * options you send, but if they do not exist in the vendor, you will throw an error.
	 * 
	 *   For options documentation see;
	 *   http://teethgrinder.co.uk/open-flash-chart-2/
	 *  
	 * @example echo $flashChart->chart();
	 * @example echo $flashChart->chart('bar_3d', array('colour'=>'#aa55AA'));
	 * @example echo $flashChart->chart('line',array('colour'=>'green'),'Apples');
	 * @param string $type Valid types - see doc in top
	 * @param array $options varies depending on type. See vendor documentation
	 * @param string $datasetName The name to be used to associate charts with data
	 * @param string $chartId Name of chart. Use for seperate charts.
	 * @return string
	 */
	private function chart($type = 'bar', $options = array(), $datasetName = 'default', $chartId = null)
	{
		if (!is_null($chartId))
		{
			$this->chartId = $chartId;
		}
		
		switch ($type)
		{
			case 'pie':
				return $this->pie($options, $datasetName, $this->chartId);
				break;
			case 'sketch':
				return $this->sketch($options, $datasetName, $this->chartId);
				break;
			case 'scatter':
				return $this->scatter($options, $datasetName, $this->chartId);
				break;
			case 'scatter_line':
				$options['type'] = $type;
				return $this->scatter($options, $datasetName, $this->chartId);
				break;
			case 'bar_stack':
				return $this->barStack($options, $datasetName, $this->chartId);
				break;
			case 'radar':
				return $this->radar($options, $datasetName, $this->chartId);
				break;
			case 'radar_filled':
				$options['type'] = 'filled';
				return $this->radar($options, $datasetName, $this->chartId);
				break;
			case 'line':
			case 'line_dot':
			case 'line_hollow':
			case 'bar':
			case 'bar_filled':
			case 'bar_glass':
			case 'bar_3d':
			case 'area_line':
			case 'area_hollow':
				if (empty($this->data[$datasetName]))
				{
					return false;
				}
				$this->Chart->set_bg_colour($this->bg_colour);
				$element = new $type();
				foreach ($options as $key => $setting)
				{
					switch ($key)
					{
						case 'line_style':
							$line_style = new line_style($setting[0],$setting[1]);
							$element->line_style($line_style);
							break;
						default:
							$set_method = 'set_' . $key;
							if (is_array($setting))
							{
								$element->$set_method($setting[0], $setting[1]);
							}
							else
							{
								$element->$set_method($setting);
							}
							break;
					}
				}
				if (!empty($this->tooltip))
				{
					$element->set_tooltip($this->tooltip);
				}
				$numbers = $this->getNumbers($datasetName);
				$element->set_values($numbers);
				$this->Chart->add_element($element);
				return $this->data($this->chartId);
				break;
			default:
				return false;
		}
	}
	
	/**
	 * Alias for FlashChart::chart('bar_stack');
	 *
	 * @param array $options
	 * @param string $datasetName The name to be used to associate charts with data
	 * @param string $chartId Name of chart. Use for seperate charts.
	 * @return string
	 */
	public function barStack($options = array(), $datasetName = 'default', $chartId = null) {
		if (!is_null($chartId))
		{
			$this->chartId = $chartId;
		}
				
		if (empty($this->data[$datasetName]))
		{
			return false;
		}
		
		$bar_stack = new bar_stack();
		$numbers = $this->getNumbers($datasetName);
		
		foreach ($numbers as $values)
		{
			$tmp = array();
			if (sizeof($this->stackColours) == sizeof($values))
			{
				foreach ($values as $key => $value)
				{
					$tmp[] = new bar_stack_value($value, $this->stackColours[$key]);
				}
			}
			else
			{
				$tmp = $values;
			}
			$bar_stack->append_stack($tmp);
		}
		
		if (!empty($this->tooltip))
		{
			$bar_stack->set_tooltip($this->tooltip);
		}
		foreach ($options as $key => $setting)
		{
			$set_method = 'set_' . $key;
			if (is_array($setting))
			{
				$bar_stack->$set_method($setting[0], $setting[1]);
			}
			else
			{
				$bar_stack->$set_method($setting);
			}
		}		
		
		$this->Chart->set_bg_colour($this->bg_colour);
		$this->Chart->add_element($bar_stack);
		
		return $this->data($this->chartId);
	}
	
	/**
	 * Alias for FlashChart::chart('scatter'), this method renders only
	 * the scatter chart type
	 *
	 * Online documentation :
	 * http://teethgrinder.co.uk/open-flash-chart-2/scatter-chart.php
	 * 
	 * @param array $options
	 * 		valid option keys : colour, size, x_key, y_key
	 * @param string $datasetName The name to be used to associate charts with data
	 * @param string $chartId Name of chart. Use for seperate charts.
	 * @return string
	 */
	public function scatter($options = array(), $datasetName = 'default', $chartId = null)
	{
		if (!is_null($chartId))
		{
			$this->chartId = $chartId;
		}
		
		if (empty($this->data[$datasetName]))
		{
			return false;
		}
		
		$options = am($this->scatter_options, $options);
		if (isset($options['type']) && $options['type'] == 'scatter_line')
		{
			$scatter = new scatter_line($options['colour'], $options['size']);
		}
		else
		{
			$scatter = new scatter($options['colour'], $options['size']);
		}
		$values = array();
		foreach ($this->data[$datasetName] as $row)
		{
			$values[] = new scatter_value($row[$options['x_key']], $row[$options['y_key']]);
		}
		if (!empty($this->tooltip))
		{
			$element->set_tooltip($this->tooltip);
		}
		$scatter->set_values($values);
		$this->Chart->add_element($scatter);
		$this->Chart->set_bg_colour($this->bg_colour);
		return $this->data($this->chartId);	
	}
	
	/**
	 * Alias for FlashChart::chart('radar'); 
	 *
	 * The Radar chart needs special axis and also
	 * have special methods for stokes and labes
	 * 
	 * @todo Each value can have it's own tooltip using the dot_value class
	 *
	 * @example echo $flashChart->radar(array('loop'=>false','colour'=>'336699'));
	 * @example echo $flashChart->radar(array('type'=>filled'),'Dataset2');
	 * @param array $options
	 * @param string $datasetName The name to be used to associate charts with data
	 * @param string $chartId Name of chart. Use for seperate charts.
	 * @return string
	 */
	public function radar($options = array(), $datasetName = 'default', $chartId = null)
	{
		if (!is_null($chartId))
		{
			$this->chartId = $chartId;
		}
		
		if (empty($this->data[$datasetName])) {
			return false;
		}	
		$this->Chart->set_bg_colour($this->bg_colour);
		
		if (isset($options['type']) && $options['type'] == 'filled') {
			$line = new area_hollow();
			
		} else {
			$line = new line_hollow();
			if (!isset($options['loop']) || (isset($options['loop']) && $options['loop'])) {
				$line->loop();
			}
			if (isset($options['loop'])) {
				unset($options['loop']);
			}
			
		
		}
		
		$values = $this->getNumbers($datasetName);
		/* @todo code below is not getting expected result
		if (isset($options['tooltip_path'])) {
			$numbers = $values;
			$values = array();
			$tooltips = Set::extract($xpath,$this->data[$datasetName]);
			if (isset($options['tooltip_colour'])) {
				$colour = $options['tooltip_colour'];
				unset($options['tooltip_colour']);	
			} else {
				$colour = $this->grid_colour;
			}
			foreach ($numbers as $key => $number) {
				$tmp = new dot_value( $number, $colour );
		    	$tmp->set_tooltip($tooltips[$key]);
		    	$values[] = $tmp;
			}			
			unset($options['tooltip_path']);	
		}*/
		
		if (isset($options['type'])) {
			unset($options['type']);	
		}
		foreach ($options as $key => $setting) {
			$set_method = 'set_' . $key;
			if (is_array($setting)) {
				$line->$set_method($setting[0], $setting[1]);
			} else {
				$line->$set_method($setting);
			}			
		}		
		$radar_axis_object = new radar_axis($this->radarAxis['max']);
		$radar_axis_object->set_steps($this->radarAxis['steps']);
		$radar_axis_object->set_colour($this->radarAxis['colour']);
		$radar_axis_object->set_grid_colour($this->radarAxis['grid_colour']);
		if (!empty($this->radarAxis['labels'])) {
			$labels = new radar_axis_labels($this->radarAxis['labels']);
			$labels->set_colour($this->radarAxis['label_colour']);
			$radar_axis_object->set_labels($labels);
		}		
		if (!is_null($this->spoke_labels)) {
			$radar_axis_object->set_spoke_labels($this->spoke_labels);
		}
		$this->Chart->set_radar_axis($radar_axis_object);	
		
		$line->set_values($values);		
		$this->Chart->add_element($line);
		return $this->data($chartId);
	}
	
	/**
	 * This is an alias for FlashChart::chart('bar_scetch',$options);
	 *
	 * Unfortunatly the Sketch class takes in is options as constructor
	 * values instead of using the set methods like the other classes. 
	 * 
	 * @param array $options
	 * 		valid option keys : colour, outline_colour, fun_factor
	 * @param string $datasetName The name to be used to associate charts with data
	 * @param string $chartId Name of chart. Use for seperate charts.
	 * @return string
	 */
	public function sketch($options = array(), $datasetName = 'default', $chartId = null)
	{
		if (!is_null($chartId))
		{
			$this->chartId = $chartId;
		}
		
		if (empty($this->data[$datasetName])) {
			return false;
		}
		$this->Chart->set_bg_colour($this->bg_colour);
		$element = new bar_sketch($options['colour'], $options['outline_colour'], $options['fun_factor']);
		if (!empty($this->tooltip)) {
			$element->set_tooltip($this->tooltip);
		}
		$numbers = $this->getNumbers($datasetName);
		$element->set_values($numbers);
		$this->Chart->add_element($element);
		return $this->data($this->chartId);
	}
	
	/**
	 * This is an alias to FlashChart::chart('pie') that is only used for the 
	 * pie type.
	 *
	 * For options documentation; 
	 * http://teethgrinder.co.uk/open-flash-chart-2/pie-chart.php
	 * 
	 * @example echo $flashChart->renderPie();
	 * @example echo $flashChart->renderPie(array('animate'=>false);
	 * @param array $options
	 * 		Valid options : values, animate, start_angle, tooltip
	 * @param string $datasetName The name to be used to associate charts with data
	 * @param string $chartId Name of chart. Use for seperate charts.
	 * @return string
	 */
	public function pie($options = array(), $datasetName = 'default', $chartId = null)
	{
		if (!is_null($chartId))
		{
			$this->chartId = $chartId;
		}
		
		if (empty($this->data[$datasetName])) {
			return false;
		}
		$this->Chart->set_bg_colour($this->bg_colour);
		$pie = new Pie();
		foreach ($options as $key => $setting) {
			$set_method = 'set_' . $key;
			$pie->$set_method($setting);
		}
		if (!empty($this->tooltip)) {
			$pie->set_tooltip($this->tooltip);
		}
		$pies = array();
		$labels = Set::extract($this->data, $this->labelsPath);
		$numbers = $this->getNumbers($datasetName);
		foreach ($numbers as $key => $value) {
			if (isset($labels[$key]) && is_string($labels[$key])) {
				$pies[] = new pie_value($value, $labels[$key]);
			} else {
				$pies[] = $value;
			}
		}
		$pie->set_values($pies);
		$this->Chart->add_element($pie);
		return $this->data($this->chartId);
	}
	
	/**
	 * Sets the tool tip for the chart by using a string with replaceable
	 * codewords like #val#. Check OFC2 for documentation. Also you can style
	 * the tooltips look and behavior using the options parameter.
	 * 
	 * Documentation:
	 * http://teethgrinder.co.uk/open-flash-chart-2/tooltip-menu.php
	 * 
	 * @example $flashChart->setToolTip('#val#%');
	 * @param string $tooltip
	 * @param array $options see OFC2 doc for valid options
	 */
	public function setToolTip($tooltip = '', $options = array())
	{
		if (is_string($tooltip))
			$this->tooltip = $tooltip;
		if (!empty($options))
		{
			$tool_tip_object = new tooltip();
			foreach ($options as $key => $setting)
			{
				$set_method = 'set_' . $key;
				$tool_tip_object->$set_method($setting);
			}
			$this->Chart->set_tooltip($tool_tip_object);
		}
	}
	
	/**
	 * Sets the title above the chart. You can also style it with
	 * css as the second parameter.
	 *
	 * @example $flashChart->setTitle('Awesomeness');
	 * @example $flashChart->setTitle('Coolness, by date','{font-size:26px;}');
	 * @param string $title_text
	 * @param string $style css
	 */
	public function setTitle($title_text, $style = '')
	{
		$title = new title($title_text);
		if (empty($style))
		{
			$style = $this->title_style;
		}
		$title->set_style($style);
		$this->Chart->set_title($title);
	}
	
	/**
	 * Set the descriptive texts next to the axies to describe their meaning.
	 * You can also style it directly here using CSS.
	 *
	 * @example $flashChart->setLegend('x','Time of day');
	 * @example $flashChart->setLegend('y','Coolness factor','{font-size:10px;color:#FF0000;}');
	 * @param string $axis 'x' or 'y'
	 * @param string $title
	 * @param string $style css
	 */
	public function setLegend($axis, $title, $style = '')
	{
		$legend_object_name = $axis . '_legend';
		$legend_set_method = 'set_' . $axis . '_legend';
		$legend_object = new $legend_object_name($title);
		if (empty($style))
		{
			$style = $this->legend_style;
		}
		$legend_object->set_style($style);
		$this->Chart->$legend_set_method($legend_object);
	}
	
	/** 
	 * Use this method to set up the axis' range and labels. There are also a number
	 * of options (mostly styling) that can be set up. The two axis have different 
	 * options, but a full documentation can be found on the links given under.
	 * Importantly though, the y has a range option that takes an array with 3 values
	 * (minimum value, max value and step size). On the x axis you will often want
	 * to use the labels from the dataset and the helper will add those labels if
	 * you have defined a proper labels path, either as the third parameter of 
	 * setDate() or using the setLabelsPat() method. Note, that even if you require
	 * no options for the x-axis, you will have to call this method on that axis
	 * for it to use those labels.
	 *
	 * See documentation for options ;
	 * http://teethgrinder.co.uk/open-flash-chart-2/x-axis.php
	 * http://teethgrinder.co.uk/open-flash-chart-2/y-axis.php
	 * 
	 * @example $flashChart->axis('x'); //Sets labels from dataset
	 * @example $flashChart->axis('x',array('labels'=>array('Things','To','Do')),array('colour'=>'#aaFF33', 'vertical'=>true)); 
	 * @example $flashChart->axis('y', array('range'=>array(0,50,5), 'tick_length'=>15);
	 * @param string $axis 'x' or 'y'
	 * @param array $options
	 * @param array $labelsOptions used to customize x axis labels
	 */
	public function axis($axis, $options = array(), $labelsOptions = array())
	{
		$axis_object_name = $axis . '_axis';
		$axis_set_method = 'set_' . $axis . '_axis';
		$axis_object = new $axis_object_name();
		
		foreach ($options as $key => $setting)
		{
			// special options set direcly bellow
			if (in_array($key, array('labels', 'range')))
				continue;
			$set_method = 'set_' . $key;
			if (is_array($setting))
			{
				switch ($key)
				{
					case 'colours':
						$axis_object->set_colours($setting[0], $setting[1]);
						break;
					default:
						$axis_object->$set_method($setting);
				}
			}
			else
			{
				$axis_object->$set_method($setting);
			}
		}
		// that wich must always be set :
		if (!isset($options['colour']))
		{
			$axis_object->set_colour($this->grid_colour);
		}
		if (!isset($options['grid_colour']))
		{
			$axis_object->set_grid_colour($this->grid_colour);
		}
		
		if (isset($options['range']))
		{
			if (isset($options['range'][0]))
			{
				$min = $options['range'][0]; 
			}
			else
			{
				$min = $this->defaultRange[$axis][0];
			}
			if (isset($options['range'][1]))
			{
				$max = $options['range'][1]; 
			}
			else
			{
				$max = $this->defaultRange[$axis][1];
			}
			if (isset($options['range'][2]))
			{
				$step = $options['range'][2]; 
			}
			else
			{
				$step = $this->defaultRange[$axis][2];
			}
			
			if ($axis == 'y')
			{
				$axis_object->set_range($min, $max, $step);
			}
			else
			{ // $axis == 'x'
				$axis_object->set_range($min, $max);
				$axis_object->set_steps($step);
			}			
		}
		else
		{
			if ($axis == 'y')
			{
				$axis_object->set_range($this->defaultRange[$axis][0], $this->defaultRange[$axis][1], $this->defaultRange[$axis][2]);
			}
		} 
		if ($axis == 'x' && is_string($this->labelsPath) && !empty($this->labelsPath) )
		{
            if (sizeof($labelsOptions) > 0)
			{
                $labels = Set::extract($this->data, $this->labelsPath);
                $x_axis_label = new x_axis_labels;        
                foreach ($labelsOptions as $key => $setting)
				{
                    $set_method = 'set_' . $key;
                    $x_axis_label->$set_method($setting);      
                }    
                $x_axis_label->set_labels($labels); 
                $axis_object->set_labels($x_axis_label);
            }
			else
			{
                $labels = Set::extract($this->data, $this->labelsPath);
                $axis_object->set_labels_from_array($labels);
			}
		}
		elseif (isset($options['labels']) && is_array($options['labels']) && $axis == 'x')
		{
            if (isset($labelsOptions['vertical']) && $labelsOptions['vertical'] == true)
			{
                $x_axis_label = new x_axis_labels;           
                $x_axis_label->set_vertical();          
                $x_axis_label->set_labels($options['labels']); 
                $axis_object->set_labels($x_axis_label);
            }
			else
			{
                $axis_object->set_labels_from_array($options['labels']);
            }			
		}
		elseif (isset($options['labels']))
		{
			$axis_object->set_labels($options['labels']);
		}		
		$this->Chart->$axis_set_method($axis_object);
	}
	
	/**
	 * When using multiple charts in one diagram, it may be useful to have a second
	 * y-axis for different values. At the moment this feature is not perfectly 
	 * implemented in the vendor, among other problems, all charts will use the left
	 * y-axis' range for displaying their values.
	 * 
	 * The options it takes in is documented here;
	 * http://teethgrinder.co.uk/open-flash-chart-2/y-axis-right.php
	 *
	 * @param array $options
	 */
	public function rightAxis($options = array())
	{
		$y = new y_axis_right();
		if (!empty($options)) {
			foreach ($options as $key => $setting)
			{
				$set = 'set_' . $key;
				if (is_array($setting) && sizeof($setting) == 2)
				{
					$y->$set($setting[0], $setting[1]);
				}
				else
				{
					$y->$set($setting);
				}
			}
		}
		$this->Chart->set_y_axis_right($y);
	}
			
	/**
	 * Radar charts are circular and this method sets the grid options, more
	 * than an axis really. The options it takes in define the "height" and
	 * steps of the grid and its colour. You can also set the labels for the 
	 * y axis (or what you can think of as the radius).
	 *
	 * @param array $options
	 * 		valid option keys : max, steps, colour, grid_colour, label_colour
	 * @param array $labels
	 * @return string
	 */
	public function setRadarAxis($options = array(), $labels = array())
	{
		$this->radarAxis  = am($this->radarAxis, $options);
		if (!empty($labels))
		{
			$this->radarAxis['labels'] = $labels;
		}
		return  $this->radarAxis;
	}

	/**
	 * Spokes are the labels that name the "radius"-axis of the chart
	 *
	 * @example $flashChart->setRadarSpokes(array('weight','height','strength'));
	 * @example $flashChart->setRadarSpokes(array('red','green','blue'),'#AA3377');
	 * @param array $spokes
	 * @param string $colour
	 */
	public function setRadarSpokes($spokes, $colour = null)
	{
		if (!$colour)
		{
			$colour = $this->defaultSpokeColour;
		}		
		$this->spoke_labels = new radar_spoke_labels( $spokes  );		
		$this->spoke_labels->set_colour( $colour );		
	}
	
	/**
	 * Tells the helper where to find the numbers to generate the graph with. 
	 * This is the same functionality as the 2nd paramter of the setData() 
	 * method. You do not need to set it both places.
	 *
	 * @param string $path
	 * @param string $datasetName The name to be used to associate charts with data
	 */
	public function setNumbersPath($path, $datasetName = 'default')
	{
		$this->numbersPath[$datasetName] = $path;
	}
	
	/**
	 * Tells the helper where to find the labels for the X axis. 
	 * This is the same functionality as the third paramter of the setData() 
	 * method. You do not need to set it both places.
	 * NB. The path should start with the name of the dataset
	 *
	 * @example $flashChart->setLabelsPath('Default.{n}.User.name');
	 * @param string $path
	 */
	public function setLabelsPath($path)
	{
		$this->labelsPath = $path;
	}
	
	/**
	 * Set the background color for the entire diagram. Optional. Will
	 * use the default stored in FlashChart::bg_colour if not used.
	 *
	 * @param string $colour #AA0000
	 */
	public function setBgColour($colour)
	{
		$this->bg_colour = $colour;
	}
	
	/**
	 * For the chart type Bar_stack this method sets the colours of the bars.
	 *
	 * @param array $colours
	 */
	public function setStackColours($colours = array())
	{
		$this->stackColours = $colours; 
	}
}

/**
 * Merge a group of arrays
 * 
 * @param array First array
 * @param array Second array
 * @param array Third array
 * @param array Etc...
 * @return array All array parameters merged into one
 * @link http://book.cakephp.org/view/696/am
 */
function am()
{
	$r = array();
	$args = func_get_args();
	foreach ($args as $a)
	{
		if (!is_array($a))
		{
			$a = array($a);
		}
		$r = array_merge($r, $a);
	}
	
	return $r;
}