package
{
    
    import flash.display.Sprite;
    import flash.utils.Timer;
    import flash.events.*;
    
    import com.tadSrc.tadsClasses.DOMEx;
    import com.tadSrc.tadsClasses.LoadSomeXML;
    
    public class domexRss extends Sprite
    {
        
        private var INI_LAG_TIME:Number = 1500;
        private var theXML:XML;
        private var xmlURL:String;
        private var wrapperDivID:String = "RssContent";

	public var memoryHolder:Array = [];
        
        private var specs:Array = [ "linkStyle", "linkDivStyle", "titleStyle", "overallFeedStyle", "descriptionStyle" ];
        
	private const DEFAULT_overallFeedStyle:String = 
	"font-family:arial;color:black;width:700px;margin-left:auto;margin-right:auto;";

	private const DEFAULT_linkDivStyle:String = "font-family:helvetica;color:#6495ED;font-size:105%";

	private const DEFAULT_titleStyle:String = "font-family:times;color:blue;font-size:110%;font-weight:bold";
	
	private const DEFAULT_descriptionStyle:String = "font-family:times;color:black;font-size:80%";

	private const DEFAULT_linkStyle:String = "font-family:times;color:blue;font-size:100%";

        private var styleSpecs:Object;
        
        
        public function set rssURL(toThis:String):void { xmlURL = toThis; }
        public function get rssURL():String { if (xmlURL) {return xmlURL;} else { return "";} }
        
        
        public function set outputDivID(thisID:String):void { wrapperDivID = thisID; }
        public function get outputDivID():String { return wrapperDivID; }
        
        
        public function get lagTime():Number { return INI_LAG_TIME; }
        
        
        public function get currentStylesDefined():String {
            
            var theS:String = "No styles defined";
            
            if (styleSpecs) {
                theS = "";
                for (var eachSpec:String in styleSpecs)
                { theS += eachSpec+" = "+styleSpecs[eachSpec]+"\n"; }
            }
            
            return theS;
            
        }

	
        public function get establishFeedStyles():Function { return specCreation; } 
        
	public function get applyFeedStyles():Function { return giveFeedStyle; }        


       /* changeFeedStyle is used to change the css of any feed that is displayed.
          pass the css name value string pairs as an object in the first param
          and the id of the feed div as the second param, */
	public function get changeFeedStyle():Function { return feedStyleChangeSteps; }
	

        /* loadRssXML is used to retreve the rss file, pass the name of the feed via flashvars (rssURL), 
           or directly with loadRssXML as the first param. 
           The second optional param is the id of the div in which to place the resulting feed.
           The third optional param is an object that contains the style specs. */
        public function get loadRssXML():Function { return loadAnRssFeedXML; }
        
        
       
/* 
* All possible flashvars options are: 
*    rssURL, lagTime, outputDivID, linkDivStyle, linkStyle, titleStyle, overallFeedStyle, descriptionStyle, noDOM 
*
* rssURL - the url to the rss xml file.
* lagTime - the lag time to ensure that the DOM is ready (should be at least 1000(milliseconds))
* outputDivID - the id of the div that will hold the initial feed
* linkDivStyle - the css style of the divs that hold each link anchor
* linkStyle - the css style of each link anchor
* titleStyle - the css style of the divs that will hold each title
* overallFeedStyle - the css style of the div that will hold the feed (the outputDivID div)
* descriptionStyle - the css style of the divs that will hold each description 
* noDOM - simply declare this flashvar with any value to disable DOM support
* 
* All public getters (above these comments) can be called with "domexRSS" in the wrapper - 
*
*  example - domexRSS("loadRssXML", "rss.xml", "divID");
*
* Setters can be set using the same, via standard DOMEx setting syntax - domexRSS("rssURL", "=", "rss.xml");
* 
* @author Tad D Green
*
*/
    
        
        public function domexRss(fvars:Object = null)
        {
            
            if (fvars == null) {
                
                try { fvars = loaderInfo.parameters; } catch(e:Error) {  fvars = new Object(); };
                
            }
            
            if (fvars.hasOwnProperty('rssURL')) { xmlURL = fvars.rssURL.toString(); } 
            if (fvars.hasOwnProperty('lagTime')) { INI_LAG_TIME = Number(fvars.lagTime); } 
            if (fvars.hasOwnProperty('outputDivID')) { wrapperDivID = fvars.outputDivID.toString(); } 
            
            
            specCreation(fvars);
            
            if (!fvars.hasOwnProperty("noDOM")) {
                
                var inALittleBit:Timer = new Timer(INI_LAG_TIME, 1);
                inALittleBit.addEventListener(TimerEvent.TIMER_COMPLETE, domexSetup, false, 0, true);
                inALittleBit.start();
            }
            
        }
        
        
        private function specCreation(theSpecs:Object = null):void
        {
            
            if (!styleSpecs) styleSpecs = new Object();
            
            
            if (theSpecs != null) {
                for (var sc:int = 0; sc < specs.length; sc++)
                { if (theSpecs.hasOwnProperty(specs[sc])) styleSpecs[specs[sc]] = theSpecs[specs[sc]]; }
            }
            
        }
        
        
        
        private function loadAnRssFeedXML(theURL:String = null, divToPutInto:String = null, 
									feedStyles:Object = null):void
        {
            if (theURL != null) rssURL = theURL;
            if (divToPutInto != null) wrapperDivID = divToPutInto;
            if (feedStyles != null) specCreation(feedStyles);
            LoadSomeXML.freshXMLFile(xmlURL, xmlLoadComplete, xmlLoadError, true);
        }
        
        private function domexSetup(e:TimerEvent):void
        {
	    /* dont use 'class' at the end of your swfs id */
            var ider:String = DOMEx.idGet().replace("/clas[s]{1}$/", ""); 
            if(DOMEx.addCall("domexRssFunctions", new DOMEx(this).invokeViaJavaScript))
            {DOMEx.makeMasterTalk("domexRSS", "domexRssFunctions", ider);}    
        }
        
        
        private function xmlLoadComplete(e:Event):void
        {
            
            theXML = new XML(e.target.data);
	    if (memoryHolder.indexOf(wrapperDivID) == -1) {
	    	memoryHolder.push(wrapperDivID);memoryHolder.push(theXML);
	    }
	    else {
		memoryHolder[memoryHolder.indexOf(wrapperDivID)+1] = theXML;
	    }
	    giveFeedStyle(wrapperDivID);
            
        }


	private function feedStyleChangeSteps(feedStyleSpecs:Object, divID:String):void
	{
	    establishFeedStyles(feedStyleSpecs);
	    applyFeedStyles(divID);
	} 


	private function giveFeedStyle(whichFeedID:String):void
	{

		var theChosenXML:XML;
	    if (memoryHolder.length >= 2 && memoryHolder.indexOf(whichFeedID) != -1) {
		theChosenXML = memoryHolder[memoryHolder.indexOf(whichFeedID)+1];
	    }
	    else {
		if (theXML) { theChosenXML = theXML; } else { throw new Error("No xml feed loaded."); }
	    }


	    var wholeStyle:String = (styleSpecs && styleSpecs.hasOwnProperty("overallFeedStyle")) ?
            			     styleSpecs.overallFeedStyle : DEFAULT_overallFeedStyle;
            
            var holderDiv:String = "/n<div id='feedHolder' style='"+wholeStyle+"'>";
            
            
            var linkStylers:String = (styleSpecs && styleSpecs.hasOwnProperty("linkDivStyle")) ?
            			styleSpecs.linkDivStyle : DEFAULT_linkDivStyle;
            
            var linkDivs:String = "<div style='"+linkStylers+"'>";
            
            
            var titleStylers:String = (styleSpecs && styleSpecs.hasOwnProperty("titleStyle")) ?
            			styleSpecs.titleStyle : DEFAULT_titleStyle;
            
            var titleDivs:String = "<div style='"+titleStylers+"'>";
            
            var descriptionStylers:String = (styleSpecs && styleSpecs.hasOwnProperty("descriptionStyle")) ?
            			styleSpecs.descriptionStyle : DEFAULT_descriptionStyle;
            
            var descriptionDivs:String = "<div style='"+descriptionStylers+"'>";
            
            
            var linkAStylers:String = (styleSpecs && styleSpecs.hasOwnProperty("linkStyle")) ?
            			styleSpecs.linkStyle : DEFAULT_linkStyle;
            			
            
            
            var rssItems:XMLList = theChosenXML.child("*").child("item");
            
            for each(var xi:XML in rssItems)
            {
                
                var titler:String = xi.title.toString();
                var descriptioner:String = xi.description.toString();
                var linker:String = "<a href='"+xi.link.toString()+"' style='"+linkAStylers+"'>"+
                xi.link.toString()+"</a>";
                
                holderDiv += "/n" + titleDivs + titler + "<br /></div>/n" + linkDivs + linker + "</div>/n" +
                	     descriptionDivs + descriptioner + "<br /><br /></div>/n";
                
            }
            
            holderDiv += "</div>/n";
            
            
            var outputRss:XML = 
            <script>
            <![CDATA[
            function(theID, theContent) {
                
                function putRss(ider, contenter) {
                    
                    document.getElementById(ider).innerHTML = contenter;
                }
                
                putRss(theID, theContent);
                
            }
            ]]>
            </script>;
            
            DOMEx.call(outputRss, whichFeedID, holderDiv);

	}
        
        
        private function xmlLoadError(e:Event):void
        {
            DOMEx.alert("Error loading Rss");
        }
        
        
    }
}