/**
 * Initializes a httpRequest object
 */
function InitializeXMLReader() 
{    
    var httprequest = false
    if (window.XMLHttpRequest) 
    {// if Mozilla, Safari etc        
        httprequest = new XMLHttpRequest();
        if (httprequest.overrideMimeType)
            httprequest.overrideMimeType('text/xml');
    }
    else if (window.ActiveXObject) 
    {// if IE        
        try 
        {
            httprequest = new ActiveXObject("Msxml2.XMLHTTP"); 
        }
        catch (e) 
        {
            try {
                httprequest = new ActiveXObject("Microsoft.XMLHTTP"); 
            }
            catch (e) {}
        }
    }
    return httprequest;    
}

/** 
 * Constructor
 */
function NewsScroller(fileURL, dIndex, divId, divClass, delay, scrollSpeed, linkTarget, logicSwitch)
{   
    this.dataIndex = dIndex;
    
    this.file = fileURL; // File URL
    this.tickerId = divId; // ID of ticker div to display information
    this.delay = delay; // Delay between msg change, in miliseconds.
    this.scrollSpeed = scrollSpeed; // Speed of animation [1..5]
    this.linkTarget = (typeof linkTarget != "undefined") ? linkTarget : "";
    this.logicSwitch = (typeof logicSwitch != "undefined") ? logicSwitch : "";
    this.mouseOverBol = 0; // Boolean to indicate whether mouse is currently over scroller (and pause it if it is)
    this.hiddenDivPointer = 1; // index of message array for hidden div
    this.pointer = 0;
        
    //Arrays to hold each component of an RSS item
    this.title=[];
    this.link=[];
    this.description=[];
    this.pubdate=[];
    
    // Initializing xml reader
    this.xmlDoc = InitializeXMLReader();
    // Initializing div
    document.write('<div id="'+divId+'" class="'+divClass+'" style="position: relative; overflow: hidden"><div class="innerDiv" style="position: absolute; width: 100%" id="'+divId+'1"><span class="rssdescription" style="position: absolute">Initializing...</span></div><div class="innerDiv" style="visibility: hidden" id="'+divId+'2"></div></div>');
    // Reading content
    this.GetXMLContent();
}

/**
 * Load XML data
 */
NewsScroller.prototype.GetXMLContent = function() {
    if (this.xmlDoc)
    {
        var instanceOfTicker = this;
        this.xmlDoc.onreadystatechange = function () {
			instanceOfTicker.Initialize();
		};
        this.xmlDoc.open("GET", this.file, true);
        this.xmlDoc.send(null);  
    }
}

/**
 * Initializes the div and data retrieval
 */
NewsScroller.prototype.Initialize = function() 
{
    if (this.xmlDoc.readyState == 4) 
    {
        //if request of file completed
        if (this.xmlDoc.status == 200) 
        {            
            //if request was successful
            var xmldata = this.xmlDoc.responseXML
            if(xmldata.getElementsByTagName("newsID").length == 0) 
            {   //if no <item> elements found in returned content   
                document.getElementById(this.tickerId).innerHTML = "Could not initialize data!";
                return;
            }
            var instanceOfTicker = this;

            // initializing feed
            this.feeditems = xmldata.getElementsByTagName("newsID");
            for (var i = 0; i < this.feeditems.length; i++) 
            {            
                this.title[i] = this.feeditems[i].getElementsByTagName("title")[0].firstChild.nodeValue;
                this.description[i] = this.feeditems[i].getElementsByTagName("description")[0].firstChild.nodeValue;
                this.link[i] = this.feeditems[i].getElementsByTagName("url")[0].firstChild.nodeValue;
                this.pubdate[i] = this.feeditems[i].getElementsByTagName("date")[0].firstChild.nodeValue;
            }
                        
            // initializing animation
            this.InitializeAnimation();  
        }
    }
}

/*
 * Initialize scroller method. Get div objects, set initial positions, start up down animation
 */
NewsScroller.prototype.InitializeAnimation = function()
{
    var scrollerInstance = this;
    // retrieving div's info
    this.tickerDiv = document.getElementById(this.tickerId); 
    this.visibleDivTop = parseInt(this.getCSSPadding(this.tickerDiv));
    this.visibleDiv = document.getElementById(this.tickerId + "1");
    this.hiddenDiv = document.getElementById(this.tickerId + "2");

    this.visibleDiv.innerHTML = this.FormatXMLMessage(this.pointer);    
            
    this.GetInLine(this.visibleDiv, this.hiddenDiv);
    this.hiddenDiv.style.visibility = "visible";
    // set width of inner DIVs to outer DIV's width minus padding (padding assumed to be top padding x 2)
//    this.visibleDiv.style.width = this.hiddenDiv.style.width = this.tickerDiv.offsetWidth - (this.visibleDivTop * 2) + "px";

    this.tickerDiv.onmouseover = function()
    {
        scrollerInstance.mouseOverBol = 1;
    }

    this.tickerDiv.onmouseout = function()
    {
        scrollerInstance.mouseOverBol = 0;
    }

    if (window.attachEvent) // Clean up loose references in IE
        window.attachEvent("onunload", 
            function(){
                scrollerInstance.tickerDiv.onmouseover = scrollerInstance.tickerDiv.onmouseout = null;
            }
        )

    setTimeout(function(){
        scrollerInstance.RotateMessage();
    }
    , this.delay);
}

