﻿// JScript File

function Item(node)
{
    // Public Members
    this.title = GetElementValue(node, "*", "title", "");
    this.srcUrl = GetElementValue(node, "*", "link", "");
    this.pubDate = GetElementValue(node, "*", "pubDate", "");
    this.imgUrl = GetElementValue(node, "http://search.yahoo.com/mrss/", "content", "url");
    this.description = GetElementValue(node, "http://search.yahoo.com/mrss/", "description", "");
    this.keywords = GetElementValue(node, "http://search.yahoo.com/mrss/", "keywords", "");
    this.thumbnail = GetElementValue(node, "http://search.yahoo.com/mrss/", "thumbnail", "url");
    this.language = GetElementValue(node, "http://purl.org/dc/terms/", "language", "");
    this.publisher = GetElementValue(node, "http://purl.org/dc/terms/", "publisher", "");
    this.embedCode = GetElementValue(node, "*", "embedcode", "");
    this.rank = GetElementValue(node, "*", "rank", "");
    this.itemId = GetElementValue(node, "*", "itemid", "");
    this.categoryId = GetElementValue(node, "*", "catid", "");
    this.providerId = GetElementValue(node, "*", "pid", "");
    this.contentId = GetElementValue(node, "*", "ctid", "");
    this.pubts = GetElementValue(node, "*", "pubts", "");
    this.provider = GetElementValue(node, "*", "provider", "");
    this.category = GetElementValue(node, "*", "category", ""); 
    
    // Private Functions
    function GetElementValue(node, ns, element, attribute)
    {
        var val = "";
        var elementRoot;
        
        if(typeof(node.getElementsByTagNameNS) == "undefined")
        {
            return getElementsByTagNameNSWrapper(node, ns, element, attribute);
        }
        
        if (node != null)
        {
            if (node.getElementsByTagNameNS(ns, element).length != 0)
            {
                elementRoot = node.getElementsByTagNameNS(ns, element);
                
                if (attribute == "")
                {
                    if (elementRoot != null && elementRoot.length != 0 && elementRoot[0].childNodes.length > 0)
                        val = elementRoot[0].childNodes[0].nodeValue;
                   
                    else if (elementRoot.length > 1)
                    {
                        if (elementRoot != null && elementRoot.length != 0 && elementRoot[1].childNodes.length > 0)
                            val = elementRoot[1].childNodes[0].nodeValue;
                    }
                }
                else 
                {
                    if (elementRoot != null && elementRoot[0].getAttribute(attribute))
                        val = elementRoot[0].getAttribute(attribute);
                }
            }
        }
        return val;
    }
    function getElementsByTagNameNSWrapper(node, ns, element, attribute)
    {
        var val = "";
        var elementRoot;
        
        if ( ns == "http://search.yahoo.com/mrss/")
            element = "media:" + element;
        if (ns == "http://purl.org/dc/terms/")
            element = "dcterms:" + element;
        
        if (node != null)
        {
            if (node.getElementsByTagName(element).length != 0)
            {
                elementRoot = node.getElementsByTagName(element);
                
                if (attribute == "")
                {
                    if (elementRoot != null && elementRoot.length != 0 && elementRoot[0].childNodes.length > 0)
                        val = elementRoot[0].childNodes[0].nodeValue;
                }
                else 
                {
                    if (elementRoot != null && elementRoot[0].getAttribute(attribute))
                        val = elementRoot[0].getAttribute(attribute);
                }
            }
        }
        return val;
    }
}

