// JavaScript Document

var contentData = new Array();
var xmlDoc = null;

/** 
 * Constructor
 */
function NewsScroller(fileURL, divId, divClass, delay, scrollSpeed, linkTarget, logicSwitch){   
    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.js_is_loaded = 0;
    this.number_of_tries = 0;
    
    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="position: absolute; width: 100%; visibility: hidden" id="'+divId+'2"></div></div>');
    if (document.getElementById){    
        NewsScroller.loadXMLFile(fileURL);
        this.do_onJSLoad();    
    }
}

/**
 * Initializes the scrolling scripts.
 */
NewsScroller.prototype.do_onJSLoad = function(){
    var scrollerInstance = this;

    if (contentData.length == 0 && this.number_of_tries < 40) {
        // if Content not yet loaded
        this.number_of_tries++;
        setTimeout( function() {
            scrollerInstance.do_onJSLoad()
        } , 200); // Re-check
    }
    else if (contentData.length > 0) {
        // if content array has loaded
        this.tickerDiv = document.getElementById(this.tickerId); 
        this.visibleDiv = document.getElementById(this.tickerId + "1");
        this.hiddenDiv = document.getElementById(this.tickerId + "2");
        this.visibleDivTop = parseInt(NewsScroller.getCSSPadding(this.tickerDiv));
        
        // set width of inner DIV to outer DIV 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.visibleDiv.innerHTML = formatXMLMessage(this.tickerId, 0, this.linkTarget, this.logicSwitch);
        if(contentData.length > 1)
            this.hiddenDiv.innerHTML = formatXMLMessage(this.tickerId, 1, this.linkTarget, this.logicSwitch);
        else
            this.hiddenDiv.innerHTML = formatXMLMessage(this.tickerId, 0, this.linkTarget, this.logicSwitch);
        
        this.do_onDivsInitialized();
    }
    else {
        document.getElementById(this.tickerId).innerHTML = "<span class='rssdescription'>No data available.</span>";
    }
}

/**
 * Creates Text Divs.
 */
NewsScroller.prototype.do_onDivsInitialized = function(){
    var scrollerInstance = this;
    if (parseInt(this.visibleDiv.offsetHeight) == 0 || parseInt(this.hiddenDiv.offsetHeight) == 0)
        setTimeout(function(){
            scrollerInstance.do_onDivsInitialized();
        }
        , 100);
    else
        this.initialize();
}

/*
 * Initialize scroller method. Get div objects, set initial positions, start up down animation
 */
NewsScroller.prototype.initialize = function(){
    var scrollerInstance = this;
    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.animateUp();
    }
    , this.delay);
}


/**
 * Formats the content
 */
function formatXMLMessage(divid, msgNumber, linkTarget, logicSwitch) {
    var content = contentData[msgNumber];
    var rssContent = "";

    var linktitle = '<span class="rsstitle">' + unescape(content[0]) + '</span>';
    var description = '<span class="rssdescription">' + unescape(content[1]) + '</span>';
    var contentDate = '<span class="rssdate">' + unescape(content[2]) + '</span>';
    var linkmore = '<span class="rsslink"><a href="../'+unescape(content[3])+'" target="'+linkTarget+'" class="rsslink">more</a></span>';

    // Default - Just return hyperlinked RSS title
    rssContent += linktitle;
    
    // Logic switch - Show date
    if (logicSwitch.indexOf("date") != -1)
        rssContent += contentDate;

    // Logic switch - Show description
    if (logicSwitch.indexOf("description") != -1) 
        rssContent += "<br />" + description;
    
    // Logic switch - Show "more" link        
    if (logicSwitch.indexOf("more") != -1)
        rssContent += linkmore;

    return rssContent;
}

/*
 * 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);
    }
}

/**
 * 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";
}

/**
 * Populate the hidden div with the next message before it's visible
 */
NewsScroller.prototype.rotateMessage = function(){
    var scrollerInstance = this;
    if (this.mouseOverBol == 1) // if mouse is currently over scoller, do nothing (pause it)
        setTimeout(function(){
            scrollerInstance.rotateMessage()
        }
        , 100);
    else{
        var i = this.hiddenDivPointer;
        var ceiling = contentData.length;
        this.hiddenDivPointer = (i + 1 > ceiling - 1) ? 0 : i + 1;
        this.hiddenDiv.innerHTML = formatXMLMessage(this.tickerId, this.hiddenDivPointer, this.linkTarget, this.logicSwitch);
        this.animateUp();
    }
}

/**
 * Returns the data as an array
 */
function getXMLContent() {
    var rootObj = xmlDoc.documentElement;
    if(rootObj == null || typeof rootObj == 'undefined')    
        if(xmlDoc.responseXML != null)
            rootObj = xmlDoc.responseXML.documentElement;    

    var news = new Array(); // Initializing the news array.
    if(rootObj != null) {        
        // Iterating over nodes.
        for (var i =0; i < rootObj.childNodes.length; i++) {
            var child = rootObj.childNodes.item(i); // Retrieving current child.
            var temp = new Array(); // Initializing temporary array to hold node values.
            
            // Iterating over node properties.
            for (var j = 0; j < child.childNodes.length; j++) { 
                var item = child.childNodes.item(j); // Now that we get the current item
                if (item.nodeType == 1) { // Test to check if it is an ELEMENT
                    temp[j] = item.childNodes[0].nodeValue;
                }
            }
            trim(temp);
            news[i] = temp;
        }
    }
    trim(news); // trimming current array
    contentData = news;    
}

/**
 * Reads an XML file and returns its DOM object
 */
NewsScroller.loadXMLFile = function(fileURL) {    
    // Microsoft's API for Internet Explorer
    if (window.ActiveXObject)
    {
        // Create a new XML document
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); 
        // Specify what should happen when it finishes loading
        xmlDoc.onreadystatechange = function () {
			if (xmlDoc.readyState == 4) getXMLContent();
		};
        xmlDoc.load(fileURL);		
    }
    else if (window.XMLHttpRequest) // branch for native XMLHttpRequest object :: Google Chrome / Mozilla / Opera
    {
        xmlDoc = new XMLHttpRequest();
        xmlDoc.onreadystatechange = getXMLContent;
        xmlDoc.open("GET", fileURL, true);
        xmlDoc.send(null);         
    }
}

/**
 * Trims the current array
 */
function trim(array) {
	var tmp = new Array();
	
	for(i = 0 ; i < array.length; i++) {
		if(array[i] != '' && (typeof array[i]!="undefined")) {
			tmp[tmp.length] = array[i];
		}
	}
	
    array.length = tmp.length;
	
	for(i = 0; i < tmp.length; i++) {
		array[i] = tmp[i];
	}
		
	return array;
}

/**
 * Get CSS padding
 */
NewsScroller.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;
}

