package
{
    import mx.collections.ArrayCollection;
    import mx.controls.TextInput;
    import mx.core.Application;
    import mx.rpc.events.ResultEvent;
    import mx.rpc.http.HTTPService;

    public class WeatherApp extends Application
    {

        function WeatherApp()
        {
        }

        [Bindable]
        public var myResult:XML;

        [Bindable]
        public var weatherObject:Object;

        [Bindable]
        public var listContents:ArrayCollection;

        public var weatherService:HTTPService;
        public var zip:TextInput;

        public namespace yweather = "http://xml.weather.yahoo.com/ns/rss/1.0";
        use namespace yweather;

        public function requestWeather():void {
            weatherService.cancel();
            var params:Object = new Object();
            params.p = zip.text;
            weatherService.send(params);
        }

        public function resultHandler(event:ResultEvent):void {
            myResult = XML(event.result);
            weatherObject = new Object();
            weatherObject.zip = zip.text;
            weatherObject.city = myResult.channel.yweather::location.@city;
            weatherObject.temp = myResult.channel.item.yweather::condition.@temp;
            weatherObject.imgsource = parseImageUrl(myResult.channel.item.description);

            var a:Array = new Array(weatherObject);
            listContents = new ArrayCollection(a);
        }

        public function parseImageUrl(fromHtml:XMLList):String {
            var pattern:RegExp = /img src="(.+?)"/;
            var results:Array = pattern.exec(fromHtml);
            var imageURL:String = results[1]; // backreference 1 from pattern
            return imageURL;
        }
    }
}