/**
 * Populate the hidden div with the next message before it's visible
 */
NewsScroller.prototype.RotateMessage = function()
{
    var instanceOfTicker = this;
    if (this.mouseoverBol == 1) //if mouse is currently over ticker, do nothing (pause it)
        setTimeout(function() {instanceOfTicker.RotateMessage()} , 100);
    else 
    {   //else, construct item, show and rotate it!    
        var i = this.hiddenDivPointer;
        var ceiling = this.title.length;

        this.visibleDiv.innerHTML = instanceOfTicker.FormatXMLMessage(this.pointer);
        if (this.feeditems.length > 1)
            this.hiddenDiv.innerHTML = instanceOfTicker.FormatXMLMessage(this.hiddenDivPointer);
        else
            this.hiddenDiv.innerHTML = instanceOfTicker.FormatXMLMessage(this.pointer);
        
        this.AnimateUp();

        // Move pointer        
        this.pointer = (this.pointer < this.feeditems.length - 1) ? this.pointer + 1 : 0;
        this.hiddenDivPointer = (this.hiddenDivPointer < this.feeditems.length - 1) ? this.pointer + 1 : 0;
    }    
}

/*
 * Move the two inner divs of the scroller up and in sync
 */
NewsScroller.prototype.AnimateUp = function()
{
    var scrollerInstance = this;
    
    if (parseInt(this.hiddenDiv.style.top) > (this.visibleDivTop + this.scrollSpeed))
    {
        this.visibleDiv.style.top = parseInt(this.visibleDiv.style.top) - this.scrollSpeed + "px";
        this.hiddenDiv.style.top = parseInt(this.hiddenDiv.style.top) - this.scrollSpeed + "px";
        setTimeout(function(){
            scrollerInstance.AnimateUp()
        }
        , 50);
    }
    else
    {
        this.GetInLine(this.hiddenDiv, this.visibleDiv);
        this.SwapDivs();
        setTimeout(function(){
            scrollerInstance.RotateMessage()
        }
        , this.delay);
    }
}

/****************************************************/
/********** HELPER FUNCTIONS ************************/
/****************************************************/

/**
 * Swap between which is the visible and which is the hidden div
 */
NewsScroller.prototype.SwapDivs = function()
{
    var tempContainer = this.visibleDiv;
    this.visibleDiv = this.hiddenDiv;
    this.hiddenDiv = tempContainer;
}

/**
 * Get in line action
 */
NewsScroller.prototype.GetInLine = function(div1, div2)
{
    div1.style.top = this.visibleDivTop + "px";
    div2.style.top = Math.max(div1.parentNode.offsetHeight, div1.offsetHeight) + "px";
}

/**
 * Formats the content
 */
NewsScroller.prototype.FormatXMLMessage = function(pnt)
{
    var instanceOfTicker = this;

    var rssContent = "";
    var linktitle = '<span class="rsstitle">' + this.title[pnt] + '</span>';
    var description = '<span class="rssdescription">' + this.description[pnt] + '</span>';
    var contentDate = '<span class="rssdate">' + this.pubdate[pnt] + '</span>';
    var linkmore = '<span class="rsslink"><a href="../'+ this.link[pnt] + '" target="'+this.linkTarget+'" class="rsslink">more &gt&gt</a></span>';

    // Default - Just return hyperlinked RSS title
    rssContent += linktitle;
    
    // Logic switch - Show date
    if (this.logicSwitch.indexOf("date") != -1)
        rssContent += contentDate;

    // Logic switch - Show description
    if (this.logicSwitch.indexOf("description") != -1) 
        rssContent += "<br />" + description;
    
    // Logic switch - Show "more" link        
    if (this.logicSwitch.indexOf("more") != -1)
        rssContent += linkmore;

    return rssContent;
}

/**
 * Get CSS padding
 */
NewsScroller.prototype.getCSSPadding = function(tickerObj)
{
    // get CSS padding value, if any
    if (tickerObj.currentStyle)
        return tickerObj.currentStyle["paddingTop"];
    else if (window.getComputedStyle) // if DOM2
        return window.getComputedStyle(tickerObj, "").getPropertyValue("padding-top");
    else
        return 0;
}
