<?xml version="1.0" encoding="utf-8"?>
<s:Group 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:views="com.sharewithagent.views.*" 
               xmlns:services="com.sharewithagent.services.*"
               addedToStage="onAdded()"
               creationComplete="init()" >
    
    <fx:Script><![CDATA[
        import com.afi.estimator.model.ContactModel;
        import com.afi.estimator.model.PagesModel;
        import com.afi.estimator.style.forms.BlueAFIInput;
        import com.afi.estimator.views.pages.ContactsPage;
        import com.afi.estimator.views.paging.FormScroller;
        import com.afi.estimator.views.vo.ContactVO;
        import com.google.maps.*;
        import com.google.maps.controls.*;
        import com.google.maps.overlays.*;
        import com.google.maps.services.*;
        import com.sharewithagent.map.AgentMarker;
        import com.sharewithagent.net.CommunicatorEvent;
        import com.sharewithagent.services.valueObject.AgentContact;
        import com.sharewithagent.views.*;
        import com.utils.Mustache;
        
        import mx.collections.ArrayCollection;
        import mx.controls.Alert;
        import com.afi.estimator.model.TextModel;
        import mx.formatters.CurrencyFormatter;
        import mx.managers.CursorManager;
        import mx.rpc.events.FaultEvent;
        import mx.rpc.events.ResultEvent;
    
        
    public static var statesCollection:ArrayCollection = new ArrayCollection(["AL","AK","AZ","AR","CA","CO","CT","DE","FL","GA","HI","ID","IL",
        "IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT",
        "NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI",
        "SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY"]);
        
    [Bindable]public var api_key:String ;
        //= "ABQIAAAAWBj1kapda1wpOtqeUUxEixT2yXp_ZAY8_ufC3CFXhHIE1NvwkxREFzS02OHOSikW-CAiixno8kYhgg";
        
    [Bindable]public var padding:Number = 20;
        
    public var selectedAgent:Object = {
        firstName: "",
        lastName: ""
    };
        
    [Bindable]private var pageName:String = 'sharePage';
        
    private var infoPopup:Popup,
                popupOverlay:Marker,
                systemSelectedAgent:ListItem,
                currentAgents:Array = new Array();
     
    private function onAdded():void
    {
        //this.locateNearestAgentsByZIPCodeResult.addEventListener(ResultEvent.RESULT, handleLocateNearestAgentsByZIPCodeResult);
        
        this.locateNearestAgentsByZIPCodeResult.addEventListener(ResultEvent.RESULT, handleLocateNearestAgentsByZIPCodeResult);
        this.locateNearestAgentsByZIPCodeResult.addEventListener(FaultEvent.FAULT,handleFault);
        
         if(ContactModel.instance.VO.zip) {
            this.locateNearestAgentsByZIPCode(ContactModel.instance.VO.zip, -1, '','','AF');
        } 
        
        var st:String = ContactModel.instance.VO.state;
        
    }
        
    public function init():void {    
        
    }
    
    private function handleFault(e:ResultEvent):void
    {
        noagents.visible = true;
    }
    
    private function pinClick(e:CommunicatorEvent):void {
        var point:LatLng = new LatLng(e.data.marker.latlong.lat()+0.01, e.data.marker.latlong.lng());
        map.setCenter(point, 13, MapType.NORMAL_MAP_TYPE);
        
        if (popupOverlay) map.removeOverlay(popupOverlay);
        
        var p:Popup = new Popup();
        p.show(e.data.agent, e.data.marker, map);
        
        var group:Group = new Group();
        group.addElement(p);
        
        popupOverlay = new Marker(
            e.data.marker.latlong,
            new MarkerOptions({
                hasShadow: false,
                icon: group
            })
        );
        
        map.addOverlay(popupOverlay);
        
        selectAgent(e.data.agent);
    }
        
    private function selectAgent(agent:Object):void {
        for(var i:uint=0; i<currentAgents.length; i++) {
            if(currentAgents[i].agent == agent) {
                
            } else {
                currentAgents[i].listItem.chbx.selected = false;
                currentAgents[i].listItem.selected = false;
            }
        }
        selectedAgent = agent;
    }
    
    public function emailSelectedAgent():void {
        if (selectedAgent && selectedAgent.emailAddress) {
            sendLeadToAgent(selectedAgent.emailAddress);
            FormScroller.instance.gotoPage('thanks');
        } 
        
    }
    
    // Services
    public function handleLocateNearestAgentsByZIPCodeResult(event:ResultEvent):void {
        var systemSelected:Boolean = true;
        
        trace('>>> [systemSelected] ', systemSelected, ' pref: ', ContactModel.instance.VO.agent_selection_preference); 
        
        // Clear out old results
        agentList.removeAllElements();
        map.clearOverlays();
        
        // Process new agents
        var alpha:Array = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
        var alphaCount:int = 0;
        var pinsPlaced:int = 0;
        var bounds:LatLngBounds = new LatLngBounds();
        currentAgents = new Array();
        
        if(event.result.agents.length > 0) {
            
            if (systemSelected) event.result.agents = [event.result.agents[0]];
            
            for each (var a:* in event.result.agents) {
                var agent:AgentMarker = new AgentMarker(map, a, alpha[alphaCount], systemSelected);
                agent.addEventListener("clicked", pinClick);
                agent.addEventListener(CommunicatorEvent.PIN_PLACED, function(e:CommunicatorEvent):void {
                    pinsPlaced++;
                    bounds.extend(e.data.pin.point);
                    
                    trace("pin placed ", e.data.pin.letter);
                    
                    if (pinsPlaced == event.result.agents.length && !systemSelected) {
                        trace("centered!");
                        map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds), MapType.NORMAL_MAP_TYPE);
                    }
                });
                
                var listItem:ListItem = new ListItem();
                if (alphaCount == 0) listItem.currentState = "first";
                listItem.agentName = a.firstName + " " + a.lastName;
                listItem.address = a.address +" "+ a.city + ", "+a.state+" "+a.zip;
                listItem.miles = a.distanceFromCoordinatesUsedToLocate;
                listItem.mapPin = agent;
                listItem.selectEvent = selectAgent;
                currentAgents.push({'listItem':listItem, 'agent':a});
                agentList.addElement(listItem);
                alphaCount++;
                
                if (systemSelected) {
                    trace("System is selecting..");
                    (function(listItem:ListItem, agent:AgentMarker):void{
                        agent.geocodeCallback = function():void{
                            listItem.selectItem();
                        }
                    })(listItem, agent);
                }
            }
            
            
        } else {
            agentList.addElement(noagents);
        }
    } 
        
    private function getTurnByTurn():void
    {
        if(selectedAgent && selectedAgent.city) {
                
            var vo:ContactVO = ContactModel.instance.VO;
            var url:String = 'http://maps.google.com/maps?f=d&saddr='+vo.address+' '+vo.city+' '+vo.state+' '+vo.zip;
            url += '&daddr='+selectedAgent.address+' '+selectedAgent.city+' '+selectedAgent.state+' '+selectedAgent.zip;
            navigateToURL(new URLRequest(url),'_blank');
        }
    }
        
    /**
     * The sendLeadToAgent() method is used to call the sendLeadToAgent 
     * web service operation.  The method gets called when the user clicks the Send Needs Assessment 
     * to Agent button. 
     */   
    public function sendLeadToAgent(sEmailTo:String):void{
        
        var sMsg:String;
        var sXML:String;
        var sEmailFrom:String = "ANNUITIES_CALCULATOR@amfam.com"
        var sSubject:String = "Annuities Calculator Lead"            
        
        sXML = "<RECORD>"
            + "  <SECTION>"
            + "    <HEADER>"
            + "      Contact Information"
            + "    </HEADER>"
            + "    <FIELD>"
            + "      <NAME>Contact name</NAME>"
            + "      <VALUE>" + ContactModel.instance.VO.name + "</VALUE>"
            + "    </FIELD>"
            + "    <FIELD>"
            + "      <NAME>Address</NAME>"
            + "      <VALUE>"+ContactModel.instance.VO.address+', '+ContactModel.instance.VO.city+', '+ContactModel.instance.VO.state+', '+ContactModel.instance.VO.zip+"</VALUE>"
            + "    </FIELD>"
            + "    <FIELD>"
            + "      <NAME>Preferred contact method</NAME>"
            + "      <VALUE>"+ContactModel.instance.VO.contact_method+"</VALUE>"
            + "    </FIELD>"
            + "    <FIELD>"
            + "      <NAME>Phone</NAME>"
            + "      <VALUE>"+ContactModel.instance.VO.phone+"</VALUE>"
            + "    </FIELD>"
            + "    <FIELD>"
            + "      <NAME>Email</NAME>"
            + "      <VALUE>"+ContactModel.instance.VO.email+"</VALUE>"
            + "    </FIELD>"
            + "  </SECTION>"
            
            + "</RECORD>";
            
            
            Mustache.render_template("com/afi/estimator/assets/templates/agentEmail.mustache", {
                name: ContactModel.instance.VO.name,
                address: ContactModel.instance.VO.address+', '+ContactModel.instance.VO.city+', '+ContactModel.instance.VO.state+', '+ContactModel.instance.VO.zip,
                contact_method: ContactModel.instance.VO.contact_method,
                email: ContactModel.instance.VO.email,
                phone: ContactModel.instance.VO.phone
            }, function(sMsg:String):void {    
                sendLeadToAgent2(sEmailTo, sEmailFrom, sSubject, sMsg, sXML);
            });
            
            
            if(ContactModel.instance.VO.email) {
                var cMsg:String;
                var cXML:String;
                var cEmailFrom:String = "ANNUITIES_CALCULATOR@amfam.com"
                var cSubject:String = TextModel.get(pageName).emailTitle;
                
                //var res:ArrayCollection = AnnuityModel.instance.calculate();
                //var accumulated_balance:String = res[res.length-1].Value
                    
                //res = AnnuityModel.instance.calculate(true, true);
                //var annual_payout:String = res[res.length-1].Value;
                
                // Format Currency
                var cur:CurrencyFormatter = new CurrencyFormatter();
                cur.currencySymbol = "$";
                cur.rounding = "none";
                cur.precision = 2;
                cur.useThousandsSeparator = true;
                
                /* accumulated_balance = cur.format(accumulated_balance);
                annual_payout = cur.format(annual_payout);
                var initial_premium:String = cur.format(AnnuityModel.instance.annuity_vo.initial_premium);
                var annual_premium:String = cur.format(AnnuityModel.instance.annuity_vo.annual_contribution); */
                
                
                Mustache.render_template("com/afi/estimator/assets/templates/customerEmail.mustache", {
                }, function(cMsg:String):void {    
                    sendLeadToAgent2(ContactModel.instance.VO.email, cEmailFrom, cSubject, cMsg, '');
                });
            }
    } 
        
    
        
    // Map
    private function onMapReady(e:Event):void {
        
        if(ContactModel.instance.VO.zip) {
              this.locateNearestAgentsByZIPCode(ContactModel.instance.VO.zip, -1, "", "", "AF"); 
            map.addEventListener(MapMoveEvent.MOVE_START, onMapStartMove);
            map.y += 0.3;
            map.setDoubleClickMode(0);
        } 
    }
        
    private function onMapStartMove(e:Event):void {
        //infoPopup.visible = false;
    }
    
    protected function locateNearestAgentsByZIPCode(zipcode:String, numberOfOfficesToLocate:int, licensedState:String, languageSpoken:String, enrolledInProgram:String):void
    {
        //locateNearestAgentsByZIPCodeResult.token = agentLocatorService.locateNearestAgentsByZIPCode(zipcode, numberOfOfficesToLocate, licensedState, languageSpoken, enrolledInProgram);
         locateNearestAgentsByZIPCodeResult.token = agentLocatorService.assignNearestAgentByAddress(ContactModel.instance.VO.address, ContactModel.instance.VO.city,ContactModel.instance.VO.state,
            ContactModel.instance.VO.zip,licensedState, languageSpoken, enrolledInProgram);
        
        //locateNearestAgentsByZIPCodeResult.token = agentLocatorService.locateAgentsByName(ContactModel.instance.VO.);
        
    }
    
    
    protected function sendLeadToAgent2(emailTo:String, emailFrom:String, emailSubject:String, emailMessage:String, leadInfo:String):void
    {
        sendLeadToAgentResult.token = agentLocatorService.sendLeadToAgent(emailTo, emailFrom, emailSubject, emailMessage, leadInfo);
    }
        
    ]]></fx:Script>
    <fx:Declarations>
        <s:Label id="noagents" text="{TextModel.get(pageName).noAgents}" width="300" />
        <s:CallResponder id="locateNearestAgentsByZIPCodeResult"/>
        <services:AgentLocatorService id="agentLocatorService" fault="Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail)" showBusyCursor="true"/>
        <s:CallResponder id="sendLeadToAgentResult"/>
    
    </fx:Declarations>
    
    <s:VGroup id="zipInput" gap="10"
              paddingBottom="{padding}" paddingLeft="{padding}" paddingRight="{padding}" paddingTop="{padding}">
        
        <s:HGroup gap="-10" id="mapAndList">
        
            <s:Group width="400" height="270" id="agentListHolder">
                <s:Rect width="100%" height="100%" radiusX="5" top="-1">
                    <s:fill>
                        <s:SolidColor color="#FEFEFE" />
                    </s:fill>
                    <s:stroke>
                        <s:SolidColorStroke color="#A3A3A3" />
                    </s:stroke>
                </s:Rect>
                
                
                <s:VGroup horizontalAlign="left" 
                          width="100%" height="100%" 
                          paddingBottom="15" paddingLeft="15" paddingRight="15" paddingTop="15">
                    <s:Scroller skinClass="com.afi.estimator.style.scroll.SmallAFIScroller" height="220" width="370" horizontalScrollPolicy="off">
                        <s:VGroup id="agentList" gap="0">
                        </s:VGroup>
                    </s:Scroller>
                </s:VGroup>
                
            </s:Group>
            
            <maps:Map xmlns:maps="com.google.maps.*"
                      id="map" 
                      mapevent_mapready="onMapReady(event)" 
                      width="400" height="269" 
                      key="{api_key}" sensor="false"
                      />
            
        </s:HGroup>
        
        <s:HGroup>
            
            <s:HGroup width="400" height="80" verticalAlign="middle" horizontalAlign="center">
                <s:Button skinClass="com.afi.estimator.style.buttons.LargeGreenButton" click="emailSelectedAgent()" buttonMode="true" label="{TextModel.get(pageName).shareWithAgent}" width="200" height="35" />
            </s:HGroup>
            
        </s:HGroup>
        
    </s:VGroup>
    
</s:Group>