<?xml version="1.0" encoding="utf-8"?>
<!--

////////////////////////////////////////////////////////////////////////////////
//
//    Copyright 2014 Ardisia Labs LLC. All Rights Reserved.
//
//    This file is licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////

-->
<s:Module xmlns:fx="http://ns.adobe.com/mxml/2009" 
          xmlns:s="library://ns.adobe.com/flex/spark" 
          xmlns:mx="library://ns.adobe.com/flex/mx"
          xmlns:treeMap="ardisia.charts.treeMap.*"
          xmlns:containers="containers.*"
          xmlns:data="containers.data.*"
          xmlns:separators="ardisia.components.separators.*"
          xmlns:colorizer="ardisia.components.colorizer.*" 
          xmlns:data1="ardisia.components.colorizer.data.*"
          xmlns:colorPicker="ardisia.components.colorPicker.*"
          xmlns:legend="ardisia.charts.legend.*"
          frameRate="60"
          width="100%" height="100%"
          removedFromStage="removedFromStageHandler(event)">
    
    <!-- scripts -->
    <fx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection;
            
            import ardisia.charts.treeMap.events.TreeMapEvent;
            import ardisia.charts.treeMap.interfaces.ITreeMapItemRenderer;
            
            //--------------------------------------
            //  variables
            //--------------------------------------
            
            private var collection:ArrayCollection;
            
            //----------------------------------
            //  methods
            //----------------------------------
            
            public function creationComplete():void
            {
                // build hierarchical data
                var nodes:Array = [];
                var categories:Array = [];
                
                // get the categories
                for each (var item:XML in xml.Breed) 
                {
                    var category:String = item["@category"];
                    
                    if (categories.indexOf(category) < 0)
                        categories.push(category);
                }
                
                var tree:Array = [];
                
                // get the groups
                for each (var cat:String in categories) 
                {
                    var groups:Array = [];
                    tree.push([cat, groups]);
                    
                    for each (item in xml.Breed.(@category == cat)) 
                    {
                        var group:String = item["@group"];
                        
                        if (groups.indexOf(group) < 0)
                            groups.push(group);
                    }
                }
                
                for each (var catArr:Array in tree) 
                {
                    var catNodes:Array = [];
                    var catObject:Object = {
                        name: catArr[0] 
                        ,children: catNodes
                    };
                    
                    nodes.push(catObject);
                    
                    for each (group in catArr[1])
                    {
                        var groupNodes:Array = [];
                        var groupObject:Object = {name: group, children: groupNodes};
                        
                        catNodes.push(groupObject);
                        
                        for each (var xmlObj:XML in xml.Breed.(@group == group)) 
                        {    
                            var obj:Object = {
                                name: xmlObj["@name"], 
                                registrations: xmlObj["@registrations"], 
                                group: xmlObj["@group"], 
                                category: xmlObj["@category"]
                            };
                            
                            groupNodes.push(obj);
                        }
                        
                    }
                    
                }
                
                collection = new ArrayCollection([{name:"Dog Breed Registrations", children: nodes}]);
                treemap.dataProvider = collection;
            }
            
            protected function dataTipFunction(value:Object):String
            {
                /*
                var hoveredRenderer:ITreeMapItemRenderer = treemap.getHovered();
                var name:String = value.name;
                var registrations:Number = hoveredRenderer.treeMapData.weight;
                var group:String = value["group"];
                var category:String = value["category"];
                
                var percent:Number = Math.round((registrations / treemap.totalWeight * 100) * 100) / 100;
                var str:String = "<p><b>" + name + "</b></p>";
                str += "<br>Registrations: " + registrations + " (" + percent + "% total)";
                if (!hoveredRenderer.treeMapData.isBranch)
                {
                    str += "<br>Group: " + group;
                    str += "<br>Category: " + category;
                }
                
                return str;
                */
                return null
            }
            
            protected function colorFunction(value:Object):uint
            {
                if (!value.nodeData || !value.nodeData.hasOwnProperty("group"))
                    return 0;
                
                var group:String = value.nodeData.group;
                
                var rand:Number = Math.random();
                
                switch (group)
                {
                    
                    case "Gundog":
                        return redColorizer.getColor(rand);
                        
                        break;
                    
                    case "Hound":
                        return violentColorizer.getColor(rand);
                        
                        break;
                    
                    case "Terrier":
                        return greenColorizer.getColor(rand);
                        
                        break;
                    
                    case "Pastoral":
                        return tealColorizer.getColor(rand);
                        
                        break;
                    
                    case "Toys":
                        return blueColorizer.getColor(rand);
                        
                        break;
                    
                    case "Utility":
                        return yellowColorizer.getColor(rand);
                        
                        break;
                    
                    case "Working":
                        return pinkColorizer.getColor(rand);
                        
                        break;
                    
                    default:
                        return pinkColorizer.getColor(rand);
                        
                        break
                    
                }
                
                return 0x3F3F3F;
            }
            
            //--------------------------------------
            //  event handlers
            //--------------------------------------
            
            protected function treemapHandler(event:TreeMapEvent):void
            {
                return;
                var renderer:ITreeMapItemRenderer = event.renderer;
                
                switch (event.type)
                {
                    
                    case TreeMapEvent.ITEM_ROLL_OVER:
                        Mouse.cursor = renderer && renderer.data.children ? MouseCursor.BUTTON : MouseCursor.AUTO;
                        
                        break;
                    
                    case MouseEvent.ROLL_OUT:
                        Mouse.cursor = MouseCursor.AUTO;
                        
                        break;
                    
                    case TreeMapEvent.ITEM_CLICK:
                        
                        if (renderer && renderer.data.children)
                        {
                            if (renderer.data == treemap.dataProvider[0])
                            {
                                treemap.dataProvider = collection;
                            }
                            else
                            {
                                treemap.dataProvider = new ArrayCollection([renderer.data]);
                            }
                        } 
                        
                        break;
                    
                }
            }
            
            protected function removedFromStageHandler(event:Event):void
            {
                
            }
            
        ]]>
    </fx:Script>
    
    <!-- declarations -->
    <fx:Declarations>
        
        <fx:XML id="xml" 
                source="data/DogBreeds.xml" />
        
        <!--- @required -->
        <!--- vary ratio from 0 to 1 -->
        <colorizer:GradientColorizer id="redColorizer" rangeMinimum="0" rangeMaximum="1">
            <data1:GradientColorizerData ratio="0" color="#9C1F1F" />
            <data1:GradientColorizerData ratio="1" color="#4E0F0F" />
        </colorizer:GradientColorizer>
        
        <colorizer:GradientColorizer id="yellowColorizer" rangeMinimum="0" rangeMaximum="1">
            <data1:GradientColorizerData ratio="0" color="#9C891F" />
            <data1:GradientColorizerData ratio="1" color="#4E440F" />
        </colorizer:GradientColorizer>
        
        <colorizer:GradientColorizer id="greenColorizer" rangeMinimum="0" rangeMaximum="1">
            <data1:GradientColorizerData ratio="0" color="#449C1F" />
            <data1:GradientColorizerData ratio="1" color="#224E0F" />
        </colorizer:GradientColorizer>
        
        <colorizer:GradientColorizer id="tealColorizer" rangeMinimum="0" rangeMaximum="1">
            <data1:GradientColorizerData ratio="0" color="#1F9C66" />
            <data1:GradientColorizerData ratio="1" color="#0F4E33" />
        </colorizer:GradientColorizer>
        
        <colorizer:GradientColorizer id="blueColorizer" rangeMinimum="0" rangeMaximum="1">
            <data1:GradientColorizerData ratio="0" color="#1F689C" />
            <data1:GradientColorizerData ratio="1" color="#0F344E" />
        </colorizer:GradientColorizer>
        
        <colorizer:GradientColorizer id="violentColorizer" rangeMinimum="0" rangeMaximum="1">
            <data1:GradientColorizerData ratio="0" color="#421F9C" />
            <data1:GradientColorizerData ratio="1" color="#210F4E" />
        </colorizer:GradientColorizer>
        
        <colorizer:GradientColorizer id="pinkColorizer" rangeMinimum="0" rangeMaximum="1">
            <data1:GradientColorizerData ratio="0" color="#9C1F8B" />
            <data1:GradientColorizerData ratio="1" color="#4E0F45" />
        </colorizer:GradientColorizer>
        
    </fx:Declarations>
    
    <!-- states -->
    <s:states>
        <s:State name="stockholm" />
        <s:State name="london" />
        <s:State name="spark" />
    </s:states>
    
    <!-- application -->
    <containers:DemoApplicationWrapper id="demoAppWrapper" 
                                       width="100%" height="100%"
                                       westRegionTitle="TreeMap Description"
                                       description="TreeMap chart. Uses the squarified layout scheme.&#13;&#13;See http://www.win.tue.nl/~vanwijk/stm.pdf for an explanation of how the squarified layout works."
                                       currentState.stockholm="stockholm" currentState.london="london" currentState.spark="spark">
        
        <containers:expandingContainerContent>
            
            <!--- expanding container #1 -->
            <data:ExpandingContainerData>
                <data:label>API</data:label>
                <data:content>
                    <s:FormHeading label="Layout:"/>
                    <s:FormItem label="Branch Headers:">
                        <s:CheckBox id="showBranchHeadersSelect" 
                                    selected="true"/>
                        <s:helpContent>
                            <s:Image source="@Embed(source='icons/question.png')"
                                     toolTip="True to display the branch header nodes."/>
                        </s:helpContent>
                    </s:FormItem>
                    <s:FormItem label="Gap:">
                        <s:HSlider id="nodeGapSelect"
                                   minimum="0" maximum="10" value="1"/>
                    </s:FormItem>
                    
                    <separators:HSeparator width="100%"
                                           paddingTop="5" paddingBottom="5"/>
                    <s:FormHeading label="Colors"/>
                    <s:FormItem label="Use Custom Colors:">
                        <s:CheckBox id="colorFunctionSelect" 
                                    selected="true"
                                    change="treemap.colorFormatFunction=colorFunctionSelect.selected ? colorFunction : null; ArrayCollection(treemap.dataProvider).refresh();"/>
                        <s:helpContent>
                            <s:Image source="@Embed(source='icons/question.png')"
                                     toolTip="True to use a custom color function."/>
                        </s:helpContent>
                    </s:FormItem>
                    <s:FormItem label="Background Color:">
                        <colorPicker:ColorPicker id="backgroundColorSelect"
                                                 selectedColor="#000000"/>
                    </s:FormItem>
                    <s:FormItem label="Background Alpha:">
                        <s:HSlider id="backgroundAlphaSelect"
                                   minimum="0" maximum="1" snapInterval="0" value="1"/>
                    </s:FormItem>
                    
                    <separators:HSeparator width="100%"
                                           paddingTop="5" paddingBottom="5"/>
                    <s:FormHeading label="DataTip"/>
                    <s:FormItem label="Display DataTip:">
                        <s:CheckBox id="showDataTipSelect"
                                    selected="true"/>
                    </s:FormItem>
                    <s:FormItem label="Hide Delay:">
                        <s:HSlider enabled="{showDataTipSelect.selected}" 
                                   id="dataTipHideDelaySelect"
                                   width="100"
                                   minimum="0" maximum="1000" snapInterval="0" value="350"/>
                        <s:helpContent>
                            <s:Image source="@Embed(source='icons/question.png')"
                                     toolTip="Delay before removing datatip after mousing out of a data node."/>
                        </s:helpContent>
                    </s:FormItem>
                </data:content>
            </data:ExpandingContainerData>
            
        </containers:expandingContainerContent>
        
        <containers:centerContent>
            
            <!--- example #1 -->
            <data:PrimaryContentData>
                <data:exampleDescription>Dog Breeds in the UK</data:exampleDescription>
                <data:primaryContent>
                    <s:HGroup height="100%" width="100%"
                              verticalAlign="justify">
                        <treeMap:TreeMap id="treemap" 
                                         width="100%"
                                         showDataTip="{showDataTipSelect.selected}"
                                         dataTipHideDelay="{dataTipHideDelaySelect.value}"
                                         nodeGap="{nodeGapSelect.value}"
                                         labelField="name"
                                         colorFormatFunction="{colorFunction}"
                                         showBranchHeaders="{showBranchHeadersSelect.selected}"
                                         backgroundAlpha="{backgroundAlphaSelect.value}"
                                         backgroundColor="{backgroundColorSelect.selectedColor}"
                                         weightField="registrations"/>
                    </s:HGroup>
                </data:primaryContent>
            </data:PrimaryContentData>
            
        </containers:centerContent>
        
    </containers:DemoApplicationWrapper>
    
</s:Module>