<?xml version="1.0" encoding="utf-8"?>
<!--
////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2003-2006 Adobe Macromedia Software LLC and its licensors.
// All Rights Reserved.
// The following is Sample Code and is subject to all restrictions on such code
// as contained in the End User License Agreement accompanying this product.
// If you have received this file from a source other than Adobe,
// then your use, modification, or distribution of it requires
// the prior written permission of Adobe.
//
////////////////////////////////////////////////////////////////////////////////
-->
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="bizLibrary.sharedComponent.*" creationComplete="init();">
    <mx:Metadata>
        [Event("regionChange")]
    </mx:Metadata>
    
    <mx:Script>

        <![CDATA[
        import mx.events.FlexEvent;
        import mx.controls.dataGridClasses.DataGridColumn;
    	import mx.controls.Button;
    	import mx.controls.Label;
    	import mx.controls.ToolTip;
        import mx.charts.HitData;
        
        private var chartToolTip:String;
        private var gridToolTip:String;
        private var selectedIndex:String;
        
        [Bindable]
        public var itemData:XML;

        [Bindable] 
        private var togToolTip:String = "";
        
        [Bindable]
        private var chartDGToolTip:String = "";

		[Bindable]
        public var pcToolTip:String = "";
        [Bindable]
        public var title:String;
        
        import flash.events.KeyboardEvent;
        import mx.events.DataGridEvent;
        
        private function init():void 
        {
        	if(Accessibility.active)
			{
				this.tabIndex=120;
        		//charts instead of grid is shown first when in accessibility mode
        		toggle.selectedIndex = 1;
        		
				var chartButton:Button = Button(toggle.getChildAt(0));
				var gridButton:Button = Button(toggle.getChildAt(1));

        		gridButton.toolTip = "View regional breakdown in grid" ;
        		chartButton.toolTip = "View regional breakdown in chart";
        		
        		var index:int = toggle.selectedIndex;
        		
        		//sets toolTip for toogle bar depending on which view is selected
				if(index == 0) 
				{ 
					togToolTip = chartButton.toolTip + 
						" is selected. To view in grid " + 
						"hit the right arrow and then space bar."; 
				} 
				else 
				{ 
					togToolTip = gridButton.toolTip + 
						" is selected. To view in chart hit the left arrow and then space bar."; 
				}

				chartButton.addEventListener(FlexEvent.BUTTON_DOWN, toggleUpdate);
				gridButton.addEventListener(FlexEvent.BUTTON_DOWN, toggleUpdate);
				toggle.addEventListener(KeyboardEvent.KEY_DOWN, toggleUpdate);

				//Added for changing the value of the togglebutton toolTip when the views are changed
				toggle.addEventListener(FlexEvent.VALUE_COMMIT, toggleUpdate);
        	}        	
		}
		
		private function toggleUpdate(e:Event):void
		{
			var index:int = toggle.selectedIndex;
			
			var chartButton:Button = Button(toggle.getChildAt(0));
			var gridButton:Button = Button(toggle.getChildAt(1));
			
			//sets toolTip for toogle bar depending on which view is selected
			if(index == 0) 
			{ 
				togToolTip = chartButton.toolTip + 
					" is selected. To view in grid " + 
					"hit the right arrow and then space bar."; 
			} 
			else 
			{ 
				togToolTip = gridButton.toolTip + 
					" is selected. To view in chart hit the left arrow and then space bar."; 
			}
		}
        
        //used only when accessibility is true
        //sorts dataGrid according to column (e.g. pressing "1" will sort the 1st column)
        //not global because dataGrid uses a keyboardEvent handler to jump in datagrid (e.g. if "1" is pressed, 
        //will find first entry that starts with "1")
        private function gridKeyDownHander(event:KeyboardEvent):void 
		{
			//checks to see if key pressed is between 1 and however many columns are in the datagrid
			// keyCode for "1" = 48, "2" = 49, ...
			var colIdx:int = event.keyCode - 49;
			
			if ((colIdx < grid.columns.length) && (colIdx >= 0)) 
			{

				var col:DataGridColumn = grid.columns[colIdx];
				
				//dispatches an event to sort indicated column
				var dataGridEvent:DataGridEvent = new DataGridEvent(DataGridEvent.HEADER_RELEASE, false, true);
							dataGridEvent.columnIndex = colIdx;
							dataGridEvent.dataField = col.dataField;
							grid.dispatchEvent(dataGridEvent);
			}
		}
        
        public function set period(m:Object):void
        {
        	_period = m;
        	this.title = "[" + _period.@name + "]";
    	}
    	
    	public function get period():Object
    	{
    		return _period;
    	}
   

		[Bindable()]
		private var _period:Object;

        private function getSliceLabel(item:Object, arg2:String, arg3:Number, arg4:Number):String
        {
            return item==null?"":item.@name.slice(0,20);
        }

		private var _selectedRegion:Object;
		
        public function get selectedRegion():Object
        {
            return _selectedRegion;
        }

        public function set selectedRegion(item:Object):void
        {
            _selectedRegion = item;

            var index:int = -1;
            for (var i:int=0; i < _period.region.length && index == -1; i++)
            {
                if (_period.region[i].@name == item.@name)
                    index = i;
            }
            //we only want to explode the selected region
            var explodeData:Array = [];
            explodeData[index] = 0.15;
            pcRegion.series[0].perWedgeExplodeRadius = explodeData;
        }

        private function dataGridCurrencyFormat(item:Object, column:Object):String
        {
            return suDisplay.format(item[column.dataField]);
        }

        private function formatDataTip(hitData:HitData):String
        {
            var name:String = hitData.item.@name;
            var value:Number = hitData.item.@value;
            return "<b>"+name+"</b><br>"+suDisplay.format(value);
        }
        
        private function gridComp():void
        {
        	if(Accessibility.active) 
        	{
        		grid.addEventListener(KeyboardEvent.KEY_DOWN, gridKeyDownHander);
        	}
        }
        
		private function chartComp():void
		{
			if(Accessibility.active) 
        	{
        		pcRegion.accessibilityProperties.forceSimple = true;

				//Trying to make chart accessible
				var accessProps:AccessibilityProperties = new AccessibilityProperties();
				accessProps.name = "Chart data is available in grid view";
				accessProps.description = "Chart data is available in grid view";
				accessProps.forceSimple = true;

				pcRegion.accessibilityProperties = accessProps;
				Accessibility.updateProperties(); 

				pcToolTip = "Chart data is available in grid view";
        	}
		}


        ]]>

    </mx:Script>

    <mx:CurrencyFormatter id="cf"/>
	<mx:NumberFormatter id="suDisplay" 
		decimalSeparatorTo="."
		thousandsSeparatorTo=","
		useThousandsSeparator="true"/>

    <mx:SeriesInterpolate id="interpolate" elementOffset="10"/>

    <mx:VBox width="100%" height="100%" verticalGap="0">
    
    <mx:HBox width="100%">
		<mx:Label text="{title}" fontSize="12" fontWeight="bold" paddingLeft="10"/>
		<mx:Spacer width="100%"/>
        <mx:ToggleButtonBar dataProvider="{vs}" id="toggle" toolTip="{togToolTip}"/>
    </mx:HBox>
    <mx:ViewStack id="vs" width="100%" height="100%">
        <mx:VBox id="gridBox" width="100%" height="100%"  icon="@Embed('assets/icon_chart2.png')" toolTip="View in Chart" hideEffect="Fade" showEffect="Fade">
            <mx:PieChart id="pcRegion" dataProvider="{_period.region}" name="Chart data is available in grid view" toolTip="{pcToolTip}" showDataTips="true" width="100%" height="100%"
                dataTipFunction="formatDataTip"
                creationComplete="chartComp()">

                <mx:series>
                    <mx:Array>
                        <mx:PieSeries startAngle="90" field="@value" nameField="@name" labelPosition="callout"
                                      labelFunction="getSliceLabel" showDataEffect="{interpolate}">
	                    </mx:PieSeries>
                    </mx:Array>
                </mx:series>

            </mx:PieChart>
        </mx:VBox>

        <mx:HBox id="chartBox" width="100%" height="100%" icon="@Embed('assets/icon_grid.png')" toolTip="View in Grid" hideEffect="Fade" showEffect="Fade"
        	horizontalGap="0">
            <mx:Spacer width="15%"/>
            <mx:DataGrid dataProvider="{_period.region}" width="70%" height="100%" id="grid" creationComplete="gridComp();"
            	toolTip="{chartDGToolTip}">
                <mx:columns>
                    <mx:Array>
                        <mx:DataGridColumn dataField="@name" headerText="{itemData.@region}"/>
                        <mx:DataGridColumn dataField="@value"  textAlign="right" headerText="{itemData.@value}" labelFunction="dataGridCurrencyFormat" />
                    </mx:Array>
                </mx:columns>
            </mx:DataGrid>
            
        </mx:HBox>
    </mx:ViewStack>
    </mx:VBox>

</mx:Canvas>
