<?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"
         creationComplete="creationComplete()" 
         xmlns:shell="com.afi.estimator.views.shell.*"
         xmlns:paging="com.afi.estimator.views.paging.*" xmlns:services="com.sharewithagent.services.*">
    
    <fx:Declarations>
        <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>
    
    
    <fx:Script>
        <![CDATA[
            import com.afi.estimator.model.*;

            import com.afi.estimator.views.paging.*;
            import com.afi.estimator.views.shell.*;
            import com.afi.estimator.views.vo.AnnuityVO;
            import com.afi.estimator.views.vo.PageVO;
            import com.sharewithagent.services.valueObject.AgentContact;

            import com.tracking.TrackingManager;
            
            import mx.controls.Alert;
            import mx.rpc.events.ResultEvent;
            
            import spark.components.Application;
            
            public static var instance:View;
            
            public var nextprevious:NextPrevious;
            public var footer:com.afi.estimator.views.shell.footer;
            
            private var current_page_index:Number = 0;
            
            [Bindable]private var state:State = Model.instance.state;
            
            private var trackingXML:XML;
            
            
            private var current_page_vo:PageVO;
            
            private var results_ac:ArrayCollection;
            
            private function creationComplete():void {
                var loader:URLLoader = new URLLoader(new URLRequest('com/afi/estimator/assets/xml/tracking.xml'));
                loader.addEventListener(Event.COMPLETE, onLoadTracking);
                showCurrentPage();
            }
            
            private function clearContent():void
            {
                title.text = '';
                body.text = '';
            }
            

            private function valid():Boolean
            {
                var ret:Boolean  = true;
                var msg:String = '';
                
                
                if(age.text == '') {
                    warn.visible = true;
                    warn.label = 'Please enter your age';
                    return false;
                } else if(Number(age.text) >= Number(retirement_age.selectedItem.val)) {
                    warn.visible = true;
                    warn.label = 'Your age must be less than your retirement age';
                    return false;
                } else {
                    warn.visible = false;
                }
                
                if(annual_premium.text == '') {
                    warn.visible = true;
                    warn.label = 'Please enter an annual contribution';
                    return false;
                } else {
                    warn.visible = false;
                }
                
                if(initial_premium.text=='') {
                    warn.visible = true;
                    warn.label = 'Please enter an initial investment amount';
                    return false;
                } else {
                    warn.visible = false;
                }
                
                return true;
            }
            
            private function showCurrentPage():void
            {
                clearContent();
                var cur_page:PageVO = PagesModel.pages[current_page_index];
                current_page_vo = cur_page;
                if(cur_page.section == 'calculate') {
                    vs.selectedChild = calculate;
                    next_btn.label = 'Next';
                    prev_btn.label = 'Previous';
                } else if(cur_page.section == 'results') {
                    vs.selectedChild = results;
                    prev_btn.label = 'Recalculate';
                    next_btn.label = 'Send To An Agent';
                } else if(cur_page.section == 'send') {
                    vs.selectedChild = sendToAgent;
                } else {
                    next_btn.label = 'Next';
                    prev_btn.label = 'Previous';
                    vs.selectedChild = education;
                    title.text = TextModel.get(cur_page.name).title;
                    body.htmlText = TextModel.get(cur_page.name).body;
                }
            }
            
            private function onLoadTracking(e:Event):void
            {
                trackingXML = XML(e.target.data);
            }

            private function previous():void
            {
                if(current_page_index > 0) {
                    current_page_index --;
                    showCurrentPage();
                }
            }
            
            private function next():void
            {
                if(current_page_vo.name == 'calculate') {
                    var am:AnnuityModel = new AnnuityModel(new AnnuityVO(Number(age.text), 
                        Number(initial_premium.text), 
                        Number(annual_premium.text), 
                        Number(retirement_age.selectedItem.val)));
                    
                    results_ac = am.calculate();
                    current_page_index++;
                    if(valid()) {
                        showCurrentPage();
                    }
                    
                } else if(current_page_vo.name == 'sendToAgent') {
                    trace("CALLING TO AGENT");
                    this.locateNearestAgentsByZIPCodeResult.addEventListener(ResultEvent.RESULT, handleResult);
                    this.locateNearestAgentsByZIPCode(zip_TI.text,-1,'','','AF');
                } else {
                    if(current_page_index < PagesModel.pages.length) {
                        current_page_index++;
                        showCurrentPage();
                    }
                }
            }
            
            private function handleResult(e:ResultEvent):void
            {
               var agent:AgentContact = e.result.agents[0];
               var sMsg:String;
               var sXML:String;
               var sEmailFrom:String = "ANNUITIES_CALCULATOR@amfam.com"
               var sSubject:String = "amfam.com Annuities Calculator Lead"
               
               
               sMsg = "<p><B>This is a Annuities Calculator Lead - Please verify and delete.&nbsp;&nbsp;&nbsp;Kris Anich</B></p>"        
                   
                   + "<p>"
                   + "Dear American Family Insurance Agent,"
                   + "</p><p>"
                   + "A customer has requested your assistance after completing the Annuities Calculator process on amfam.com."
                   + "</p><p>"
                   + "Please follow up with this individual within one business day of receiving this request. Take this opportunity to educate and make suggestions on additional product or services not listed in this summary."
                   + "</p><p>"
                   + "We have included the customer&#39;s contact information as well as a summary of the products suggested by the system as a pre-qualification criteria."
                   + "</p><p>"
                   + "Thanks and good luck with this potential sales opportunity."
                   + "</p><p>"
                   + "The amfam.com team / Marketing"
                   + "</p>"
                   
                   + "<p><B>This is a Needs Assessment email test - Please verify and delete.&nbsp;&nbsp;&nbsp;Kris Anich</B></p>";
               
               sXML = "<RECORD>"
                   + "  <SECTION>"
                   + "    <HEADER>"
                   + "      Contact Information"
                   + "    </HEADER>"
                   + "    <FIELD>"
                   + "      <NAME>Contact name</NAME>"
                   + "      <VALUE>" + name_TI.text + "</VALUE>"
                   + "    </FIELD>"
                   + "    <FIELD>"
                   + "      <NAME>Preferred contact method</NAME>"
                   + "      <VALUE>Email</VALUE>"
                   + "    </FIELD>"
                   + "    <FIELD>"
                   + "      <NAME>Email</NAME>"
                   + "      <VALUE>"+email_TI.text+"</VALUE>"
                   + "    </FIELD>"
                   + "  </SECTION>"
                   
                   + "  <SECTION>"
                   + "    <HEADER>"
                   + "      Annuity Information"
                   + "    </HEADER>"
                   + "    <FIELD>"
                   + "      <NAME>Age</NAME>"
                   + "      <VALUE>"+AnnuityModel.instance.annuity_vo.issue_age+"</VALUE>"
                   + "    </FIELD>"
                   + "    <FIELD>"
                   + "      <NAME>Initial Premium Amount</NAME>"
                   + "      <VALUE>$"+AnnuityModel.instance.annuity_vo.initial_premium+"</VALUE>"
                   + "    </FIELD>"
                   + "    <FIELD>"
                   + "      <NAME>Annual Contribution Amount</NAME>"
                   + "      <VALUE>$"+AnnuityModel.instance.annuity_vo.annual_contribution+"</VALUE>"
                   + "    </FIELD>"
                   + "    <FIELD>"
                   + "      <NAME>Planned Retirement Age</NAME>"
                   + "      <VALUE>"+AnnuityModel.instance.annuity_vo.retirement_age+"</VALUE>"
                   + "  </SECTION>"
                   + "</RECORD>";
                    
               this.sendLeadToAgent(agent.emailAddress, sEmailFrom, sSubject,sMsg,sXML);
               this.current_page_index = 0;
               this.showCurrentPage();
            }
                
            
            protected function locateNearestAgentsByZIPCode(zipcode:String, numberOfOfficesToLocate:int, licensedState:String, languageSpoken:String, enrolledInProgram:String):void
            {
                locateNearestAgentsByZIPCodeResult.token = agentLocatorService.locateNearestAgentsByZIPCode(zipcode, numberOfOfficesToLocate, licensedState, languageSpoken, enrolledInProgram);
            }
            
            
            protected function sendLeadToAgent(emailTo:String, emailFrom:String, emailSubject:String, emailMessage:String, leadInfo:String):void
            {
                sendLeadToAgentResult.token = agentLocatorService.sendLeadToAgent(emailTo, emailFrom, emailSubject, emailMessage, leadInfo);
            }
            
        ]]>
    </fx:Script>
    <mx:VBox>
            
        <mx:ViewStack id="vs" width="1024" height="500" tabIndex="1" tabChildren="true">
            
            <mx:Panel id="education" width="100%" height="100%" tabChildren="true">
                <mx:VBox>
                    <mx:Text width="800" height="200" tabChildren="true" tabFocusEnabled="true" id="title" tabIndex="2" />
                    <mx:Text  width="800" height="200" tabFocusEnabled="true" tabChildren="true"  id="body" tabIndex="3" />
                </mx:VBox>
            </mx:Panel>
            
            <mx:Panel id="calculate" width="100%" height="100%">
                <mx:VBox>
                    <mx:Form>
                        <mx:FormItem visible="false" id="warn" tabEnabled="false" />
                        <mx:FormItem label="Enter Your Age">
                            <mx:TextInput restrict="0-9" id="age" toolTip="Enter Your Age" />
                        </mx:FormItem>
                        <mx:FormItem label="Enter the amount you would like to contribute each year">
                          <mx:TextInput restrict="0-9" id="annual_premium" toolTip="Enter the amount you would like to contribute each year" />
                        </mx:FormItem>
                        <mx:FormItem label="Enter the amount you would like to contribute this year">
                            <mx:TextInput restrict="0-9" id="initial_premium" toolTip="Enter the amount you would like to contribute this year" />
                        </mx:FormItem>
                        <mx:FormItem label="{TextModel.get(current_page_vo.name).field4}">
                            <s:DropDownList id="retirement_age" 
                                            toolTip="Select the age you would like to retire.  use the up and down arrows to select an age" 
                                            requireSelection="true" 
                                            selectedIndex="1" 
                                            labelField="name" 
                                            itemRenderer="com.afi.estimator.style.forms.renderers.DDL_Renderer">
                                
                                <s:ArrayCollection id="ac">
                                    <fx:Object name="55 Years Old" val="55" />
                                    <fx:Object name="60 Years Old" val="60" />
                                    <fx:Object name="65 Years Old" val="65" />
                                    <fx:Object name="70 Years Old" val="70" />
                                    <fx:Object name="75 Years Old" val="75" />
                                </s:ArrayCollection>
                                
                            </s:DropDownList>
                        </mx:FormItem>
                    </mx:Form>
                </mx:VBox>
            </mx:Panel>
            
            <mx:Panel id="results" width="100%" height="100%">
                <mx:DataGrid toolTip="Form results" dataProvider="{results_ac}" width="100%" height="100%" />
            </mx:Panel>
            
            <mx:Panel id="sendToAgent" width="100%" height="100%">
                <mx:VBox>
                    <mx:Form>
                        <mx:FormItem label="Your Name">
                            <mx:TextInput id="name_TI" tabIndex="3" />
                        </mx:FormItem>
                        <mx:FormItem label="Your Email">
                            <mx:TextInput id="email_TI" tabIndex="4" />
                        </mx:FormItem>
                        <mx:FormItem label="Your Zip Code">
                            <mx:TextInput id="zip_TI" tabIndex="5" restrict="0-9" />
                        </mx:FormItem>
                    </mx:Form>
                </mx:VBox>
            </mx:Panel>
            
        
            
        </mx:ViewStack>
        <s:HGroup>
            <mx:Button id="prev_btn" label="Previous" tabIndex="1" click="previous()" />
            <mx:Button id="next_btn" label="Next" tabIndex="2" click="next()" />
        </s:HGroup>
        
    </mx:VBox>
</s:Group>