function HeadlineModule()
{
    // Globals
    var PIXSY_XML_FEED_URL = "http://xml.pixsy.com/";
    //var PIXSY_XML_FEED_URL = "http://xml-beta.pixsy.com/";
    //var PROXY_URL = "StreamingProxy.ashx";
    var PROXY_URL = "AjaxProxy.ashx";
    var DELAY = 5; // timer delay between switching results, in seconds
    
    // Internal Shorthand
    var Dom = YAHOO.util.Dom;
    var Anim = YAHOO.util.Anim;
    var Event = YAHOO.util.Event;
    function $(el)
    {
        return Dom.get(el);
    }

    // Private Members
    var currentFrame;
    var maxFrames;
    var title;
    var xmlDoc;
    var spotlight;
    var imgHighlight;
    var txtHighlight;
    var resultsFrame;
    var slide;
    var slideArry;
    var slideLen;
    var fadeInAnim;
    var fadeOutAnim;
    var slideLeft;
    var slideRight;
    var resultsArry;
    var imgArry;
    var array;
    var collection;
    var fadeDuration = 5;
    var auto = true;
    var autodelay = 5;
    var _self = this;
    var resultsLoaded = false;
    
    // Public/Privileged methods
    this.init = function(nResults, params, responseType)
    {   
        var that = this;   
        currentFrame = 1;
        maxFrames = 1;
    
        var container = $("ModuleContainer");
        var element;
        
        element = document.createElement("div");
        element.setAttribute("id", "Spotlight"); 
        container.appendChild(element);
        
        element = document.createElement("div");
        element.setAttribute("id", "ThumbnailsContainer");
        container.appendChild(element);
        
        container = $("Spotlight");
        
        element = document.createElement("div");
        element.setAttribute("id", "SpotlightContent");
        element.onmouseover = function() { that.stop(); };
        element.onmouseout = function() { that.auto(); };
        container.appendChild(element);
        
        container = $("ThumbnailsContainer")
        
        element = document.createElement("img");
        element.setAttribute("id", "LSlideBttn");
        element.setAttribute("src", "images/master/leftScroll.jpg");
        element.onclick = function() { that.move(-1); };
        element.onmouseover = function() { this.src = "images/master/leftScrollHover.jpg"; };
        element.onmouseout = function() { this.src = "images/master/leftScroll.jpg"; };
        container.appendChild(element);
        
        element = document.createElement("div");
        element.setAttribute("id", "Thumbnails");
        container.appendChild(element);
        
        element = document.createElement("img");
        element.setAttribute("id", "RSlideBttn");
        element.setAttribute("src", "images/master/rtScroll.jpg");
        element.onclick = function() { that.move(1); };
        element.onmouseover = function() {this.src = "images/master/rtScrollHover.jpg";};
        element.onmouseout = function() { this.src = "images/master/rtScroll.jpg"; };
        container.appendChild(element);
        
        container = $("Thumbnails");
        
        element = document.createElement("div");
        element.setAttribute("id", "ThumbnailSlide");
        container.appendChild(element);
        
        
        /** Testing buttons **/
        /*element = document.createElement("div");
        element.setAttribute("id", "test");
        container.appendChild(element);
        
        var test = $("test");
        test.innerHTML = "<input type='button' value='left' onclick='module.move(-1);' /><input type='button' value='right' onclick='module.move(1);' />";*/
        
        /** End testing buttons **/
        
        container = $("SpotlightContent");
        element = document.createElement("div");
        element.setAttribute("id", "SpotlightImg");
        container.appendChild(element);
        
        element = document.createElement("div");
        element.setAttribute("id", "SpotlightTxt");
        container.appendChild(element);
        
		module.load();
		module.loadResults(nResults, params, responseType);
    }
    
    this.load = function()
    {
        spotlight = $("SpotlightContent"); 
        imgHighlight = $("SpotlightImg");
        txtHighlight = $("SpotlightTxt");
        resultsFrame = $("ThumbnailSlide");
        var attributesL = { left: { by: 505 } };
        var attributesR = { left: { by: -505 } };
        
        var fdinAttributes = { opacity: { to: 1, from: 0 } };
        var fdoutAttributes = { opacity: { to: 0, from: 1 } };
        
        fadeInAnim = new Anim(spotlight, fdinAttributes, .75);
        fadeOutAnim = new Anim(spotlight, fdoutAttributes, .75);
        slideLeft = new Anim(resultsFrame, attributesL, 2.5);
        slideRight = new Anim(resultsFrame, attributesR, 2.5);
    }
    
    function doNothing()
    {
    }
    
    this.onHover = function(index)
    {
        this.stop();
        if (resultsLoaded)
            setPausedHighlight(resultsArry[index], index);
    }
    
    this.onSelect = function()
    {
    }
    
    this.move = function(direction)
    {   
        if (resultsLoaded)
        {
            var pos = resultsFrame.posX;
            if (direction < 0)
            {
                if (resultsFrame.offsetLeft < 0)
                {
                    slideLeft.animate();
                    currentFrame -= 1;
                }
            }
            else // direction == "right"
            {
                if (resultsFrame.offsetLeft > ((maxFrames - 1) * -505))
                {
                    slideRight.animate();
                    currentFrame += 1;
                }
            }
        }
    }

    // Private methods
    this.loadResults = function(nResults, params, responseType)
    {
        var explicit;
        if (Cookie.get("explicit"))
            explicit = Cookie.get("explicit");
        if (explicit == "yes")
            params += "&ff=1";
        if (nResults != "")
            params += "&ps=" + nResults;
        //var url = PROXY_URL + "?url=" + PIXSY_XML_FEED_URL + escape(params) + "&type=" + escape(responseType);
        var url = PROXY_URL + "?url=" + escape(PIXSY_XML_FEED_URL + "?psg=AC70711B-1768-48DE-A9E0-695C55A78143&lang=en&" + params + "&format=pixsymrss") + "&type=" + escape("text/xml"); //&format=pixsymrss&media=jpg,png,gif
        loadXml(url);
    }
    
    function loadXml(url)
    {
        xmlhttp = null;
        if (window.XMLHttpRequest)
        {   // code for all new browsers
            xmlhttp = new XMLHttpRequest();
        }
        else if (window.ActiveXObject)
        {   // code for IE5 and IE6
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (xmlhttp != null)
        {
            xmlhttp.onreadystatechange = function() { loadResponse(xmlhttp); };
            xmlhttp.open("GET",url,true);
            xmlhttp.send(null);
        }
        else
        {
            //alert("Your browser does not support XMLHTTP.");
        }
    }

    function loadResponse(xmlhttp)
    {
        if (xmlhttp.readyState==4)
        {   // 4 = "loaded"
            if (xmlhttp.status==200)
            {   // 200 = OK
            
                // Check for ability to parse DOM
                if(typeof(DOMParser) == 'undefined') 
                {
                    DOMParser = function() {}
                    DOMParser.prototype.parseFromString = function(str, contentType) 
                    {
                        if(typeof(ActiveXObject) != 'undefined') 
                        {
                            var xmldata = new ActiveXObject('MSXML.DomDocument');
                            xmldata.async = false;
                            xmldata.loadXML(str);
                            return xmldata;
                        }
                    }
                }
                
                xmlDoc = (new DOMParser()).parseFromString(xmlhttp.responseText, "text/xml");
                if (xmlDoc)
                {
                    resultsLoaded = true;
                    setResults(xmlDoc.documentElement);
                }
            }
            else
            {
                //alert("Problem retrieving XML data");
            }
        }
    }
    
    function setResults(xmlDoc)
    {
        var html;
        var itemcount = 0;
        if (xmlDoc == null)
            html = "<div style='color:red;padding: 10px;'>Feed error.</div>";
        else
        {
            var err = GetElementValue(xmlDoc, "error");
            
            if (err != "")
                html = "<div style='color:red; padding: 10px;'>Error: " + err + "</div>";
            
            else
            {
                var items = xmlDoc.getElementsByTagName("item");
                var html = "";

                itemCount = items.length;
                maxFrames = itemCount/5;
                var len = 5 + (itemCount * 107);
                
                resultsFrame.style.width = len + "px";
                resultsFrame.style.position = "relative";
                resultsFrame.style.overflow = "hidden"; 

                if (itemCount > 0)
                {
                    /* For now, set max number of thumbnails to 5. Will change later*/
                    //itemCount = 5;
                    resultsArry = new Array(itemCount);
                    imgArry = new Array(itemCount);
                    
                    var item;
                    for (var i = 0; i < itemCount; i++)
                    {
                        item = new Item(items[i]);                   
                        html += initThumbs(item, i);
                        resultsArry[i] = item;
                        var img = new Image();
                        if (item.imgUrl != "")
                            img.src = item.imgUrl;
                        else
                            img.src = item.thumbnail;
                        
                        imgArry[i] = img;
                    }
                }
                else
                {
                    html = "<div style='padding: 10px;'>Sorry, no results found.</div>";
                }
            }
        }
        resultsFrame.innerHTML = "<ul id='inner'>" + html + "</ul>";
        slide = $("inner");
        collection = slide.getElementsByTagName("li");
        if (resultsLoaded)
        {
            setHighlight(resultsArry[0], 0);
        }
    }
    
    function initThumbs(item, index)
    {   
        var html;
        /*if (document.images)
        {
            var img = new Image();
            if (item.imgUrl != "")
                img.src = item.imgUrl;
            else
                img.src = item.thumbnail;
        }*/
        var imgSrc = item.thumbnail;
        
        /*if (item.imgUrl != "")
            imgSrc = item.imgUrl;*/
        
        html = "<li value='" + item.itemId + "' class='thumbnail'>";
        html += "<a href='" + createDetailLink(item.itemId, item.srcUrl) + "' onmouseover='module.onHover(" + index + ");' onmouseout='module.auto()' ><img class='list_image_blend' src='" + imgSrc + "' id='img" + item.itemId + "' /></a>";
        html += "</li>";
        
        return html;
    }
    
    function createDetailLink(itemId, url)
    {
        var html = "";
        //<a href='./detailframe.aspx?i=itemid&src=q_s&rids=RelatedIds&url=templatelink'
        html += "detailframe.aspx?i=" + itemId + "&src=" + window.location.href + "&url=" + url;
        
        return html;
    }
    
    function setBorder(index)
    {
        collection[index].style.backgroundColor = "#81c8f7";
    }
    
    function removeBorder()
    {
        for (var i = 0; i < collection.length; i++)
            collection[i].style.backgroundColor = "transparent";
    }
    
    this.auto = function()
    {
	    resultsFrame.timer = setInterval(function(){ cycle(1) }, autodelay*1000);
	}
    
    function fadeIn(item, index)
    {
        fadeInAnim.animate();
        var img;
        var imgSrc;
        var style = "";
        var imgW, imgH;
        
        if (item.embedCode != null)
        {
            imgSrc = item.thumbnail;
            img = new Image();
            img.src = imgSrc;
            if (img.width > img.height)
            {
                imgW = img.width * 2;
                if (imgW > 274)
                    imgW = 274;
                style = "style='width:" + imgW + "px;'"
            }
            else
            {
                imgH = img.height * 2;
                style = "style='height:" + imgH + "px;'"
            }
        }
        else
        {
            if (item.imgUrl != null)
            {
                imgSrc = item.imgUrl;
                img = new Image();
                img.src = imgSrc;
            }
            else
            {
                imgSrc = item.thumbnail;
                img = new Image();
                img.src = imgSr;c
                if (img.width > img.height)
                {
                    imgW = img.width * 2;
                    if (imgW > 274)
                        imgW = 274;
                    style = "style='width:" + imgW + "px;'"
                }
                else
                {
                    imgH = img.height * 2;
                    style = "style='height:" + imgH + "px;'"
                }
            }
        }
        //' onmouseover='module.stop()' onmouseout='module.auto()
        imgHighlight.innerHTML = "<a href='" + createDetailLink(item.itemId, item.srcUrl) + "'><img src='" + imgSrc + "' id='" + item.itemId + "' " + style + " /></a>";
        txtHighlight.innerHTML = getContext(item);
    }
    
    function fadeOut()
    {
        removeBorder();
        fadeOutAnim.animate();
    }
    
    function setHighlight(item, index)
    {
        clearInterval(resultsFrame.timer);
        if ($(item.itemId))
            return;
        
        if (imgHighlight.innerHTML != "")  
            fadeOut();    
            
        setBorder(index);
        spotlight.timer = setTimeout(function(){fadeIn(item, index);}, .75 * 1000);
        module.auto();
    }
    
    function setPausedHighlight(item, index)
    {
        clearInterval(resultsFrame.timer);
        if ($(item.itemId))
            return;
        
        if (imgHighlight.innerHTML != "")  
            fadeOut();    
            
        setBorder(index);
        spotlight.timer = setTimeout(function(){fadeIn(item, index);}, .75 * 1000);
    }
    
    function getContext(item)
    {
        var context = "";
        
        context += "<div class='descTitle'><a href='" + createDetailLink(item.itemId,item.srcUrl) + "'>" + trimText(item.title, 100) + "</a></div>";
        context += "<div class='descPubDate'><a title='See more content from " + item.provider + "' href='search.aspx?pid=" + item.providerId + "'><b>" + item.provider + "</b></a> - " + formatDate(item.pubDate) + "</div>";
        context += "<div class='descCategory'><a title='See more content from the " + item.category + " category' href='search.aspx?catid=" + item.categoryId + "'><b>" + item.category + "</b></a></div>";
        context += "<div class='descContext'>" + trimText(item.description, 125) + "</div>";
        context += "<div class='moreLink'><a href='" + createDetailLink(item.itemId, item.srcUrl) + "'>(More Details)</a>";
        
        return context;
    }
    
    /**************************************************************************/
    
    function cycle(direction)
    {
        if (resultsLoaded)
        {
            var c = 0;
            var spotlightImg = imgHighlight;
            for (index in resultsArry)
            {
                if(resultsArry[index].itemId == spotlightImg.firstChild.firstChild.id)
                    c = index;
                //collection[c].style.border = "solid 2px black";
            }
            if(resultsArry[parseInt(c) + direction])
            {
                var nextEl = parseInt(c) + direction;
                setHighlight(resultsArry[nextEl], nextEl);
            }
            else // we are at the end of the slide
            {   
                if(direction == 1) // at last slide, return to first
                    setHighlight(resultsArry[0], 0);
                else // at first element (going backwards) go to last item
                    setHighlight(resultsArry[resultsArry.length - 1], resultsArry.length - 1);
            }
        }
    }
	
	this.stop = function()
	{
	    clearTimeout(resultsFrame.timer);
	}
    
    /**************************************************************************/
  
    function GetElementValue(fromNode, elementName) 
    {
        var val = "";
        if (fromNode != null)
        {
            var elementRoot = fromNode.getElementsByTagName(elementName);

            if (elementRoot != null && elementRoot.length != 0 && elementRoot[0].childNodes.length > 0)
            {
                val = elementRoot[0].childNodes[0].nodeValue;
            }
        }
        return val;
    }
    function trimText(text, len)
    {
        var trimmed = "";
        if (text)
        {
            trimmed = (text.length > len ? text.substring(0, len) + "..." : text);
        }
        return trimmed;
    }

    function formatDate(pubdate)
    {
        var date = "";
        if (pubdate.length > 9)
        {
            date = pubdate.substring(5 , 7) + "/" + pubdate.substring(8 , 10) + "/" + pubdate.substring(0 , 4);
        }
        return date;
    }
    
}

/** PIXSY GLOBAL OBJECT *******************************************************/

if (typeof PIXSY == "undefined" || !PIXSY){
    var PIXSY = {};
}


