package net {
    import flash.events.*;
    import flash.net.*;
    
    import vo.*;
    import libs.fy;
    
    public class Communicator extends EventDispatcher {
        public var agents:Array;
        public var callback:Function;
        
        private var uLoader:URLLoader;
        private var source:String;
        private var letters: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"];
        
        public function Communicator(source:String) {
            super();
            this.source = source;
        }
        
        private function parseXML(s:String):void {
            s = s.replace(/<[^!?]?[^>]+?>/g, removeNamspaces)
            var xml:XML = new XML(s);
            var agents:XMLList = xml.agents.agent;
            Main.agents = new Array();
            for(var i:Number=0; i<agents.length(); i++) {
                if(i < 8) {
                    var agent:XML = agents[i];
    
                    // Preprocess XML Data
                    var phones:Array = new Array();
                    for each(var p:XML in agent.phones.phone) {;
                        var phone:Object = {number: p.number, type: p.type};
                        phones.push(phone);
                    }
                    // Save into VO
                    Main.agents.push(new Agent({
                        name: agent.name,
                        email: agent.email,
                        website: agent.agentInternetAddress,
                        address: agent.address.address1+", "+agent.address.city+" "+agent.address.state+" "+agent.address.zip,
                        phones: phones,
                        pictureUrl: agent.pictureUrl,
                        districtAgentCode: agent.districtAgentCode,
                        agentId: agent.agentId,
                        userId: agent.userId,
                        distanceFromLoc: agent.distanceFromLoc,
                        globalNickname: agent.globalNickname,
                        pointerLetter: letters[i]
                    }));
                }
            }
            
            // if callback is set map out agents
            Main.agents.map(mapAgents);
            dispatchEvent(new CommunicatorEvent(CommunicatorEvent.MAP_DONE));
        }
        
        private function mapAgents(a:*, index:int, arr:Array):void {
            dispatchEvent(new CommunicatorEvent(CommunicatorEvent.AGENT_DATA, a));
        }
        
        private function removeNamspaces(...rest):String
        {
            rest[0] = rest[0].replace(/xmlns[^"]+\"[^"]+\"/g, "");
            var attrs:Array = rest[0].match(/\"[^"]*\"/g);
            rest[0] = rest[0].replace(/\"[^"]*\"/g, "%attribute value%");
            rest[0] = rest[0].replace(/(<\/?|\s)\w+\:/g, "$1");
            while (rest[0].indexOf("%attribute value%") > 0)
            {
                rest[0] = rest[0].replace("%attribute value%", attrs.shift());
            }
            return rest[0];
        }
        
        private function handleLoaderComplete(e:Event):void {
            parseXML(e.target.data);
        }
        
        private function httpStatusHandler(e:HTTPStatusEvent):void {
            dispatchEvent(new DataEvent('addText',true,false,'HTTP STATUS: '+String(e.status)));
        }
        
        private function securityErrorHandler(e:SecurityErrorEvent):void {
            dispatchEvent(new DataEvent('addText',true,false,'Security: '+String(e.text)));
        }
        
        // Actions
        
        public function findAgents(zip:String):void {
            var requestVars:URLVariables = new URLVariables();
            var request:URLRequest = new URLRequest(source);
            
            requestVars.deviceId = 'agtloc';
            requestVars.locateMethod = 'radius';
            requestVars.radius = '5';
            requestVars.results = '5';
            requestVars.searchType = 'locateByZip';
            requestVars.version = 'v1';
            requestVars.zip = zip;
            request.data = requestVars;
            request.method = URLRequestMethod.POST
            
            uLoader = new URLLoader();
            uLoader.addEventListener(Event.COMPLETE, handleLoaderComplete);
            uLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
            uLoader.load(request);
        }
        
    }
}