///* Relegence API Functions */
var defaultRelavancy="0";
var riverCache = [];
var pauseRiverWidget = "";
var riverCacheLength = 0;
var storedRelavancy = "";
var storedCluster = "on";//"off";//"on";
var refreshData = "true";
var relatedInfoDiv = "";
var currentDisplayedRelated = "";
var currentShowTab = 5;
var currentFilterSource = "";
var currentRiverSize = 0;
var currentHoverID = 0;
var currentTicker = "";
var currentCountry = "USA";
var currentSeoname = "";
var currentTopicID = 0;
var curPage="0";
var pgIndicator="";
var customBoxFlag="0"; //custon Box hidden by default : keep showing the headlines/relatedartiles box on hover

/** 
 * RelegenceNews is an object holding the news fields that make up a news object
 **/
function setCustomBoxFlag(flag){
    customBoxFlag=flag;
    if(flag==1){
       hideRelated();
        //hideheadlines();
    }
}

function RelegenceNews(title) {
	this.winID = "";
    this.title = title;
    this.source = "";
    this.newsDate = "";
    this.mediaType = "";
    this.storyURL = "";
    this.firstLine = "";
    this.topicID = "";
    this.relevancy = "";
    this.related = "false";
    this.formattedDate = "";
    this.formattedDateTZ = "";
    this.sourceGroup = "";
    this.assetID = "";
    this.srcGroupArray = new Array();
    this.srcGrpRelated = new Array();
    this.storyFullDate = "";
    this.parseRelatedCount = function(relatedCount) { 
        for (var i=0; i< relatedCount.length; i++) {
            var related = relatedCount[i];
            this.srcGroupArray[i] = related.sourceGroupID;
            this.sourceGroup = related.sourceGroupID;
        }
    };
    
    this.parseAllRelated = function(relatedCount) {
        var k=0;
        for (var i=0; i< relatedCount.length; i++) {
            var related = relatedCount[i];
            if (related.assetCount > 0) {
                var relObj = new Object();
                relObj.sourceGroup = related.sourceGroupID;
                relObj.relatedCount = (related.assetCount);
                this.srcGrpRelated[k] = relObj;
                k++; 
            }
        }
    };
    this.sourceInGroups = function(filter) {
        var fParts = filter.split(',');
        for (var i=0; i < fParts.length; i++) {
            for (var k=0; k<this.srcGroupArray.length; k++) {
                if (fParts[i] == this.srcGroupArray[k]) {
                    return true;
                }
            }
        }
        return false;
    };
    
     this.relatedCountGroups = function(filter) {
        var fParts = filter.split(',');
        total_count = 0;
        for (var i=0; i < fParts.length; i++) {
            for (var k=0; k<this.srcGrpRelated.length; k++) {
                if (fParts[i] == this.srcGrpRelated[k].sourceGroup) {
                    total_count = total_count + this.srcGrpRelated[k].relatedCount;
                }
            }
        }
        return total_count;
    };
    
    this.getFormattedDateTZ = function() {
        this.getFormattedDate();
        return this.formattedDateTZ;
       
    };
    
    this.getFormattedDate = function() {
       if (this.formattedDate != "") {
           return this.formattedDate;
       }
       this.formattedDate = formatRelegenceDate(this.newsDate, "false");
       this.formattedDateTZ = formatRelegenceDate(this.newsDate, "true");
      return(this.formattedDate); 
    };
  
		       
   this.setStoryURL = function(urlStr) {
        var decodedUrl = decodeURIComponent(urlStr);
		var indx = decodedUrl.toLowerCase().indexOf("http://");
		if (indx < 0 ) {

		    // We have a relative url. Append channel to it
		    this.storyUrl = RTN_CHANNEL + decodedUrl;
		} else {
		    this.storyUrl = decodedUrl;
		}
   };
   
   this.encodeFirstLine = function(firstline) {
        // URI encoding doesn't encode the single quote so doing this manually. escape works here but not
        // sure if it's what we should use.
        // TODO: look into it.
        if(firstline.match(/'/g))  {
            firstline = firstline.replace(/'/g,"%27");
        }
        if(firstline.match(/ /g))  {
            firstline = firstline.replace(/ /g,"+");
        }
        this.firstLine = firstline;
   };
   
   this.getStoryFullDate = function() {
       if (this.storyFullDate != "") {
           return this.storyFullDate;
       }
       var parsedDate = parseDate(this.newsDate); 
       var articleDate = weekday[parsedDate.getDay()] + ", " + month[parsedDate.getMonth()] + " " + checkTime(parsedDate.getDate()) + ", " + parsedDate.getFullYear();
       return articleDate;
    };
}

function push() {
    var sub = this.length;
    for (var i = 0; i < push.arguments.length; ++i) {
        this[sub] = push.arguments[i];
        sub++;
    }
}
function shift(str) {
  var val = this[0];
  for (var i = 1; i < this.length; ++i) {
    this[i-1] = this[i];
  }
  this.length--;
  return val;
}
function dropOldestStory() {
   return riverCache.shift("story");
}
function storeStory(newsObject) {
// The limit of the cache is probably going to be the no. of stories on a page
  if (riverCache.length >=riverCacheLength) {
  	dropOldestStory();
  } 
   // add  story to array
   var len = riverCache.push([newsObject]);
}

function populateNewsModule(newsObject) {
    if (refreshData == "true") {
	   loadRelegenceCookie();
	}
	if (newsObject.relevancy < storedRelavancy) {
	    newsObject = null;
	    return;
	}
	if (pauseRiverWidget != "") {
	    // store stories different caches for different tabs?
	    storeStory(newsObject);
    } else {
        outputToPage(newsObject);
	}
}
function checkTime(i) {
    if (i<10) 
    {
		i="0" + i
	}
    return i
}

function outputToPage(newsObject) {
	var divs = document.getElementsByTagName("div"); 

	for (var x=0; x<divs.length; x++) {
	    if(divs[x].className == "RiverWidget") {
                var node = divs[x];
                var riverSize = 20;
                var filterSource = "";
                //var dropdowns = "false";
                //var tab = 5;
                var subscription = "";
                var superGroup = "";
                var backgroundColor = "";
                for(var y=0;y < node.attributes.length; y++) {
                    if(node.attributes[y].name.toLowerCase() == 'riversize') {
                        riverSize = node.attributes[y].value;
                                    } else if(node.attributes[y].name.toLowerCase() == 'sourcegroup') {
                        filterSource = node.attributes[y].value;
                                    } else if(node.attributes[y].name.toLowerCase() == 'subscription') {
                        subscription = node.attributes[y].value;
                                    } else if (node.attributes[y].name.toLowerCase() == 'supersourcegroup') {
                                        superGroup = node.attributes[y].value;  
                                    } else if (node.attributes[y].name.toLowerCase() == 'backgroundcolor') {
                                        backgroundColor = node.attributes[y].value;  
                                    }   
                    }
                    //Check if subscription att is == newsObject.winID
                    if (subscription=="" || subscription == newsObject.winID)
                    {
                        if (filterSource == "" || filterSource == "all" || newsObject.sourceInGroups(filterSource)==true) {
                            //populateLastHeadlineDate(node, newsObject.getFormattedDateTZ());
                            populateRiverWidgetOK(node, riverSize, filterSource, newsObject,superGroup);// , backgroundColor);
                        }
                    }
             }
	}
	newsObject = null;
}

function populateLastHeadlineDate(widgetElement, storyDate) {

    var list = widgetElement.getElementsByTagName("span");
    for (var x=0; x < list.length; x++) {
        if (list[x].className == "headlineDate") {
	        list[x].innerHTML = "Last headline was " + storyDate;
		    return;
	    }
    }
}
function relatedArticlesCallback(json) {
    
    if(typeof json.data.metaResponse.queryRslts == "undefined") {
        hideRelated();
        return;
    } 

    var assets = json.data.metaResponse.queryRslts[0].queryRslt.assets;
    var xlen=assets.length;
    if (assets.length > 0) {
        var inHtml = "";
        var lineCount = 1;
        for (var i=0; i<assets.length; i++) {
            var asset = assets[i];
            var firstline="";
            if(asset.snippet==null){
                asset.snippet="";
            }
            if(asset.snippet.match(/<a ([^>]*)>([^<]*)<\/a>/g))
                asset.snippet=asset.snippet.replace(/href/gi,"target=\"_blank\" href");
            if(asset.snippet.match(/<img ([^>]*)>/g)){
                asset.snippet=asset.snippet.replace(/</g,"&lt;");
                asset.snippet=asset.snippet.replace(/>/g,"&gt;");
            }
            firstline=encodeURIComponent(asset.snippet);
            if(firstline.match(/'/g)){
                firstline=firstline.replace(/'/g,"%27");
            }
            if(firstline.match(/ /g)){
                firstline=firstline.replace(/ /g,"+");
            }
            //var xid = asset.asset.id;
            var publishDate= formatRelegenceDate(asset.publishDate);
            inHtml = inHtml + "<li class=\"";
            inHtml = inHtml + asset.asset.id;
            
            inHtml = inHtml +"\">";
            inHtml = inHtml + "<h4><a href=\""+asset.url+"\" onClick=\"javascript:openNewsWindow('"+asset.url+"');return false;\"  onmouseover=\"handleHeadlineHover(event, '"+formatRelegenceDate(asset.publishDate)+"','"+firstline+"','"+currentFilterSource+"','"+currentRiverSize+"')\" onmouseout=\"hideHeadlines()\">" +asset.headline+"</a></h4>";
            inHtml = inHtml + "<div class=\"details\">";
            if( publishDate.indexOf("AM") == -1 && publishDate.indexOf("PM") == -1)
            {
                inHtml = inHtml + "<span class=\"time\" property=\"f:date\">" + formatRelegenceDate(asset.publishDate) + "</span>";
            } else {
                inHtml = inHtml + "<span class=\"time_bold\" property=\"f:date\">" + formatRelegenceDate(asset.publishDate) +"</span>";
            }
            
            inHtml = inHtml + "<span class=\"source\" property=\"f:source\">";
            if (asset.mediaType == "video") {
                inHtml = inHtml + "<img height=\"13\" width=\"18\" src=\""+imgDir+"icons/icon-video.gif\" />";
            }
            inHtml = inHtml + asset.source + "</span></div></li>"; //added break-as

                lineCount = lineCount + 1;
           
        }
           // var relatedUL = document.getElementById("ul"+currentShowTab+currentDisplayedRelated);
           // relatedUL.innerHTML = inHtml;
           
            var tabDiv = document.getElementById("headlines-sub");
            var list = tabDiv.getElementsByTagName("ul");
            for(var x=0; x < list.length; x++) {
                if(list[x].className == "headlines") {
                    ulObj = x;
                    x=list.length;
                }
            }
            list[ulObj].innerHTML = inHtml;  
    }

    
}
function getHeadlinesRelatedArticles(sourceGroups,ticker,exch, topic, filterSource, riverSize, assetID, tab) {
    if (currentDisplayedRelated != "") {
        var relatedUL = document.getElementById("ul"+currentShowTab+currentDisplayedRelated);
        relatedUL.innerHTML = "";
    }
    currentFilterSource = filterSource;
    currentRiverSize = riverSize;
    if (currentDisplayedRelated != assetID) {
        currentDisplayedRelated = assetID;
        //currentShowTab = tab;
        currentTicker = ticker;
        currentCountry = exch;
        currentTopicID = topic;
        getRelatedArticles(5,0,11,sourceGroups,ticker,exch, topic, 'relatedArticlesCallback') ;
    } else {
        //currentShowTab = tab;
        currentDisplayedRelated = "";
    }
}



function populateRiverWidgetOK(widgetElement, riverSize, filterSource, newsObject, superGroup) {
    // Only allow max of riverSize stories
    var list = widgetElement.getElementsByTagName("ul");
    var ulObj = -1;
    var fLine = newsObject.firstLine;
    var related = "";
    var tab = "";
    var relatedTotal = 0;
    relatedTotal = newsObject.relatedCountGroups(superGroup);
    relatedTotal = relatedTotal - 1;
    if (relatedTotal > 0) {
        related = "View all related articles";
    }
	if (refreshData == "true") {
	    loadRelegenceCookie();
	}
    for(var x=0; x < list.length; x++) {
        if(list[x].className == "headlines") {
            ulObj = x;
            x=list.length;
        }
    }
    var liList = null;
    if (storedCluster=="on" && ulObj != -1)
    {
        liList = list[ulObj].getElementsByTagName("li");
        for (var i=0; i<liList.length; i++ ) {
            if(liList[i].className == newsObject.topicID) {
                var removeTopic = liList[i];
                list[ulObj].removeChild(removeTopic);
            }
        }
    }
    
    relegenceTopics=RTN_QUERYTXT;
    var storyHTML ="<li id=\"relegence-"+ list[0].parentNode.id + "-" + newsObject.assetID+"\" class=\""+newsObject.topicID+"\">" + "<h4><a href=\"#\" onClick=\"javascript:openNewsWindow('"+newsObject.storyUrl+"');return false;\" onmouseover=\"handleHeadlineHover(event, '" + newsObject.getFormattedDate() + "','" + fLine + "','"+filterSource+"','"+riverSize+"')\" onmouseout=\"hideHeadlines()\">"+newsObject.title+"</a></h4>" ;
    storyHTML = storyHTML + "<div class=\"details\"><span class=\"time\" property=\"f:date\">" + newsObject.getFormattedDate() + "</span>"

    var related_link = "";
    //if (storedCluster=="on" ) {
       if (currentTicker == "") {
            currentTicker = JS_SYMBOL;
            currentCountry = JS_COUNTRY;
        }
	// REMOVING VIEW ALL RELATED FOR LAUNCH 
        if (relatedTotal > 0) {

            var  urlArr = RTN_QUERYTXT.toString().split(":");
            if(pgIndicator==0)
                related_link = "\/"+urlArr[0]+"-"+urlArr[1]+"\s/"+ENTITY_NAME+"\/"+urlArr[2]+"?selectedTab=snapShot&view=relatedNews&srcGrp="+superGroup+"&TpcId="+newsObject.topicID+"#statsNav"; 
            else
                related_link = "\/"+urlArr[0]+"-"+urlArr[1]+"\s/"+ENTITY_NAME+"\/"+"news?view=relatedNews&srcGrp="+superGroup+"&TpcId="+newsObject.topicID; 
            
            storyHTML = storyHTML+ "&nbsp;"+"<a href=\'"+related_link+"' onmouseover=\"handleRelatedArticlesHover(event,'"+filterSource+"','"+riverSize+"', '"+superGroup+"', '"+relegenceTopics+"','"+JS_COUNTRY+"', '"+newsObject.topicID + "','"+ storedRelavancy+"','"+newsObject.assetID+"')\" > View all related articles </a>  |";
               
        } 
                   
        storyHTML = storyHTML  + "<span class=\"source\" property=\"f:source\">";
        if (newsObject.mediaType == "video") {
            storyHTML = storyHTML + "<img height=\"13\" width=\"18\" src=\""+imgDir+"/icons/icon-video.gif\"/> ";
        }
        storyHTML = storyHTML + newsObject.source +"</span></div>";
        storyHTML = storyHTML + "</li>";
        
        if (ulObj == -1) {
            xHTML = "<ul class=\"headlines\">"  + storyHTML;
            xHTML = xHTML + "</ul>";
            widgetElement.innerHTML += xHTML;
        } else {
            if (liList == null) {
                liList = list[ulObj].getElementsByTagName("li");
            }
            if (liList.length >= riverSize || liList[0].className == "riverEmpty") {
                var elem = liList[liList.length-1];
                list[ulObj].removeChild(elem);
            }
            xHTML = storyHTML;  
            list[ulObj].innerHTML = xHTML + list[ulObj].innerHTML;
       }
       populateLastHeadlineDate(document.getElementById("headlines-sub"), newsObject.getFormattedDateTZ());
       fadeBackground( "relegence-"+ list[0].parentNode.id + "-" + newsObject.assetID.toString() , "#e4f7ff", "#fff" );
}

function populateRiverWidget(widgetElement, riverSize, filterSource, newsObject, superGroup, backgroundColor) {
    // Only allow max of riverSize stories
    var list = widgetElement.getElementsByTagName("ul");
    var ulObj = -1;
    var fLine = newsObject.firstLine;
    var related = "";
    var tabStr = "";
    var tab = "";
    var relatedTotal = 0;
    relatedTotal = newsObject.relatedCountGroups(superGroup);
    relatedTotal = relatedTotal - 1;
    if (relatedTotal > 0) {
        related = relatedTotal + " " + tabStr + "related articles";
    }
	if (refreshData == "true") {
	    loadRelegenceCookie();
	}
    for(var x=0; x < list.length; x++) {
        if(list[x].className == "headlines") {
            ulObj = x;
            x=list.length;
        }
    }
    var liList = null;
    if (storedCluster=="on" && ulObj != -1)
    {
        liList = list[ulObj].getElementsByTagName("li");
        for (var i=0; i<liList.length; i++ ) {
            if(liList[i].className == newsObject.topicID) {
                var removeTopic = liList[i];
                list[ulObj].removeChild(removeTopic);
            }
        }
    }

    var storyHTML ="<li id=\"relegence-"+ list[0].parentNode.id + "-" + newsObject.assetID+"\" class=\""+newsObject.topicID+"\">"
    var related_link = "";
    storyHTML = storyHTML + "<div class=\"headline\"><span class=\"time\">"+newsObject.getFormattedDate()+"</span>";
    storyHTML = storyHTML + "<div class=\"headlineText\">";
    storyHTML = storyHTML + "<a href=\"#\" onClick=\"javascript:openNewsWindow('"+newsObject.storyUrl+"');return false;\" onmouseover=\"handleHeadlineHover(event, '" + newsObject.getFormattedDate() + "','" + fLine + "','"+filterSource+"','"+riverSize+"')\" onmouseout=\"hideHeadlines()\">"+newsObject.title+"</a>" ;
    if (newsObject.mediaType == "video") {
        storyHTML = storyHTML + "<img height=\"13\" width=\"18\" src=\""+imgDir+"/icons/icon-video.gif\"/> ";
    }
    storyHTML = storyHTML + "</div></div>";
    storyHTML = storyHTML + "<div class=\"details\">";
    storyHTML = storyHTML + "<span class=\"source\" property=\"f:source\">" + newsObject.source + "</span>";
    storyHTML = storyHTML + "</div>";
    storyHTML = storyHTML + "</li>";
    if (ulObj == -1) {
        xHTML = "<ul class=\"headlines\">"  + storyHTML;
        xHTML = xHTML + "</ul>";
        widgetElement.innerHTML += xHTML;
    } else {
        if (liList == null) {
            liList = list[ulObj].getElementsByTagName("li");
        }
        if (liList.length >= riverSize || liList[0].className == "riverEmpty") {
            var elem = liList[liList.length-1];
            list[ulObj].removeChild(elem);
		}
        xHTML = storyHTML;  
        list[ulObj].innerHTML = xHTML + list[ulObj].innerHTML;
    }
    if (backgroundColor == 'greyBackg')
      fadeBackground( "relegence-"+ list[0].parentNode.id + "-" + newsObject.assetID.toString() , "#e4f7ff", "#EFF1F0" );
    else  
      fadeBackground( "relegence-"+ list[0].parentNode.id + "-" + newsObject.assetID.toString() , "#e4f7ff", "#fff" );
}



function handleHeadlineHover(e, storyDate, firstLine, filterSource, riverSize) {
    if(customBoxFlag=="1"){
        hideHeadlines();
        return;
    }
    if ((typeof firstLine == "undefined") || (firstLine == null) || (firstLine=="")) {
        return;
    }
    hideRelated();
    pauseRiverWidget = filterSource;
	riverCacheLength = riverSize;
    var infodiv = document.getElementById("headlinesInfo");
    if(infodiv == null) {
        infodiv = document.body.appendChild(document.createElement("div"));
        infodiv_interior = infodiv.appendChild( document.createElement("div") );
        infodiv_interior.className = "interior";
        infodiv.id = "headlinesInfo";
        infodiv.style.position = "absolute";
        infodiv.style.display = "none";
        infodiv.style.left = "-1000px";
        infodiv.style.top = "0";
        infodiv.style.marginTop = "3px";
        infodiv.style.zIndex = "10";
        infodiv.style.font = "11px Arial";    
    }
    if(firstLine.match(/[+]/))  {
   
        firstLine = firstLine.replace(/[+]/g," ");
    }
	var firstLineDecoded = decodeURIComponent(firstLine);
	if (firstLineDecoded.length > RTN_SNIPPET_SIZE) {
	    firstLineDecoded = firstLineDecoded.substring(0, RTN_SNIPPET_SIZE) + "...";
	}
    infodiv.firstChild.innerHTML = storyDate + " " + firstLineDecoded;
    if (!e) e = window.event;
    var targ = e.srcElement || e.target;
    posNode = targ.parentNode.parentNode.getElementsByTagName("DIV")[0];
    xy = findPos(posNode);
    infodiv.style.left = xy[0] + "px";
    infodiv.style.top = xy[1] - ( posNode.parentNode.parentNode.scrollTop - 12  ) + "px";
    infodiv.style.display = "block";
    setTimeout('hideHeadlines()', RTN_HOVER_TIMEOUT);

}

var topX=0;var topY=0;
function handleRelatedArticlesHover(e, filterSource, riverSize, sourceGroups, ticker, exch, topicID, relevancy, storyID) {
    currentTopicID = topicID;
    currentTicker = ticker;
    currentCountry = exch;
    getRelatedArticles(relevancy, 0, 3, sourceGroups, ticker, exch, topicID, "relatedArticlesHoverCallback");
    pauseRiverWidget = filterSource;
    riverCacheLength = riverSize;
    currentHoverID = storyID;
    relatedInfoDiv = document.getElementById("newsRelatedInfo");
    if(relatedInfoDiv == null) {
        relatedInfoDiv = document.body.appendChild(document.createElement("div"));
        relatedInfoDiv.id = "newsRelatedInfo";
        relatedInfoDiv_interior = relatedInfoDiv.appendChild( document.createElement( "div" ) );
        relatedInfoDiv_interior.className = "interior";
        relatedInfoDiv.addEventListener?relatedInfoDiv.addEventListener("mouseout",popdown,false):relatedInfoDiv.attachEvent("onmouseout",popdown);
        relatedInfoDiv.style.position = "absolute";
        relatedInfoDiv.style.display = "none";
        relatedInfoDiv.style.left = "-1000px";
        relatedInfoDiv.style.top = "0";
        relatedInfoDiv.style.marginTop = "5px";
        relatedInfoDiv.style.border = "#ccc";
        relatedInfoDiv.style.zIndex = "10";
        relatedInfoDiv.style.font = "11px Arial";
    }
  
    if(!e)e=window.event;
    //getMouseXY(e);
    var targ=e.srcElement||e.target;
    posNode=targ.parentNode.parentNode.getElementsByTagName("DIV")[0];
    xy=findPosition(posNode);
    topY=xy[1]-(posNode.parentNode.parentNode.scrollTop-12);
    topX=xy[0];
    relatedInfoDiv.style.top=xy[1]-(posNode.parentNode.parentNode.scrollTop-12)+"px";
    relatedInfoDiv.style.left=xy[0]+"px";

}

function popdown(e)
{
	getMouseXY(e);
         var y=parseInt(mousey);
	var x=parseInt(mousex);
	if(clip(x,y)==true)
	{
		return true;
	}
	hideRelated();
	return true;
}

function clip(x,y)
{
	var tmpWidth=topX+relatedInfoDiv.offsetWidth;
	if(x>topX&&x<tmpWidth)
	{
		var tmpHeight=topY+relatedInfoDiv.offsetHeight;
		if(y>topY&&y<tmpHeight)
		{	return true;
		}
	}
	return false;
}

function hideHeadlines() {
    unPauseRiverWidget();
    var infodiv = document.getElementById("headlinesInfo");
    infodiv.style.display = "none";
    infodiv.firstChild.innerHTML = "";
}

function hideRelated() {
    unPauseRiverWidget();
    var infodiv = document.getElementById("newsRelatedInfo");
    if (infodiv != null) {
        infodiv.style.display = "none";
        infodiv.firstChild.innerHTML = "";
    }
}
function unPauseRiverWidget() {
  // read through stories stored and call populate RiverWidget
  var story = dropOldestStory();
  while (story != null) {
	// Do filtering
	outputToPage(story[0]);
    story = dropOldestStory();
  }
  pauseRiverWidget = "";
}

function setRefresh(refresh) {
    refreshData = refresh;
}

function setRtnDaylightSavings(daylight) {
    RTN_DAYLIGHT = daylight;
}
function setRelCookie(relevancy, cluster, newssource, presssource, blogsource, tradesource, regsource)
{
    var the_cookie = "qp_rtn_prefs=";
	var the_cookie = the_cookie + encodeURIComponent("rel_min:"+relevancy+"/rel_max:100/cluster:"+cluster+"/news:"+newssource+"/pr:"+presssource+"/trade:"+tradesource+"/blogs:"+blogsource+"/reg:"+regsource)+";";
    var the_cookie = the_cookie + "path=/;";
	var d = new Date();
    d.setTime(d.getTime()+(365*24*60*60*1000));
	var the_cookie = the_cookie +"expires=" + d + ";";
    document.cookie = the_cookie;
}
function get_cookie ( cookie_name )
{
    var results = document.cookie.match ( cookie_name + '=(.*?)(;|$)' );

    if ( results )
        return ( unescape ( results[1] ) );
    else
        return null;
}
function readTheCookie(the_info)

{

    // load the cookie into a variable and unescape it
    var the_cookie = get_cookie("qp_rtn_prefs");
    if (the_cookie == null) {
       return;
    }
    // separate the values from the cookie name
    var the_values = the_cookie;

    // break each name:value pair into an array

    var separated_values = the_values.split("/");

    // loop through the list of name:values and load
    // up the associate array
    var property_value = "";

    for (var loop = 0; loop < separated_values.length; loop++)

    {
        property_value = separated_values[loop];
        var broken_info = property_value.split(":");
        var the_property = broken_info[0];
        var the_value = broken_info[1];
        the_info[the_property] = the_value;
    }

}

function setPgIndicator(indicator){
    pgIndicator=indicator;
}

function resetCustomPopUp(theform){
    for (var i=0; i<theform.relevancy.length; i++)
    {
        if (theform.relevancy[i].value==storedRelavancy)
        {
            theform.relevancy[i].checked = true;
        }
    }

}
function readCustomizeCookie(theform, newsDef, tradeDef, regDef, prDef, blogDef) {
   
    var cookieInfo = new Array();
    readTheCookie(cookieInfo);
    
    var relevancy = cookieInfo["rel_min"];
    var cluster = cookieInfo["cluster"];
    var newssource = cookieInfo["news"];
    var presssource = cookieInfo["pr"];
    var blogsource = cookieInfo["blogs"];
    var tradesource = cookieInfo["trade"];
    var regsource = cookieInfo["reg"];
    if(typeof relevancy == "undefined"){
        // No cookie so use defaults
		relevancy = "55";
    }
    storedRelavancy=relevancy;
    for (var i=0; i<theform.relevancy.length; i++)
    {
        if (theform.relevancy[i].value==relevancy)
        {
            theform.relevancy[i].checked = true;
        }
    }

    if(typeof cluster == "undefined"){
        cluster = "on";//"off";//"on";
    }

    if(typeof newssource == "undefined"){
        newssource = newsDef;
    }
      if (typeof theform.newssources.length == "undefined") {
        if (theform.newssources.value == newssource) {
            theform.newssources.selected = true;
            theform.newssources.checked = true;
        }
    } else {       
        for (var y=0; y<theform.newssources.length; y++) {
            if (theform.newssources[y].value == newssource) {
                theform.newssources[y].selected = true;
                theform.newssources[y].checked = true;
            }
        }
    }
    if(typeof presssource == "undefined"){
        presssource = prDef;
    }
    if (typeof theform.presssources.length == "undefined") {
        if (theform.presssources.value == presssource) {
            theform.presssources.selected = true;
            theform.presssources.checked = true;
        }
    } else {         
        for (y=0; y<theform.presssources.length; y++) {
            if (theform.presssources[y].value == presssource) {
                theform.presssources[y].selected = true;
                theform.presssources[y].checked = true;
            }
        }
    }
    if(typeof blogsource == "undefined"){
        blogsource = blogDef;
    }
    if (typeof theform.blogsources.length == "undefined") {
        if (theform.blogsources.value == blogsource) {
            theform.blogsources.selected = true;
            theform.blogsources.checked = true;
        }
    } else {       
        for (y=0; y<theform.blogsources.length; y++) {
            if (theform.blogsources[y].value == blogsource) {
                theform.blogsources[y].selected = true;
                theform.blogsources[y].checked = true;
            }
        }
    }

    if(typeof tradesource == "undefined"){
        tradesource = tradeDef;
    }
	if (typeof theform.tradesources.length == "undefined") {
	    if (theform.tradesources.value  == tradesource) {
		    theform.tradesources.selected = true;
            theform.tradesources.checked = true;
	    }
	} else {
    for (y=0; y<theform.tradesources.length; y++) {
        if (theform.tradesources[y].value == tradesource) {
            theform.tradesources[y].selected = true;
            theform.tradesources[y].checked = true;
        }
    }
	}
    if(typeof regsource == "undefined"){
        regsource = regDef;
    }
    if (typeof theform.regsources != "undefined") {
        if (typeof theform.regsources.length == "undefined") {
            if (theform.regsources.value == regsource) {
                theform.regsources.selected = true;
                theform.regsources.checked = true;
            }
        } else {       
            for (y=0; y<theform.regsources.length; y++) {
                if (theform.regsources[y].value == regsource) {
                    theform.regsources[y].selected = true;
                    theform.regsources[y].checked = true;
                }
            }
        }
    }
    if (theform.name != "smallRelegenceForm") {
    var newsEval = "var newsVal = theform.src"+newssource+".value;";
    var tradeEval = "var tradeVal = theform.src"+tradesource+".value;";
    var regEval = "var regVal = theform.src"+regsource+".value;";
    var prEval = "var prVal = theform.src"+presssource+".value;";
    var blogEval = "var blogVal = theform.src"+blogsource+".value;";
    if (newssource != 0)
        eval(newsEval);
    if (tradesource != 0)
    eval(tradeEval);
    if (regsource != 0)
    eval(regEval);
    if (presssource != 0)
    eval(prEval);
    if (blogsource != 0)
    eval(blogEval);
    var spanObj = document.getElementById("newsCount");
    if (typeof spanObj != "undefined") {
        if (typeof newsVal != "undefined") {
            spanObj.innerHTML = "Top " + newsVal + " Selected";
        } else {
            spanObj.innerHTML = "None Selected";
       }
    }
    if (typeof spanObj != "undefined") {
        var spanObj = document.getElementById("tradeCount");
        if (typeof tradeVal != "undefined") {
            spanObj.innerHTML = "Top " + tradeVal + " Selected";
        } else {
            spanObj.innerHTML = "None Selected";
       }

    }
    if (typeof spanObj != "undefined") {
       var spanObj = document.getElementById("regCount");
       if (typeof regVal != "undefined") {
            spanObj.innerHTML = "Top " + regVal + " Selected";
       } else {
            spanObj.innerHTML = "None Selected";
       }

    }
    if (typeof spanObj != "undefined") {
       var spanObj = document.getElementById("prCount");
       if (typeof prVal != "undefined") {
            spanObj.innerHTML = "Top " + prVal + " Selected";
       } else {
            spanObj.innerHTML = "None Selected";
       }

    }
    if (typeof spanObj != "undefined") {
       var spanObj = document.getElementById("blogCount");
       if (typeof blogVal != "undefined") {
            spanObj.innerHTML = "Top " + blogVal + " Selected";
       } else {
            spanObj.innerHTML = "None Selected";
       }

    }
    }
}
// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
if ( get_cookie( name ) ) {
var tmpCookie =  name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
document.cookie = tmpCookie;
}
}
function saveCustomize(theform, newsDef, tradeDef, regDef, prDef, blogDef) {
	    
    Delete_Cookie("qp_rtn_prefs", "/", "aol.com");
    var relevancy = "55";
    for (i=0; i<theform.relevancy.length; i++)
    {
        if (theform.relevancy[i].checked==true)
        {
            relevancy = theform.relevancy[i].value;
        }
    }
    var cluster = "on";//"off";//"on";
    var newssource = newsDef;
    for (y=0; y<theform.newssources.length; y++) {
	if (theform.name == "smallRelegenceForm") {
            if (theform.newssources[y].checked) {
                newssource = theform.newssources[y].value;
            }
        } else {
            if (theform.newssources[y].checked) {
                newssource = theform.newssources[y].value;
            }
        }
    }
    
    var blogsource = blogDef;
    for (y=0; y<theform.blogsources.length; y++) {
        if (theform.name == "smallRelegenceForm") {
            if (theform.blogsources[y].checked) {
                blogsource = theform.blogsources[y].value;
            }
        }else {
            if (theform.blogsources[y].checked) {
                blogsource = theform.blogsources[y].value;
            }
        }
    }
    var presssource = prDef;
    var tradesource = tradeDef;
    var regsource = regDef;
    if (typeof theform.regsources != "undefined") {
        for (y=0; y<theform.regsources.length; y++) {
            if (theform.name == "smallRelegenceForm") {
                if (theform.regsources[y].checked) {
                    regsource = theform.regsources[y].value;
                }
            } else {
                if (theform.regsources[y].checked) {
                    regsource = theform.regsources[y].value;
                }
            }
        }
    }

    //create cookie
	storedRelavancy = relevancy;
	storedCluster = cluster;
	refreshData = "false";
    setRelCookie(storedRelavancy, cluster, newssource, presssource, blogsource, tradesource, regsource);	
	
}

function setDefaultChecked(daformlist, tocheck) {
    for (var y=0; y<daformlist.length; y++) {
        if (daformlist[y].id == "sources_news") {
            daformlist[y].selected = true;
            daformlist[y].checked = true;
        }
    }
}

var custDisplay = "show";
var currentTab = "newsTab";

function showTabSourceList(whichTab) {
	var oldSrcObj = document.getElementById(currentTab);
    oldSrcObj.style.display = "none";
	var srcObj = document.getElementById(whichTab);
	srcObj.style.display = "";
	currentTab = whichTab;
}
function toggleCustomize(divId, hrefID, news, trade, regional, pr, blogs) {
    var divObj = document.getElementById(divId);
    if (custDisplay == "hide") {
        divObj.style.display = "none";
        custDisplay = "show";
		var lnk = document.getElementById(hrefID);
        lnk.innerHTML = "Customize";
        var module_tabs = document.getElementById('NEWSGROUPS');
        if ( module_tabs ) {
          module_tabs.className = "module_tab";
        }
    } else {
        readCustomizeCookie(document.smallRelegenceForm, news, trade, regional, pr, blogs);
        divObj.style.display = "";
        custDisplay = "hide";
		var lnk = document.getElementById(hrefID);
        lnk.innerHTML = "Cancel";
        var module_tabs = document.getElementById('NEWSGROUPS');
        if ( module_tabs ) {
          module_tabs.className = "module_tab expanded_module_tab";
        }
    }

}
var currentSource = "newsAnalysis";

function toggleSource(whichTab) {
	var srcObj = document.getElementById(whichTab);
	if (srcObj.style.display == "") {
	    srcObj.style.display = "none";
	} else {
	    var oldSrcObj = document.getElementById(currentSource);
        oldSrcObj.style.display = "none";
	    srcObj.style.display = "";
	}
	currentSource = whichTab;
}

function loadRelegenceCookie() {
    var cookieInfo = new Array();
    readTheCookie(cookieInfo);
    storedRelavancy = cookieInfo["rel_min"];
    //storedCluster = cookieInfo["cluster"];
    if (typeof storedRelavancy == "undefined")
        storedRelavancy = defaultRelavancy;
    if (typeof storedCluster == "undefined")
        storedCluster = "on";//"off";
    refreshData = "false";
}
function encodeSnippet(snippet) {
    var firstline = "";
    if (snippet.match(/<a ([^>]*)>([^<]*)<\/a>/g))  
        snippet = snippet.replace(/href/gi,"target=\"_blank\" href");
    if (snippet.match(/<img ([^>]*)>/g))  {
        snippet = snippet.replace(/</g,"&lt;");
        snippet = snippet.replace(/>/g,"&gt;");
    }
	firstline = encodeURIComponent(snippet);
	if(firstline.match(/'/g))  {
	    firstline = firstline.replace(/'/g,"%27");
	}
    if(firstline.match(/ /g))  {
	    firstline = firstline.replace(/ /g,"+");
	}
	return firstline;
}
function findPosition(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft,curtop];
}

// attach the cookie init function to the window's load event
window.addEventListener?window.addEventListener("load",loadRelegenceCookie,false):window.attachEvent("onload",loadRelegenceCookie);

//new function with  depricated calls removed
function getRelatedArticles(relevancy, offset, count, sourceGroups, ticker, exch, topicID, callback) {
    
    currentFilterSource = sourceGroups;
    currentRiverSize = count;

    var newsCount = count;//"4";
   // var relevancy=storedRelavancy;
    var fullUrl = RTN_BASE_URL + "getAssetsMetaNonClustered?f=json";
    var srcGrpArray = new Array();
    qTextArray = RTN_QUERYTXT.toString().split(",");
    for (var i=0; i<qTextArray.length; i++) {
        if(appID == "MF"){
                fullUrl = fullUrl + "&qTxt="+decodeURIComponent(qTextArray[i].toUpperCase()) + ".USA";
        }else{
            fullUrl = fullUrl + "&qTxt="+RTN_ENTITY+qTextArray[i];
        }
    }
    if(appID == "MF"){
        fullUrl = fullUrl + "&appId="+appID+"&qTyp=ticker&sHdln=1&fLng=en&dPgOff=0&dPgCnt=" + newsCount + "&fRelMn=" + relevancy;
    }else{
        fullUrl = fullUrl + "&appId="+appID+"&qTyp=entity&sHdln=1&fLng=en&dPgOff=0&dPgCnt=" + newsCount + "&fRelMn=" + relevancy;
    }                                                       
    var srcGrpArray = new Array();
    srcGrpArray = sourceGroups.toString().split(",");
    for (var i=0; i<srcGrpArray.length; i++) {
        fullUrl = fullUrl + "&fSgrp="+srcGrpArray[i];
    }
   fullUrl = fullUrl + "&fTpc="+topicID+"&dPgHnd=0&sPubDt=1&sUrl=1&sMedTyp=1&sSrc=1&sSnipt=1&sTopc=1&c="+callback;
   //fullUrl = fullUrl + "&dPgHnd=0&sPubDt=1&sUrl=1&sMedTyp=1&sSrc=1&sSnipt=1&sTopc=1&c="+callback;
    
    new RelegenceJSONRequest(fullUrl);

}

function getSubscriptionTopic(topic, callback) {
    // First we need to get the company id of the relegence topic
    var fullUrl = RTN_BASE_URL+"getSubscriptionTopic?tickerNews=" + topic.toLowerCase() + ".us&f=json&c="+callback;
    new RelegenceJSONRequest(fullUrl);
}
function getAssetsMetaCannedMovies(qtxt)
{
	//Here's your actuall call to the RDG to get your Movies.
    new RelegenceJSONRequest(RTN_BASE_URL+"getAssetsMetaClustered?f=json&appId=MOVIES&qTxt=movies:title:"+qtxt+"&qTyp=entity&sHdln=1&fLng=en&dPgOff=0&dPgCnt=7&fRelMn=0&fSgrp=3000&fSgrp=3001&sPubDt=1&sUrl=1&sMedTyp=1&sSrc=1&sSnipt=1&sTopc=1&c=getAssetsNewsCallback");
}

function getAssetsMetaCanned(clustered, newsCount, ticker, country, sourceGroup, relMin, beginDate, callback, pageHandle) 
{
    //debugger;
    var fullUrl = RTN_BASE_URL;
    //var fullUrl="/redirect/rdg/"
    if (clustered == "true") {
        fullUrl = fullUrl + "getAssetsMetaClustered?f=json";
    } else {
        fullUrl = fullUrl + "getAssetsMetaNonClustered?f=json";
    }
    if(appID == "MF"){
        fullUrl = fullUrl + "&appId="+appID+"&qTxt="+decodeURIComponent(ticker.toUpperCase()) + "." + country.toUpperCase() +"&qTyp=ticker&sHdln=1&fLng=en&dPgOff=0&dPgCnt=" + newsCount + "&fRelMn=" + relMin;
    }else{
        fullUrl = fullUrl + "&appId="+appID+"&qTxt="+RTN_ENTITY+RTN_QUERYTXT + "&qTyp=entity&sHdln=1&fLng=en&dPgOff=0&dPgCnt=" + newsCount + "&fRelMn=" + relMin;
    }
    var srcGrpArray = new Array();
	srcGrpArray = sourceGroup.toString().split(",");
	for (var i=0; i<srcGrpArray.length; i++) {
	    fullUrl = fullUrl + "&fSgrp="+srcGrpArray[i];
	}
    
    if (beginDate != "") {
        fullUrl = fullUrl + "&fBgnDt="+beginDate;
    } else if (pageHandle > 0) {
        fullUrl = fullUrl + "&dPgHnd=" + pageHandle;
    }
    fullUrl = fullUrl + "&sPubDt=1&sUrl=1&sMedTyp=1&sSrc=1&sSnipt=1&sTopc=1&c="+callback;
    //document.write("fullurl :"+fullUrl);
   // alert(fullUrl);
    new RelegenceJSONRequest(fullUrl);
    
}
function getInitialResponse(){

    var fullUrl = RTN_BASE_URL;
    //var fullUrl="/redirect/rdg/"
    fullUrl = fullUrl + "getAssetsMetaClustered?f=json";
    fullUrl = fullUrl + "&appId="+appID+"&qTxt="+RTN_ENTITY+RTN_QUERYTXT + "&qTyp=entity&sHdln=1&fLng=en&dPgOff=0&dPgCnt=10&fRelMn=55";
    var srcGrpArray = new Array();
    srcGrpArray = mediatypes.srcGroup[1].id.toString().split(",");
    for (var i=0; i<srcGrpArray.length; i++) {
        fullUrl = fullUrl + "&fSgrp="+srcGrpArray[i];
    }
    fullUrl = fullUrl + "&sPubDt=1&sUrl=1&sMedTyp=1&sSrc=1&sSnipt=1&sTopc=1&defer=defer&c="+"getAssetsInitialNewsCallback";
    //alert(fullUrl);
    new RelegenceJSONRequest(fullUrl);
}

function getAssetsInitialNewsCallback(json) 
{
     if(typeof json.data.metaResponse.queryRslts[0].queryRslt.errorCode == "undefined") {
        //if(parseInt(json.response.statusCode) != 200){
        rtnResponseFlag=1;
    
    }else {//if(json.data.metaResponse.queryRslts[0].queryRslt.errorCode == "400"){
        rtnResponseFlag=0;
        alert("Player NOT found in the Relegence Database : Turning off the RTN module for this player");
    }
    //alert("after value rtnResponseFlag in func :"+rtnResponseFlag);
    return parseInt(json.response.statusCode);
   
}


function getXmlHttpRequestObject() {
      if (window.XMLHttpRequest) {
         return new XMLHttpRequest(); //Not IE
      } else if(window.ActiveXObject) {
         return new ActiveXObject("Microsoft.XMLHTTP"); //IE
      } else {
         return null;
      }
   }        


    var rtnReqq=false;

   function handleRtnResponse() {
    //alert(rtnReqq.readyState);
      if (rtnReqq.readyState == 4) {
     // alert(rtnReqq.responseText);
        eval(rtnReqq.responseText);
      }
   }

 function RelegenceJSONRequest(fullUrl) {
 
 //alert("in the RelegenceJSONRequest");
  this.fullUrl = fullUrl;
  this.noCacheIE = "&noCacheIE=" + (new Date()).getTime();
  this.headLoc = document.getElementsByTagName("head").item(0);
  this.scriptId = "YJscriptId" + RelegenceJSONRequest.scriptCounter++;
  this.removeScriptTag();
  this.buildScriptTag();
  this.addScriptTag();
}

RelegenceJSONRequest.scriptCounter = 1;
/**
 *  Method for building our script tag, once this tag is appended, the JSON content will be loaded in
 */ 
RelegenceJSONRequest.prototype.buildScriptTag = function () {
  this.scriptObj = document.createElement("script");
  this.scriptObj.setAttribute("type", "text/javascript");
  this.scriptObj.setAttribute("src", this.fullUrl+ this.noCacheIE);
  this.scriptObj.setAttribute("id", this.scriptId);
    this.scriptObj.setAttribute("language", "javascript");
    this.scriptObj.setAttribute("charset","UTF-8");
}
/**
 *  Removes script tag from head
 */ 
RelegenceJSONRequest.prototype.removeScriptTag = function () {
  if (typeof this.scriptObj != "undefined") {
      // alert("removing the scriptobj");
      this.headLoc.removeChild(this.scriptObj);
  }
}
/**
 *  Appends script tag to head
 */ 
RelegenceJSONRequest.prototype.addScriptTag = function () {
  this.headLoc.appendChild(this.scriptObj);
}

/*Relegence Utility Functions */
var IE=document.all?true:false
function setVisibility(divon,divoff){if(document.getElementById){elemon=document.getElementById(divon);elemoff=document.getElementById(divoff);}
if(elemoff){elemoff.style.visibility="hidden";}
if(elemon){elemon.style.visibility="visible";}}
function conferenceCallsPopup(url)
{if(!url){url="";}
window.open(url,'ConferenceCalls','scrollbars=no,location=no,directories=no,height=420,width=700,menubar=no,resizable=yes,titlebar=no');}
function nextPage(first,last){firstNext=first;lastNext=last;document.analystRatyng.page.value="OP";document.analystRatyng.firstNext.value=firstNext;document.analystRatyng.lastNext.value=lastNext;document.analystRatyng.next.value="N";document.analystRatyng.submit();}
function prevPage(first,last){var firstPrev=0;var lastPrev=0;firstPrev=first;lastPrev=last;document.analystRatyng.firstPrev.value=firstPrev;document.analystRatyng.lastPrev.value=lastPrev;document.analystRatyng.prev.value="P";document.analystRatyng.next.value="H";document.analystRatyng.page.value="OP";document.analystRatyng.submit();}
function initFocus()
{var elemnt=document.getElementById("navsearch_field");if(elemnt){elemnt.focus();elemnt.select();}}
function changeDisplay(divon,divoff){if(document.getElementById){elemon=document.getElementById(divon);elemoff=document.getElementById(divoff);}
if(elemoff){elemoff.style.display="none";}
if(elemon){elemon.style.display="block";}}
function changeConference(divon1,divoff1,divon2,divoff2,divon3,divoff3){if(document.getElementById){elemon1=document.getElementById(divon1);elemoff1=document.getElementById(divoff1);elemon2=document.getElementById(divon2);elemoff2=document.getElementById(divoff2);elemon3=document.getElementById(divon3);elemoff3=document.getElementById(divoff3);}
if(elemoff1){elemoff1.style.display="none";}
if(elemon1){elemon1.style.display="block";}
if(elemoff2){elemoff2.style.display="none";}
if(elemon2){elemon2.style.display="block";}
if(elemoff3){elemoff3.style.display="none";}
if(elemon3){elemon3.style.display="inline";}}
function openAddholding(portfolioURL,ticker,symbol)
{var tick=ticker;var sym=symbol;url=portfolioURL+"/portfolios/addholding?exchange="+tick+"&symbols="+sym+"&from=quote_addhold";window.open(url,'Portfolio','scrollbars=no,location=no,directories=no,height=325,width=485,menubar=no,resizable=yes,titlebar=no');}
function changeFinancial(divon1,divoff1,divon2,divoff2){if(document.getElementById){elemon1=document.getElementById(divon1);elemoff1=document.getElementById(divoff1);elemon2=document.getElementById(divon2);elemoff2=document.getElementById(divoff2);}
if(elemoff1){elemoff1.style.display="none";}
if(elemon1){elemon1.style.display="block";}
if(elemoff2){elemoff2.style.display="none";}
if(elemon2){elemon2.style.display="inline";}}
function changeMonthVisibility(divon1,divoff1,divoff2){if(document.getElementById){elemon1=document.getElementById(divon1);elemoff1=document.getElementById(divoff1);elemoff2=document.getElementById(divoff2);}
if(elemoff1){elemoff1.style.display="none";}
if(elemoff2){elemoff2.style.display="none";}
if(elemon1){elemon1.style.display="block";}}
function safeMO(evt,method,obj){try{func=eval(method);func(evt,obj);}
catch(e){debug("safe mouseover error ... "+e);}}
function debug(msg){if(window.console){window.console.log(msg);}
msg=null;}
if(typeof qp=="undefined"){var qp_global=this;function qp_undef(name,object){if(object==null){object=qp_global;}
return(typeof object[name]=="undefined");}
if(qp_undef("qp")){var qp={};}};var IM_global_title;var IM_global_url;var IM_default_text_IE="Your%20friend%20wants%20you%20to%20check%20this%20out:";var IM_default_text_OT="Your friend wants you to check this out:";qp.common=function(){};qp.common.sendIM=function(title,url){if(title==''){title='Click here to checkout';}
IM_global_title=title;IM_global_url=url;var uAgt=navigator.userAgent.toLowerCase();var isAOL=uAgt.indexOf(" aol ")!=-1;var isIE=uAgt.indexOf(" msie ")!=-1;if(!isAOL){if(!isIE){qp.common.sendAIM();}else{if(!qp.common.canRunAIM()){AIMExpress.start();}else{qp.common.sendAIM();}}}else{qp.common.sendAOLCLNT();}}
qp.common.sendEmail=function(linkURL,pageTitle){var width=292;var height=500;var winl=(screen.width-width)/2;var wint=(screen.height-height)/2;if(winl<0)winl=0;if(wint<0)wint=0;var lang="en-US";window.open("http://sendtoafriend.aol.com/?url="+linkURL+"&title="+pageTitle+"&lang="+lang,"Email_Window","height="+height+",width="+width+",top="+wint+",left="+winl+",statusbar=0,toolbar=0,menubar=0,location=0,resizable=0");}
qp.common.canRunAIM=function(){var agt=navigator.userAgent.toLowerCase();var isIE=(agt.indexOf("msie")!=-1);if(!isIE)
return true;var a=document.anchors;for(var i=0;i<a.length;i++){if(a[i].name=="aimnotfound"){return false;}}
return true;}
qp.common.sendAIM=function(){var title=IM_global_title;var url=IM_global_url;var title=title.replace(/ /g,"+");var uAgt=navigator.userAgent.toLowerCase();var isIE=uAgt.indexOf(" msie ")!=-1;var isAOLBrowser=uAgt.indexOf(" america online browser ")!=-1;if(!isIE){var message=IM_default_text_OT+'<br><a href="'+url+'">'+title+'</a>';}else if(isAOLBrowser){var message=IM_default_text_OT+'<br><a href="'+url+'">'+title+'</a>';}else{var message=IM_default_text_IE+"%3cbr%3e%3ca+href=%22"+escape(url)+"%22%3e"+title+"%3c%2fa%3e";}
message=escape(message);try{document.location='aim:GoIm?message='+message;}catch(e){AIMExpress.start();}}
qp.common.sendAOLCLNT=function(){var title=IM_global_title;var url=IM_global_url;var uAgt=navigator.userAgent.toLowerCase();var isAOL=uAgt.indexOf(" aol ")!=-1;var isIE=uAgt.indexOf("msie")!=-1;try{if(!isAOL){if(!isIE){document.location="aol://9293::"+IM_default_text_OT+"<br><a href='"+url+"'>"+title+"</a>";}else{document.location="aol://9293::"+IM_default_text_IE+"%3cbr%3e%3ca href='"+url+"'%3e"+title+"%3c%2fa%3e";}}else{document.location='aol://9293::'+IM_default_text_OT+'<br><a href="'+url+'">'+title+'</a>'}}catch(e){AIMExpress.start();}}
qp.common.openBlogThis=function(name)
{blog_url=encodeURI('http://edit.journals.aol.com/_do/blog_this');eurl=this.location;esubject=document.title;esubject=esubject?esubject.replace(/"/g,'&quot;'):'';var selectedText='';var range;if(document.selection&&document.selection.createRange){range=document.selection.createRange();selectedText=range.htmlText;}else{if(window.getSelection){var selection=window.getSelection();if(selection.rangeCount>0){range=selection.getRangeAt(0);var clonedSelection=range.cloneContents();var div=document.createElement('div');div.appendChild(clonedSelection);selectedText=div.innerHTML;}}}
selectedText=escape(selectedText);var jeInput='';jeInput+='<a href="';jeInput+=eurl;jeInput+='">';jeInput+=esubject;if(selectedText.length>0)
{jeInput+='<\/a> : "';jeInput+=selectedText;jeInput+='"';}
else
{jeInput+='<\/a> : ';}
var params='directories=yes, location=yes, menubar=yes, resizable=yes, scrollbars=yes, status=yes, titlebar=yes, toolbar=yes, width=680, height=640';var windowIndex=Math.round(Math.random()*100000);name=name+windowIndex;var blogThisWindow=window.open('about:blank',name,params);var form=document.forms['blog_this_form'];var cu=document.createElement("input");cu.type="hidden";cu.name="cu";cu.value="javascript:window.close();";var js=document.createElement("input");js.type="hidden";js.name="js";js.value=esubject;var je=document.createElement("input");je.type="hidden";je.name="je";je.value=jeInput;form.appendChild(cu);form.appendChild(js);form.appendChild(je);document.blog_this_form.action=blog_url;document.blog_this_form.target=name;document.blog_this_form.submit();if(window.focus){blogThisWindow.focus();}};qp.common.utf8=function(wide){var c,s;var enc="";var i=0;while(i<wide.length){c=wide.charCodeAt(i++);if(c>=0xDC00&&c<0xE000)continue;if(c>=0xD800&&c<0xDC00){if(i>=wide.length)continue;s=wide.charCodeAt(i++);if(s<0xDC00||c>=0xDE00)continue;c=((c-0xD800)<<10)+(s-0xDC00)+0x10000;}
if(c<0x80)enc+=String.fromCharCode(c);else if(c<0x800)enc+=String.fromCharCode(0xC0+(c>>6),0x80+(c&0x3F));else if(c<0x10000)enc+=String.fromCharCode(0xE0+(c>>12),0x80+(c>>6&0x3F),0x80+(c&0x3F));else enc+=String.fromCharCode(0xF0+(c>>18),0x80+(c>>12&0x3F),0x80+(c>>6&0x3F),0x80+(c&0x3F));}
return enc;}
var hexchars="0123456789ABCDEF";qp.common.toHex=function(n){return hexchars.charAt(n>>4)+hexchars.charAt(n&0xF);}
var okURIchars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";qp.common.encodeURIComponentNew=function(s){var s=qp.common.utf8(s);var c;var enc="";for(var i=0;i<s.length;i++){if(okURIchars.indexOf(s.charAt(i))==-1)
enc+="%"+qp.common.toHex(s.charCodeAt(i));else
enc+=s.charAt(i);}
return enc;}
qp.common.whichEncode=function(fld)
{var encodedField="";var s=fld;if(typeof encodeURIComponent=="function")
{encodedField=encodeURIComponent(s);}
else
{encodedField=qp.common.encodeURIComponentNew(s);}
return encodedField;}
qp.common.validateSym=function(str)
{var invalids="<";for(i=0;i<invalids.length;i++){if(str.indexOf(invalids.charAt(i))>=0){return"There are characters in the symbol that are not allowed.";}}
return null;}
qp.common.makeSym=function(sym)
{var invalids="/+";var seosym="";var seoindex=-1;for(i=0;i<invalids.length;i++){while((seoindex=sym.indexOf(invalids.charAt(i)))>=0){seosym=sym.substring(0,seoindex);seosym+=qp.common.whichEncode(invalids.charAt(i));seosym+=sym.substring(seoindex+1,sym.length);sym=seosym;}}
return qp.common.whichEncode(sym);}
String.prototype.trim=function(){return this.replace(/^\s*|\s*$/g,'');}
qp.common.getCountryCode=function(sym){var sParts=sym.split(':');var countryCode="";if(sParts.length>=2){var countryPart=sParts[1].toLowerCase();countryCode=countryPart.trim();if(countryCode=="uk"){countryCode="gbr";}else if(countryCode=="ca"){countryCode="can";}else if(countryCode=="us"){countryCode="usa";}}
return countryCode;}
qp.common.trimSym=function(sym){var sParts=sym.split(':');var countryCode="";var trimmedSym="";if(sParts.length>=1){trimmedSym=sParts[0];}else{trimmedSym=sym;}
return trimmedSym;}
qp.common.goSearchOrQuote=function(daform)
{var ms=qp.common.validateSym(daform.sym.value);if(ms){alert(ms);return;}
if(daform.searchType_mf.checked){qp.common.getSymPage(daform);}else{var url="";url="http://search.aol.com/aol/search?query="+daform.sym.value;window.location=url;}}
qp.common.getSymPage=function(daform)
{
}

qp.common.getLookupPageAdd=function(daform)
{var sym=daform.sym.value.toLowerCase();var exch=daform.exch.value.toLowerCase();var hub="";var url="";if((sym!=null)&&(sym.length>0)){var exchange=qp.common.getCountryCode(sym);if(exchange!=""){exch=exchange;sym=qp.common.trimSym(sym);}
var encodedSym=qp.common.makeSym(sym).toLowerCase();url="/portfolios/lookuppopadd?port=true&lsym="+encodedSym+"&lexch="+exch+"&type=USA";}
else{url="/portfolios/lookuppopadd?port=true&lexch="+exch+"&type=USA";}
window.location=url;}
qp.common.getLookupPage=function(daform)
{var sym=daform.sym.value.toLowerCase();var exch=daform.exch.value.toLowerCase();var hub="";var url="";if((sym!=null)&&(sym.length>0)){var exchange=qp.common.getCountryCode(sym);if(exchange!=""){exch=exchange;sym=qp.common.trimSym(sym);}
var encodedSym=qp.common.makeSym(sym).toLowerCase();url="/lookuppop/"+encodedSym+"/"+exch+"?type=USA";}
else{url="/lookuppop//"+exch+"?type=USA";}
window.location=url;}
qp.common.trim=function(stringReplace){return stringReplace.replace(/^\s+|\s+$/g,"");}
qp.common.setupAddAlert=function(params)
{af=document.getElementById('alertForm');alertType=af.alertText.value;if(alertType=='1')
{if(af.priceText.value==null||af.priceText.value.length==0)
{alert("Please Enter a Price Rise.");return;}
if(af.priceText.value!=null&&af.priceText.value.length!=0)
{x=parseInt(qp.common.trim(af.priceText.value));if(isNaN(x))
{alert("Please Enter a Valid Price Rise.");return;}
params=params.concat(',').concat(x).concat(',,0,0,,');}}
else if(alertType=='2')
{if(af.priceText.value==null||af.priceText.value.length==0)
{alert("Please Enter a Price Fall.");return;}
if(af.priceText.value!=null&&af.priceText.value.length!=0)
{x=parseInt(qp.common.trim(af.priceText.value));if(isNaN(x))
{alert("Please Enter a Valid Price Fall.");}
params=params.concat(',,').concat(x).concat(',0,0,,');}}
else if(alertType=='3')
{if(af.dayPrice.value!=null&&af.dayPrice.value.length!=0)
{params=params.concat(',,,').concat(af.dayPrice.value).concat(',0,,');}}
else if(alertType=='4')
{if(af.dayPrice.value!=null&&af.dayPrice.value.length!=0)
{params=params.concat(',,,0,').concat(af.dayPrice.value).concat(',,');}}
else if(alertType=='5')
{params=params.concat(',,,0,0,1,');}
else if(alertType=='6')
{params=params.concat(',,,0,0,,1');}
qp.common.openAddAlert(params);}
addalertWin=null;qp.common.openAddAlert=function(params)
{if(addalertWin)addalertWin.close();addalertWin=window.open('http://alerts.aol.com/ar/dlink/dlink.rr'+params,'newWin','toolbar=no, menubar=no, resizable=no, location=no, directories=no, scrollbars=yes, width=802, height=604')}
qp.common.breadcrumbs=function()
{sURL=new String;bits=new Object;var x=0;var stop=0;var output="<a href=\"http://money.aol.com\">Money & Finance</a> &#187; <a href=\"http://money.aol.com/investing\">Investing</a> &#187 ";sURL=location.href;sURL=sURL.slice(8,sURL.length);chunkStart=sURL.indexOf("/");sURL=sURL.slice(chunkStart+1,sURL.length)
while(!stop){chunkStart=sURL.indexOf("/");if(chunkStart!=-1){bits[x]=sURL.slice(0,chunkStart)
sURL=sURL.slice(chunkStart+1,sURL.length);}else{stop=1;}
x++;}
output+=bits[0]+":&nbsp;";document.write(output);}
qp.news=function(){}
var current="headlines-sub";qp.news.setCurrent=function(curr){current=curr;}
qp.news.setVisibility=function(obj,ulName){if(current==ulName){return false;}
var newIndex=0;var oldIndex=0;if(ulName=="headlines-sub"){newIndex=0;if(typeof document.newsDateUpdate!="undefined"){document.newsDateUpdate.tab.value=5;var d=document.getElementById('headlinesTitle');d.innerHTML="Real-Time Headlines";}}
else if(ulName=="news"){newIndex=1;if(typeof document.newsDateUpdate!="undefined"){document.newsDateUpdate.tab.value=0;var d=document.getElementById('headlinesTitle');d.innerHTML="News";}}
else if(ulName=="trade"){newIndex=2;if(typeof document.newsDateUpdate!="undefined"){document.newsDateUpdate.tab.value=2;var d=document.getElementById('headlinesTitle');d.innerHTML="Articles in Trade Publications";}}
else if(ulName=="regional"){newIndex=3;if(typeof document.newsDateUpdate!="undefined"){document.newsDateUpdate.tab.value=4;var d=document.getElementById('headlinesTitle');d.innerHTML="Articles in Regional Sources";}}
else if(ulName=="releases"){newIndex=4;if(typeof document.newsDateUpdate!="undefined"){document.newsDateUpdate.tab.value=1;var d=document.getElementById('headlinesTitle');d.innerHTML="Press Releases";}}
else if(ulName=="blogs"){newIndex=5;if(typeof document.newsDateUpdate!="undefined"){document.newsDateUpdate.tab.value=3;var d=document.getElementById('headlinesTitle');d.innerHTML="Blogs";}}
if(current=="headlines-sub"){oldIndex=0;}
else if(current=="news"){oldIndex=1;}
else if(current=="trade"){oldIndex=2;}
else if(current=="regional"){oldIndex=3;}
else if(current=="releases"){oldIndex=4;}
else if(current=="blogs"){oldIndex=5;}
var changeDiv=document.getElementById(ulName);var currentDiv=document.getElementById(current);if(changeDiv){qp.news.deselectTab(obj,oldIndex);qp.news.selectTab(obj,newIndex);changeDiv.style.display="";if(currentDiv){currentDiv.style.display="none";current=ulName;}}}
qp.news.selectTab=function(curItem,index){var ul=curItem.parentNode.parentNode;var as=ul.getElementsByTagName("a");if(as.length>0){as[index].className="active "+as[index].className;}}
qp.news.deselectTab=function(curItem,index){var ul=curItem.parentNode.parentNode;var as=ul.getElementsByTagName("a");if(as.length>0){as[index].className=as[index].className.replace(/active /i,"");}}
qp.ads=function(){};qp.ads.selectRandom=function(max)
{var r=Math.random()
r*=max
r=parseInt(r)
if(isNaN(r))
r=0
else
r%=max
return r}
qp.ads.randomiseAds=function(adsToShow,magicNum1,magicNum2,magicNum3,magicNum4){var ADS_TO_SHOW=adsToShow;FB_MagicNums=new Array(magicNum1,magicNum2,magicNum3,magicNum4);var arraySize=ADS_TO_SHOW;var max=FB_MagicNums.length;randomArray=new Array();var n;var unique=0;var allUnique=true;if(ADS_TO_SHOW>FB_MagicNums.length)
{allUnique=false;}
n=qp.ads.selectRandom(max)
randomArray[0]=n;for(var i=0;i<ADS_TO_SHOW;i++)
{if(allUnique)
{while(unique==0)
{j=0;while(n!=randomArray[j]&&j<=max)
{j++;}
if(j<arraySize&&max!=1)
n=qp.ads.selectRandom(max);else
{randomArray[i]=n;unique=1;}}
unique=0;randomArray[i]=n;}
else
{n=qp.ads.selectRandom(max);randomArray[i]=n;}}}
qp.repquart=function(){}
qp.repquart.getInfoBox=function(){var infodiv=document.getElementById("repquartInfo");if(infodiv==null){infodiv=document.body.appendChild(document.createElement("div"));infodiv.id="repquartInfo";infodiv.style.position="absolute";infodiv.style.display="none";infodiv.style.left="-1000px";infodiv.style.top="0";infodiv.style.marginTop="3px";infodiv.style.zIndex="10";}
return infodiv;}
qp.repquart.showInfo=function(e,obj){var obj=obj.parentNode;if(obj.className=="qtr"){if(jsdebug)debug("called show with event obj "+e);var infobox=this.getInfoBox();getMouseXY(e);var info=obj.getElementsByTagName("div")[0];infobox.innerHTML=info.innerHTML;infobox.style.top=parseInt(mousey-8)+'px';infobox.style.left=parseInt(mousex+10)+'px';infobox.style.display="block";if(jsdebug)debug("showing reported quarterly info");}}
qp.repquart.hideInfo=function(e,obj){var obj=obj.parentNode;if(obj.className=="qtr"){if(jsdebug)debug("called hide with event obj "+e);var infobox=this.getInfoBox();infobox.style.display="none";infobox.innerHTML="";if(jsdebug)debug("hiding reported quarterly info");}}
var IE=document.all?true:false;function getMouseXY(e){if(IE){mousex=event.clientX;if(document.documentElement&&document.documentElement.scrollTop){mousey=event.clientY+document.documentElement.scrollTop;}
else if(document.body&&document.body.scrollTop&&event.clientY){mousey=event.clientY+document.body.scrollTop;}
else if(event.clientY){mousey=event.clientY;}else{mousey=0;}}else{mousex=e.pageX;mousey=e.pageY;}
return true;}
var mousex,mousey;qp.common.subHist=function(daform,t)
{daform.tf.value=t;daform.submit();}
function setAlertsDropdownChoice(object){var choice=object.options[object.selectedIndex].value;switch(choice){case"1":case"2":document.getElementById("priceText").style.display="";document.getElementById("dayPrice").style.display="none";document.getElementById("occursPrice").style.display="none";break;case"3":case"4":document.getElementById("priceText").style.display="none";document.getElementById("dayPrice").style.display="";document.getElementById("occursPrice").style.display="none";break;case"5":case"6":document.getElementById("priceText").style.display="none";document.getElementById("dayPrice").style.display="none";document.getElementById("occursPrice").style.display="inline";break;default:document.getElementById("priceText").style.display="";document.getElementById("dayPrice").style.display="none";document.getElementById("occursPrice").style.display="none";break;}}
function findPos(obj){var curleft=curtop=0;if(obj.offsetParent){curleft=obj.offsetLeft
curtop=obj.offsetTop
while(obj=obj.offsetParent){curleft+=obj.offsetLeft
curtop+=obj.offsetTop}}
return[curleft,curtop];}
function stripeTables(){var tb=document.getElementsByTagName("TBODY");for(var i=0;i<tb.length;i++){var trs=tb[i].getElementsByTagName("TR");for(var j=0;j<trs.length;j++){var classnames=trs[j].className;if(j==0){classnames=classnames+" first";}
if(j==(trs.length-1)){classnames=classnames+" last";}
if((j%2)==0){classnames=classnames+" odd";}
if((j%2)==1){classnames=classnames+" even";}
trs[j].className=classnames;classnames=null;}
trs=null;}
tb=null;}
function flashOnTop()
{document.getElementById("header").style.zIndex=1;document.getElementById("ADS").style.zIndex=1;document.getElementById("DYNAMIC").style.zIndex=1;document.getElementById("QUOTEPANEL_TOP").style.zIndex=1;if(document.getElementById("VIEW_TITLE_BAR")!=null)
{document.getElementById("VIEW_TITLE_BAR").style.zIndex=1;}}
function linksOnTop()
{document.getElementById("header").style.zIndex=4;document.getElementById("ADS").style.zIndex=3;document.getElementById("DYNAMIC").style.zIndex=3;document.getElementById("QUOTEPANEL_TOP").style.zIndex=3;if(document.getElementById("VIEW_TITLE_BAR")!=null)
{document.getElementById("VIEW_TITLE_BAR").style.zIndex=3;}}
function dateChosen(chosenDate)
{linksOnTop();}
function newsFlashOnTop()
{document.getElementById("ListOfLinks").style.zIndex=1;}
function newsLinksOnTop()
{document.getElementById("ListOfLinks").style.zIndex=3;}
function newsDateChosen(chosenDate)
{newsLinksOnTop();updateNewsPage(chosenDate);}
function updateNewsPage(chosenDate){var today=new Date();var todayString=(today.getMonth()+1)+"/"+today.getDate()+"/"+today.getFullYear();if(todayString==chosenDate){document.newsDateUpdate.pDate.value="";}else{document.newsDateUpdate.pDate.value=chosenDate;}
document.newsDateUpdate.allhndl.value=0;document.newsDateUpdate.newshndl.value=0;document.newsDateUpdate.tradehndl.value=0;document.newsDateUpdate.reghndl.value=0;document.newsDateUpdate.presshndl.value=0;document.newsDateUpdate.blogshndl.value=0;document.newsDateUpdate.currPages.value="1:1:1:1:1:1";document.newsDateUpdate.submit();}
function submitNewsForm(pgHandle,numPages){
    document.newsDateUpdate.pgHnd.value=pgHandle;
    document.newsDateUpdate.curTab.value= document.getElementById('cur').value;
    if(typeof numPages!="undefined"){
       document.newsDateUpdate.pageNum.value=numPages;
    }
    document.newsDateUpdate.submit();
}
function submitRelatedForm(numPage,handle){document.relatedUpdate.hndl.value=handle;if(typeof numPage!="undefined"){document.relatedUpdate.currPage.value=numPage;}
document.relatedUpdate.submit();}
function openNoticesAndTerms(url){custWin=window.open(url,'noticesAndTerms','scrollbars=no, resizable=no, toolbar=no, width=620, height=610');}
function fadeBackground(node,startHex,endHex,duration,steps){if(typeof(node)=="string"){}else if(node.id){node=node.id;}else if(node.nodeName&&node.nodeType==1){node.id=generateTempID();node=node.id;}else{return;}
if(duration==null){duration=1000;}
if(steps==null){steps=50;}
var pace=duration/steps;var nodeRef=document.getElementById(node);var keys=["red","green","blue"];var startColor=getColorRef(startHex);var endColor=getColorRef(endHex);var nextHex;nodeRef.style.backgroundColor=getHexColor(startColor);for(var i=0;i<3;i++){startColor[keys[i]]=startColor[keys[i]]-Math.floor(((startColor[keys[i]]-endColor[keys[i]])/steps));}
nextHex=getHexColor(startColor);steps--;duration-=pace;if(steps>0){var t=setTimeout("fadeBackground(\""+node+"\", \""+nextHex+"\", \""+endHex+"\", "+duration+", "+steps+");",pace);}else{nodeRef.style.backgroundColor=endHex;clearTempID(node);}
nodeRef=null;}
function getHexColor(colorRef){return"#"+getHexString(colorRef["red"],2)+getHexString(colorRef["green"],2)+getHexString(colorRef["blue"],2);}
function getHexString(value,length){var hexVal=value.toString(16);while(hexVal.length<length){hexVal="0"+hexVal;}
return hexVal;}
function getColorRef(hexColor){var colorRef={"red":0,"green":0,"blue":0};if(hexColor.length>6){colorRef={"red":parseInt(hexColor.substr(1,2),16),"green":parseInt(hexColor.substr(3,2),16),"blue":parseInt(hexColor.substr(5,2),16)};}else if(hexColor.length>3){colorRef={"red":parseInt(hexColor.substr(1,1)+hexColor.substr(1,1),16),"green":parseInt(hexColor.substr(2,1)+hexColor.substr(2,1),16),"blue":parseInt(hexColor.substr(3,1)+hexColor.substr(3,1),16)};}else{colorRef={"red":0,"green":0,"blue":0};}
return colorRef;}
function clearTempID(node){nodeRef=document.getElementById(node);if(nodeRef){if(node.match(/^jsinternal\d+$/)){nodeRef.id=null;}}}
function getResults(symbol,form){var xmlhttp=new XMLHttpRequest();var url="/.module/valueCalc/pfweb/standalone_modules/"+symbol+"?"
+"fromDate="+encodeURIComponent(form.fromDate.value);if(form.amount!=null||form.amount!=""){url=url+"&amount="+form.amount.value;}
if(form.shares!=null||form.shares!=""){url=url+"&shares="+form.shares.value;}
xmlhttp.open("GET",url,true);xmlhttp.onreadystatechange=processResponse;xmlhttp.send(null);function processResponse()
{if(xmlhttp.readyState==4)
{if(xmlhttp.status==200)
{d=document.getElementById("performance");d.innerHTML=xmlhttp.responseText;}
else
{d=document.getElementById("performance");alert("Unable to calculate return. Please try again later.");}}}}
function CustomRefreshMainPage(){if(typeof document.newsDateUpdate!="undefined")
{document.newsDateUpdate.submit();}
else
{if(typeof document.portfoliosfrm!="undefined")
{document.portfoliosfrm.submit();}}}
function getCustomPopUp(symbol,exch,newsDef,tradeDef,regDef,prDef,blogDef){var xmlhttp;if(window.XMLHttpRequest)
{xmlhttp=new XMLHttpRequest();}else if(window.ActiveXObject){xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}else{xmlhttp=false;}
if(xmlhttp){var url="/.module/customization/pfweb/standalone_modules/"+symbol+"?exchange="
+exch;xmlhttp.open("GET",url,true);xmlhttp.onreadystatechange=processCustomResponse;xmlhttp.send(null);}
function processCustomResponse()
{if(xmlhttp.readyState==4)
{if(xmlhttp.status==200)
{d=document.getElementById("customBox");d.innerHTML=xmlhttp.responseText;d.style.display='block';readCustomizeCookie(document.smallRelegenceForm,newsDef,tradeDef,regDef,prDef,blogDef);}
else
{}}}}
function getSourceLists(symbol,exch,cat,dropdown,myId,leftOff,topOff){var d=document.getElementById("showSourceList");if(typeof d=="undefined"){return;}else if(d.innerHTML!=""){headlines_mouseover(cat,dropdown,myId,leftOff,topOff);return;}
var xmlhttp;if(window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();}else if(window.ActiveXObject){xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}else{xmlhttp=false;}
if(xmlhttp){var url="/.module/sourcelist/pfweb/standalone_modules/"+symbol+"?exchange="
+exch;xmlhttp.open("GET",url,true);xmlhttp.onreadystatechange=processSourceListResponse;xmlhttp.send(null);}
function processSourceListResponse()
{if(xmlhttp.readyState==4)
{if(xmlhttp.status==200)
{d=document.getElementById("showSourceList");d.innerHTML=xmlhttp.responseText;headlines_mouseover(cat,dropdown,myId,leftOff,topOff);}
else
{}}}}
function histDateChosen(theDate)
{var f=document.getElementById('perf');if(f!=null)
f.fromDate.value=theDate;histLinksOnTop();f.submit()}
function histDateRangeChosen(theRange)
{linksOnTop();histLinksOnTop();var f=document.getElementById('charts');f.tf.value=theRange;f.submit()}
function histFlashOnTop()
{var linksLayer1=document.getElementById("sampleLinks1");var linksLayer2=document.getElementById("sampleLinks2");if(linksLayer2){linksLayer2.style.zIndex=2;}
var linksLayer3=document.getElementById("SPONSORED");if(linksLayer3){linksLayer3.style.zIndex=2;}
var linksLayer4=document.getElementById("HISTRETURN");if(linksLayer4){linksLayer4.style.zIndex=2;}
var linksLayer5=document.getElementById("performance");if(linksLayer5){linksLayer5.style.zIndex=2;}
var linksLayer6=document.getElementById("LOWER_AD");if(linksLayer6){linksLayer6.style.zIndex=2;}
var linksLayer7=document.getElementById("HISTCALC");if(linksLayer7){linksLayer7.style.zIndex=2;}
var flashContainer=document.getElementById("charts");if(flashContainer){flashContainer.style.zIndex=5;}}
function histPerfDateChosen(theDate)
{var f=document.getElementById('perf');f.fromDate.value=theDate;histLinksOnTop();linksOnTop();}
function histPerfDateRangeChosen(theRange)
{linksOnTop();}
function histPerfFlashOnTop()
{var linksLayer1=document.getElementById("sampleLinks1");linksLayer1.style.zIndex=1;}
function histLinksOnTop()
{var linksLayer1=document.getElementById("sampleLinks1");var linksLayer2=document.getElementById("sampleLinks2");if(linksLayer2){linksLayer2.style.zIndex=5;}
var linksLayer3=document.getElementById("SPONSORED");if(linksLayer3){linksLayer3.style.zIndex=5;}
var linksLayer4=document.getElementById("HISTRETURN");if(linksLayer4){linksLayer4.style.zIndex=5;}
var linksLayer5=document.getElementById("performance");if(linksLayer5){linksLayer5.style.zIndex=5;}
var linksLayer6=document.getElementById("LOWER_AD");if(linksLayer6){linksLayer6.style.zIndex=5;}
var linksLayer7=document.getElementById("HISTCALC");if(linksLayer7){linksLayer7.style.zIndex=5;}
var flashContainer=document.getElementById("charts");if(flashContainer){flashContainer.style.zIndex=3;}}
function generateTempID(){time=new Date();return"jsinternal"+time.getTime();}
function setPerf(input)
{if(input==document.perf.amount)
document.perf.shares.value="";else
document.perf.amount.value="";}
function liveUpdateOn(){setCookie("qp_live_update","on",365);var li=document.getElementById("live_update_options");li.innerHTML="On | <a href=\"javascript: liveUpdateOff()\">Off</a>";if(typeof LIVE_QUOTES_ENABLED!="undefined"){LIVE_QUOTES_ENABLED=true;}
if(typeof LIVE_CHARTS_ENABLED!="undefined"){LIVE_CHARTS_ENABLED=true;}
    if(typeof LIVE_NEWS_ENABLED!="undefined"){LIVE_NEWS_ENABLED=true;if(typeof newsBoxWidget!="undefined"){newsBoxWidget.connectSession("dataIM");}}
if(typeof bootstrap!="undefined"){if(bootstrap!=null){var masterObj=bootstrap.getActiveModule("headerBottom");var detailQuotesObj=bootstrap.getActiveModule("QUOTE_DETAILS");var heatObj=bootstrap.getActiveModule("NAVIGATION");if(masterObj!=null){masterObj.properties.enabled=true;masterObj.init();}
if(detailQuotesObj!=null){detailQuotesObj.properties.enabled=true;detailQuotesObj.init();}
if(heatObj!=null){heatObj.properties.enabled=true;heatObj.init();}}}}
function liveUpdateOff(){setCookie("qp_live_update","off",365);var li=document.getElementById("live_update_options");li.innerHTML="<a href=\"javascript: liveUpdateOn()\">On</a> | Off";if(typeof LIVE_QUOTES_ENABLED!="undefined"){LIVE_QUOTES_ENABLED=false;}
if(typeof LIVE_CHARTS_ENABLED!="undefined"){LIVE_CHARTS_ENABLED=false;}
if(typeof LIVE_NEWS_ENABLED!="undefined"){LIVE_NEWS_ENABLED=false;if(typeof newsBoxWidget!="undefined"){newsBoxWidget.cleanUp();}}
if(typeof bootstrap!="undefined"){if(bootstrap!=null){var masterObj=bootstrap.getActiveModule("headerBottom");var detailQuotesObj=bootstrap.getActiveModule("QUOTE_DETAILS");var heatObj=bootstrap.getActiveModule("NAVIGATION");if(masterObj!=null){bootstrap.kill("headerBottom");bootstrap.getActiveModule("headerBottom").properties.enabled=false;bootstrap.getActiveModule("headerBottom").init();}
if(detailQuotesObj!=null){bootstrap.kill("QUOTE_DETAILS");bootstrap.getActiveModule("QUOTE_DETAILS").properties.enabled=false;bootstrap.getActiveModule("QUOTE_DETAILS").init();}
if(heatObj!=null){bootstrap.kill("NAVIGATION");bootstrap.getActiveModule("NAVIGATION").properties.enabled=false;bootstrap.getActiveModule("NAVIGATION").init();}}}}
function setCookie(name,value,days){if(days){var date=new Date();date.setTime(date.getTime()+(days*24*60*60*1000));var expires="; expires="+date.toGMTString();}
else var expires="";document.cookie=name+"="+value+expires+"; path=/";}
function openCustomization(seoname,ticker,exch){custWin=window.open('/quotes/'+seoname+'/'+ticker+'/'+exch+'/customization','custWin','scrollbars=no, resizable=no, toolbar=no, width=550, height=600');}
function getSelected(selection){for(var y=0;y<selection.length;y++){if(selection[y].selected){return selection[y].value;}}}
function openSourceList(seoname,ticker,exch,category,dropdown){var group=getSelected(dropdown);if(typeof group=="undefined"){group=dropdown;}
sourceWin=window.open('/quotes/'+seoname+'/'+ticker+'/'+exch+'/sourcelist?cat='+category+'&grp='+group,'sourceWin','scrollbars=yes, resizable=no, toolbar=no, width=650, height=700');}
function openNewsWindow(url){newsWin=window.open(url,'newsWin');newsWin.focus();}
function openProvWindow(url){provWin=window.open(url,'provWin');provWin.focus();}
function headlines_mouseover(cat,dropdown,myId,leftOff,topOff){var group=getSelected(dropdown);if(typeof group=="undefined"){group=dropdown;}
myObj=document.getElementById(myId);var pCoords=findPos(myObj);var leftPos=0;var topPos=0;var offset=0;offset=topOff;leftPos=pCoords[0];topPos=pCoords[1];topPos=topPos+(offset*1);leftPos=leftPos-leftOff;var topPosPX=topPos+'px';var leftPosPX=leftPos+'px';var sourcelist=document.getElementById('SOURCELIST');if(sourcelist.innerHTML==""){var d=document.getElementById('showSourceList');var info=d.getElementsByTagName("div");for(var e=0;e<info.length;e++){if(info[e].id=='SOURCELIST'){sourcelist=info[e];}}}
sourcelist.style.top=topPosPX;sourcelist.style.left=leftPosPX;sourcelist.style.display='block';var listID='list_c'+cat+'_g'+group;document.getElementById(listID).style.display='block';var linksID='catDiv'+cat;var textID='text_c'+cat+'_g'+group;var linkID='link_c'+cat+'_g'+group;var blockDivs=getElementsByStyleClass("category_links_div");for(var i=0;i<blockDivs.length;i++){blockDivs[i].style.display='none';}
document.getElementById(linksID).style.display='block';document.getElementById(textID).style.display='block';document.getElementById(linkID).style.display='none';return;}
function getElementsByStyleClass(className){var all=document.all?document.all:document.getElementsByTagName('*');var elements=new Array();for(var e=0;e<all.length;e++)
if(all[e].className==className)
elements[elements.length]=all[e];return elements;}
function hideAllDivs(){var blockDivs=getElementsByStyleClass("source_names_list");for(var i=0;i<blockDivs.length;i++){blockDivs[i].style.display='none';}
var sourcelist=document.getElementById('SOURCELIST');if(sourcelist.innerHTML==""){var d=document.getElementById('showSourceList');var info=d.getElementsByTagName("div");for(var e=0;e<info.length;e++){if(info[e].id=='SOURCELIST'){sourcelist=info[e];}}}
sourcelist.style.display='none';return;}
function showNextLink(cat,group){hideAllDivs();var listID='list_c'+cat+'_g'+group;var linkID='link_c'+cat+'_g'+group;var textID='text_c'+cat+'_g'+group;document.getElementById(listID).style.display='block';var sourcelist=document.getElementById('SOURCELIST');if(sourcelist.innerHTML==""){var d=document.getElementById('showSourceList');var info=d.getElementsByTagName("div");for(var e=0;e<info.length;e++){if(info[e].id=='SOURCELIST'){sourcelist=info[e];}}}
sourcelist.style.display='block';var textDivs=getElementsByStyleClass("display_text");for(var i=0;i<textDivs.length;i++){if(textDivs[i].style.display='block'){textDivs[i].style.display='none';}}
var linkDivs=getElementsByStyleClass("display_link");for(var i=0;i<linkDivs.length;i++){if(linkDivs[i].style.display='none'){linkDivs[i].style.display='block';}}
document.getElementById(linkID).style.display='none';document.getElementById(textID).style.display='block';return;}
prntPackPop=null;function prntPack(args,width,height)
{if(prntPackPop&&(!prntPackPop.closed))
{prntPackPop.close();}
prntPackPop=window.open(args,"prntPackRef","width="+width+",height="+height+",toolbar=no,menubar=no,scrollbars=no,resizable=yes,location=no,directories=no");prntPackPop.focus();}
function doQuote(sym,exch){window.opener.location="/quotes/"+qp.common.makeSym(sym)+"/"+exch;}
function getTabString(tab){if(tab==0){return"News ";}else if(tab==1){return"Press Release ";}else if(tab==2){return"Trade ";}else if(tab==3){return"Blogs ";}else if(tab==4){return"Regional ";}else if(tab==5){return"";}else{return"";}}
function getElementFromTableRow(tr,id){if(tr&&id){var tds=tr.getElementsByTagName("td");for(var j=0;j<tds.length;j++){var td=tds[j];if(td.id&&td.id==id){return td;}}}}
function getRowFromTable(t,rowid){if(t&&rowid){var trs=t.getElementsByTagName("tr");for(var j=0;j<trs.length;j++){var tr=trs[j];if(tr.id&&tr.id==rowid){return tr;}}}};function updateOmniture(pgn){if(pgn&&s_265){s_265.pageName=s_265.pfxID+" : "+pgn;if(pgn==null||pgn=="null"||pgn==""){s_265.pageName=s_265.pfxID+" : "+document.title;}
var s_code=s_265.t();if(s_code)document.write(s_code)}}
function updateColorClass(o,newClass){var clsName=null;if(o)clsName=o.className;if(clsName){clsName=replaceCurrentColorClass(clsName,newClass);if(jsdebug)debug("MyPortfoliosUpdater:updateValWithColour - new className is: "+clsName);o.className=clsName;}}
function replaceCurrentColorClass(clsName,newClsName){var classColors=new Array("red","green","black","up","down","non-mover");if(clsName&&clsName.length!=0){for(var i=0;i<classColors.length;i++){if(clsName.indexOf(classColors[i])>=0){clsName=clsName.replace(classColors[i],newClsName);return clsName;}}
if(newClsName&&newClsName.length!=0)clsName=clsName+" "+newClsName;return clsName;}else{if(newClsName&&newClsName.length!=0)return newClsName;else return"";}}
function checkBrowser(){var agt=navigator.userAgent.toLowerCase();var is_major=parseInt(navigator.appVersion);var browser="";if(agt.indexOf("gecko")!=-1){browser="is_gecko";}
if((agt.indexOf('mozilla')!=-1)&&(agt.indexOf('spoofer')==-1)&&(agt.indexOf('compatible')==-1)&&(agt.indexOf('opera')==-1)&&(agt.indexOf('webtv')==-1)){browser="is_nav";}
if(agt.indexOf("mac")!=-1){browser="is_mac";}
return browser;}
advanceCreateWin=null;function openAdvancedCreateWindowFromTicker(_url)
{if(checkBrowser()=="is_mac"){advanceCreateWin=window.open(_url,'advCreateWin','resizable=yes, toolbar=no, location=no, directories=no, scrollbars=yes, status=yes, width=728, height=420');}else{if(advanceCreateWin!=null)advanceCreateWin.close();advanceCreateWin=window.open(_url,'advCreateWin','resizable=yes, toolbar=no, location=no, directories=no, scrollbars=yes, status=yes, width=728, height=395');}
advanceCreateWin.focus();}
createWin=null;function openCreateWindowFromTicker(_url)
{if(checkBrowser()=="is_mac"){createWin=window.open(_url,'createWin','resizable=yes, toolbar=no, location=no, directories=no, scrollbars, status=yes, width=875, height=500');}else{createWin=window.open(_url,'createWin','resizable=yes, toolbar=no, location=no, directories=no, scrollbars, status=yes, width=875, height=500');}
createWin.focus();}
editWin=null;function openEditWindowFromTicker(_url)
{editWin=window.open(_url,'editWin','resizable=yes, toolbar=no, location=no, directories=no, scrollbars, status=yes, width=875, height=500');editWin.focus();}


/*Relegence Generic Functions */
var newsTab = null;
function requestArticles(riverSize, sourceGroup, superSourceGroup, divName, clustered, relMin, ticker, country, seoname, pDate, newsHub, pageNum, pageHandle) 
{
        //.ok
        //hack to be removed later...done to avoid build
        //var clustered="true";
        //if(curPage == pgIndicator){
            if(storedRelavancy == undefined ||storedRelavancy == ""){
                storedRelavancy = defaultRelavancy;
            } 
            if(relMin == undefined || relMin==""){
                relMin=storedRelavancy;
            }
       /* }else
        {
             storedRelavancy = defaultRelavancy;
             relMin=defaultRelavancy;
             curPage = pgIndicator;
             
        }*/
        
        
            //alert("cursrc grp not nll in the request articles");
            //alert(sourceGroup);
        if (riverSize == "undefined" || riverSize=="")
            riverSize="40";
            
        if(sourceGroup==""){
            newsTab = new RelegenceTab(relMin, riverSize, sourceGroup, superSourceGroup, 0, divName, clustered, ticker, country, seoname, pDate, 'generic', pageNum, pageHandle);
            displayEmptyTab(newsTab);
        }else{
            newsTab = new RelegenceTab(relMin, riverSize, sourceGroup, superSourceGroup, 0, divName, clustered, ticker, country, seoname, pDate, 'generic', pageNum, pageHandle);
            //alert("calling getAssetsMetaCanned");
            getAssetsMetaCanned(clustered, riverSize, ticker, country, sourceGroup, relMin, newsTab.dateFrom, 'getAssetsNewsCallback', pageHandle);      
            
        }
}

function getAssetsNewsCallback(json) 
{
    //This is the callBack used when you make your Movies query, you 
    //noted JSON format (&f) and callback name (&c) in the url.
    //"http://pfdlrdc-d01.....getAssetsMetaClustered?f=json.............&c=getAssetsNewsCallback
    //.ok
  

    var tabObj = newsTab;
    if(typeof json.data.metaResponse.queryRslts == "undefined") {
        //alert("result not defined");
        return;
    }
    var results = json.data.metaResponse.queryRslts;
    if (results.length <= 0) {
        //alert("result <0");
        return;
    }
    var qryResult = results[0];
    tabObj.subscription = qryResult.queryRslt.subscriptionTopic;
    tabObj.nextPageHandle = qryResult.queryRslt.pageHandle;
    var assets = null;
    if (tabObj.clustered == "true") {
        assets = qryResult.queryRslt.clusters;
    }  else {
        var assets = qryResult.queryRslt.assets;
    }
    if (typeof assets != "undefined" && assets.length > 0) {
        //alert("result .lenght>0");
        var assetsArray = new Array();
        for (var i=0; i<assets.length; i++) {
            var asset = null;
            var relObj = new Object();
            if (tabObj.clustered == "true") {
                asset = assets[i].cluster.assets[0]; 
                relObj.topicID = assets[i].cluster.topicId;
                var related = assets[i].cluster.assetsRelated;
                var total_count = 0;
                if (typeof related != "undefined") {
                var fParts = tabObj.superSourceGroup.split(',');
                
                for (var j=0; j < fParts.length; j++) {
                    for (var k=0; k<related.length; k++) {
                        if (fParts[j] == related[k].sourceGroup) {
                            total_count = total_count + related[k].count;
                        }
                    }
                }
                }
                relObj.relatedCount = total_count;
            } else {
                asset = assets[i]; 
            }
            relObj.pubdate=formatRelegenceDate(asset.publishDate, "false");
            relObj.dateLast=formatRelegenceDate(asset.publishDate, "true");
            relObj.shortDate=formatShortDate(asset.publishDate, "true");
            relObj.longDate=formatLongDate(asset.publishDate);
            relObj.assetID = asset.asset.id;
            if (typeof asset.snippet == "undefined") {
                relObj.snippet = "";
            } else {
                relObj.snippet = encodeSnippet(asset.snippet);
            }
            relObj.url = asset.url;
            relObj.headline = asset.headline;
            relObj.mediaType = asset.mediaType;
            relObj.source = asset.source;
            assetsArray[i] = relObj;
        }
        tabObj.assets = assetsArray;
    }   
    //alert("calling buildupHtml");
    buildUpHtml(tabObj);
    newsBoxWidget.updateSubscription(tabObj.subscription);
    tickersloaded = true;
}
function openNewsWindow(url)
{
    //.ok
	newsWin=window.open(url,'newsWin');
}
function buildUpHtml(tabObj) {
    // get the company id and register with aim at some point. 
    //.ok
    //alert("inside buildupHtml");
    var inHtml = "";
    var assets = tabObj.assets;
    if (assets.length > 0) {
       // alert("inside buildupHtml assets.legth>0");
        for (var i=0; i<assets.length; i++) {
            var asset = assets[i];
            inHtml = inHtml + "<li class=\"";
            if (tabObj.clustered == "true") {
                inHtml = inHtml + asset.topicID;
            } else {
                inHtml = inHtml + asset.assetID;
            }
            inHtml = inHtml +"\">";
            inHtml = inHtml + "<h4><a href=\""+asset.url+"\" onClick=\"javascript:openNewsWindow('"+asset.url+"');return false;\" property=\"f:title\" onmouseover=\"handleHeadlineHover(event, '"+asset.pubdate+"','"+asset.snippet+"','"+tabObj.sourceGroup+"','"+tabObj.riverSize+"')\" onmouseout=\"hideHeadlines()\">" +asset.headline+"</a></h4>";
            inHtml = inHtml + "<div class=\"details\">";
            if( asset.pubdate.indexOf("AM") == -1 && asset.pubdate.indexOf("PM") == -1)
            {
                inHtml = inHtml + "<span class=\"time\" property=\"f:date\">" + asset.pubdate + "</span>";
            } else {
                inHtml = inHtml + "<span class=\"time_bold\" property=\"f:date\">" +asset.pubdate+"</span>";
            }
            if (tabObj.clustered == "true" ){//&& pgIndicator == 0) {
                var relatedCount = asset.relatedCount - 1;
                if (relatedCount > 0) {
                    //inHtml = inHtml + "<a href=\"#\" onmouseover=\"handleRelatedArticlesHover(event,'"+tabObj.sourceGroup+"','7', '"+tabObj.superSourceGroup+"', '"+tabObj.symbol.toUpperCase()+"','"+tabObj.country+"', '"+tabObj.seoname+"', '"+asset.topicID+"','5','"+asset.assetID+"')\"> View all Related Articles</a>  |";
                    //actual inHtml = inHtml + "&nbsp;"+"<a href=\"#\" onmouseover=\"handleRelatedArticlesHover(event,'"+tabObj.sourceGroup+"','7', '"+tabObj.superSourceGroup+"', '"+tabObj.symbol.toUpperCase()+"','"+tabObj.country+"', '"+asset.topicID+"','5','"+asset.assetID+"')\"> View all Related Articles</a>  |";
                     var callbackfunction="relatedArticlesCallback"; 
                     relegenceTopics=tabObj.sourceGroup;
                     currentTopicId=asset.topicID;
                    var relLink="";
                    var  urlArr = RTN_QUERYTXT.toString().split(":");
                    //relLink = "\/"+urlArr[0]+"-"+urlArr[1]+"\s/"+ENTITY_NAME+"\/"+urlArr[2]+"?selectedTab=snapShot&view=relatedNews#statsNav";
                    if(pgIndicator==0)
                        relLink = "\/"+urlArr[0]+"-"+urlArr[1]+"\s/"+ENTITY_NAME+"\/"+urlArr[2]+"?selectedTab=snapShot&view=relatedNews&srcGrp="+tabObj.sourceGroup+"&TpcId="+asset.topicID+"#statsNav";
                    else
                        relLink = "\/"+urlArr[0]+"-"+urlArr[1]+"\s/"+ENTITY_NAME+"\/"+"news?view=relatedNews&srcGrp="+tabObj.sourceGroup+"&TpcId="+asset.topicID;
                }
            } 
            inHtml = inHtml + "<span class=\"source\" property=\"f:source\">";
            if (asset.mediaType == "video") {
                inHtml = inHtml + "<img height=\"13\" width=\"18\" src=\""+imgDir+"icons/icon-video.gif\" />";
            }
            inHtml = inHtml + asset.source + "</span></div></li>"; //added break-as
        }
          
        populateLastHeadlineDate(document.getElementById(tabObj.divName), assets[0].dateLast);
        //populateLastHeadlineDate(document.getElementById("tabDate"), assets[0].dateLast);                                   
    } else {
        inHtml = inHtml + "<li class=\"riverEmpty\"><span class=\"headline empty\" property=\"f:title\">";
        inHtml = inHtml + "Sorry, there are no matches for this topic.</span></li>";    
    }
    var tabDiv = document.getElementById(tabObj.divName);
    var list = tabDiv.getElementsByTagName("ul");
    for(var x=0; x < list.length; x++) {
        if(list[x].className == "headlines") {
            ulObj = x;
            x=list.length;
        }
    }
    if(_allNews == '1'){
	    if(tabObj.pageNum>1){
	        inHtml=inHtml+"<a href=\"#\" onClick=\"submitNewsForm('0',1);return false;\">&lt;Page 1&gt;</a>&nbsp;&nbsp;";
	    }
	    inHtml=inHtml+tabObj.pageNum+"&nbsp;&nbsp;";
	    if(tabObj.nextPageHandle!=0){
	       var pageNum=tabObj.pageNum+1;
	       inHtml=inHtml+"<a href=\"#\" onClick=\"submitNewsForm('"
	              +tabObj.nextPageHandle+"',"+pageNum
	              +");return false;\">&lt;Next&gt;</a>&nbsp;&nbsp;";
	     }
    }

    list[ulObj].innerHTML = inHtml;  
    
}

function displayEmptyTab(newsTab){
    var llObj= -1;
    var innerHtml;
    innerHtml = "<li class=\"riverEmpty\"><span class=\"headline empty\" property=\"f:title\">";
    innerHtml = innerHtml + "Source is turned off or not available.</span></li>"; 
    
    var tabObj=newsTab;
    var tabDiv = document.getElementById(tabObj.divName);
    var list = tabDiv.getElementsByTagName("ul");
    for(var x=0; x < list.length; x++) {
        if(list[x].className == "headlines") {
            llObj = x;
            x=list.length;
        }
    }
    list[llObj].innerHTML = innerHtml; 
    
    var list = tabDiv.getElementsByTagName("span");
    for (var x=0; x < list.length; x++) {
        if (list[x].className == "headlineDate") {
	        list[x].innerHTML = "" ;
	 }
    }
}

function relatedArticlesHoverCallback(json) {
    if(customBoxFlag=="1"){

        hideRelated();
        return;
    }
        
    //debugger;
    //if(typeof json.response.data.getRelatedResponse.relatedResponse == "undefined") {
    if(typeof json.data.metaResponse.queryRslts == "undefined") {

        hideRelated();
        return;
    } else {
        var infodiv = document.getElementById("headlinesInfo");
        if (infodiv != null && infodiv.style.display == "block") {
            return;
        }
    }
   // var assets = json.response.data.getRelatedResponse.assets;
    var assets = json.data.metaResponse.queryRslts[0].queryRslt.assets;

    if (assets.length > 0) {
        var inHtml = "<ul>";
        var lineCount = 1;
        for (var i=0; i<assets.length; i++) {
            var asset = assets[i];
            if (asset.asset.id != currentHoverID) {
                inHtml = inHtml + "<li><a href=\""+asset.url+"\" onClick=\"javascript:openNewsWindow('"+asset.url+"');return false;\">"+asset.headline+"</a> " + formatRelegenceDate(asset.publishDate) + " | ";
                if (asset.mediaType == "video") {
                }
                inHtml = inHtml + asset.source + "</li>"; 
                lineCount = lineCount + 1;
            }
            if (lineCount == assets.length) {
                // We've got 2 stories displayed already
                i = assets.length;
            }
        }
        if (currentTicker == "") {
        }

        var relLink="";
        var  urlArr = RTN_QUERYTXT.toString().split(":");
        if(pgIndicator==0)
            relLink = "\/"+urlArr[0]+"-"+urlArr[1]+"\s/"+ENTITY_NAME+"\/"+urlArr[2]+"?selectedTab=snapShot&view=relatedNews&srcGrp="+relegenceTopics+"&TpcId="+currentTopicID+"#statsNav";
        else
            relLink = "\/"+urlArr[0]+"-"+urlArr[1]+"\s/"+ENTITY_NAME+"\/"+"news?view=relatedNews&srcGrp="+relegenceTopics+"&TpcId="+currentTopicID;

        inHtml = inHtml +"</ul>";
        inHtml = inHtml +"<a href=\'"+relLink+"'> View all Related Articles</a><!--[if lt IE 7]><iframe></iframe><![endif]-->";
        

        relatedInfoDiv.firstChild.innerHTML = inHtml;
        relatedInfoDiv.style.display = "block";
        if (typeof RTN_HOVER_TIMEOUT == "undefined") {
            var RTN_HOVER_TIMEOUT = 16000;
        }
    	setTimeout('hideRelated()', RTN_HOVER_TIMEOUT);
    } else {
        hideRelated();
   }
}
function formatShortDate(newsDate, timezoneOn) {  
    //.ok
    todayString = getTodaysDate();
    var parsedDate = parseDate(newsDate); 
    var articleDate = weekday[parsedDate.getDay()] + ", " + month[parsedDate.getMonth()] + " " + parsedDate.getDate() + ", " + parsedDate.getFullYear();
    if (todayString == articleDate)  {
       var a_p = "PM";
       var curr_hour = parsedDate.getHours();
       if (curr_hour < 12)
       {
           a_p = "AM";
       }
       if (curr_hour == 0) {
           curr_hour = 12;
       }
       if (curr_hour > 12) {
           curr_hour = curr_hour - 12;
       }
       if (timezoneOn == "true") {
           var timezone = "EST";
           if (RTN_DAYLIGHT == "true") {
               timezone = "EDT";
           }
           return (curr_hour+":"+checkTime(parsedDate.getMinutes()) + ":" + checkTime(parsedDate.getSeconds()) + " " + a_p + " " + timezone) ;
       } else {
           return (curr_hour+":"+checkTime(parsedDate.getMinutes()) + ":" + checkTime(parsedDate.getSeconds()) + " " + a_p);
       }
   } else {
       return(articleDate);
   }
}

function formatLongDate(newsDate) {
    //.ok
    var parsedDate = parseDate(newsDate); 
    var articleDate = weekday[parsedDate.getDay()] + ", " + month[parsedDate.getMonth()] + " " + parsedDate.getDate() + ", " + parsedDate.getFullYear();
    return articleDate;
}

function getTodaysDate() {
    today = new Date();
    var timezoneoffset = today.getTimezoneOffset();
    today.setTime(today.getTime() + timezoneoffset*60*1000);
    var etOffset = -5;
    if (RTN_DAYLIGHT == "true") {
        etOffset = -4;
    }
    today.setTime(today.getTime() + etOffset*60*60*1000);
       
    var todayString = weekday[today.getDay()] + ", " + month[today.getMonth()] + " " + today.getDate() + ", " + today.getFullYear();
    return todayString;
}

function parseDate(newsDate) {
    var timezoneoffset = today.getTimezoneOffset();
    var sDate = Date.parse(newsDate);
    var parsedDate = new Date();
    parsedDate.setTime(sDate);
    parsedDate.setTime(parsedDate.getTime() + timezoneoffset*60*1000);
    var etOffset = -5;
    if (RTN_DAYLIGHT == "true") {
        etOffset = -4;
    }
    parsedDate.setTime(parsedDate.getTime() + etOffset*60*60*1000);
    return parsedDate;
} 

function formatBeginDate(bDate) {
    var splitDate = bDate.split("/");
    var parsedDate = new Date();
    var month = splitDate[0] - 1;
    parsedDate.setMonth(month);
    parsedDate.setDate(splitDate[1]);
    parsedDate.setFullYear(splitDate[2]);
    parsedDate.setHours(23);
    parsedDate.setMinutes(59);
    parsedDate.setSeconds(59);
    return parsedDate.toUTCString();
}
function RelegenceTab(relMin, riverSize, sourceGroup, superSourceGroup, tab, divName, clustered, symbol, country, seoname, pDate, hubPage, pageNum, pageHandle) {
    this.relMin = relMin;
    this.riverSize = riverSize;
    this.superSourceGroup = superSourceGroup;
    this.tab = tab;
    this.divName = divName;
    this.sourceGroup = sourceGroup;
    this.clustered = clustered;
    this.assets = new Array();
    this.symbol = symbol;
    this.country = country;
    this.seoname = seoname;
    this.hubPage = hubPage;
    if (typeof pDate == "undefined" || pDate == "") {
        this.dateFrom = "";
    } else {
        this.dateFrom = formatBeginDate(pDate);
    }
    this.pageNum = pageNum;
    this.pageHandle = pageHandle;
    this.nextPageHandle = 0;    
}
function checkTimeZone() {
   var rightNow = new Date();
   var date1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
   var date2 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0);
   var temp = date1.toGMTString();
   var date3 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
   var temp = date2.toGMTString();
   var date4 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
   var hoursDiffStdTime = (date1 - date3) / (1000 * 60 * 60);
   var hoursDiffDaylightTime = (date2 - date4) / (1000 * 60 * 60);
   if (hoursDiffDaylightTime == hoursDiffStdTime) { 
      alert("Time zone is GMT " + hoursDiffStdTime + ".\nDaylight Saving Time is NOT observed here.");
   } else {
      alert("Time zone is GMT " + hoursDiffStdTime + ".\nDaylight Saving Time is observed here.");
   }
}


function calculateSrcGrp(element){

        var cookie = new Array();
        readTheCookie(cookie);
        
        var newssource = cookie["news"];
        var blogsource = cookie["blogs"];
        var regsource = cookie["reg"];

        var curSourceGrp;//=""; 
        
	
        if(element.value.toString()=="1")
        {
            if(newssource=="0"){
                curSourceGrp="";
            }
            else{
                curSourceGrp=mediatypes.srcGroup[1].id
            }

        }
        else if(element.value.toString()=="2")
        {
            if(blogsource=="0"){
                curSourceGrp="";
            }
            else{
                curSourceGrp=mediatypes.srcGroup[2].id
            }
        }
        else if(element.value.toString()=="3")
        {
            if(regsource=="0"){
                curSourceGrp="";
            }
            else{
                curSourceGrp=mediatypes.srcGroup[3].id
            }
        }
        else{
            //its all tab call
            curSourceGrp="";
            if (newssource!="0")
            {
               // curSourceGrp="2050";
		curSourceGrp =mediatypes.srcGroup[1].id;
            }
            if (blogsource!="0")
            {   
                if(curSourceGrp==""){
                    //curSourceGrp="2051";
		    curSourceGrp =mediatypes.srcGroup[2].id;
		}
                else{
                   //curSourceGrp+=",2051";
		   curSourceGrp+=","+mediatypes.srcGroup[2].id;
		}
            }
            if(regsource!="0")
            {
                if(curSourceGrp==""){
                    //curSourceGrp="2052";
		    curSourceGrp =mediatypes.srcGroup[3].id;
		}	
                else{
                   //curSourceGrp+=",2052";
		   curSourceGrp+=","+mediatypes.srcGroup[3].id;
		}
            }
            
        }
       // alert ("calc :"+curSourceGrp);
        return curSourceGrp;

}
//checkTimeZone Notes.
//The variable date1 is initially set to the 1st of January (month 0 in JavaScript) this year. The variable date2 is initially set to the 1st of July (month 6 in JavaScript) this year. Then date1 is converted to a GMT string. This format will be something like Fri, 25 Apr 2003 00:00:00 UTC. In fact, your computer's clock as of when this page was loaded gives a GMT string of Wed, 9 Apr 2008 15:08:59 UTC. The variable date3 pulls out everything except the time zone from that string. (The time zone says "UTC", and we want this date to be in the local time zone). So that GMT time (in the local time zone) minus the actual time (in the local time zone) is the number of hours away from GMT we are at this point. By your computer information, this difference is -4.
//All JavaScript dates are in milliseconds, so 1000 milliseconds times 60 seconds times 60 minutes is the number of milliseconds in one hour. This is the methodology used to compare the hours. The check of time in January sets the benchmark for winter for both old and new methods of determination. 
//The summer time check serves the same purpose in both old and new methods, establishing the benchmark for summer comparison. If the calculated number of hours difference changes from January to July, then daylight saving time is observed in this time zone. (However, keep in mind that not all locations within a specific time zone honor DST.) Based on the information provided by your computer and login, daylight saving time IS observed in this time zone.
//This code is valid in time zones that are partial (not full hour differences) also, such as a quarter hour or a half hour difference from GMT, in some parts of the world. The hoursDiffStdTime variable value will obviously not be a whole number; the fractional part will be .25, .5, or .75 depending on the time zone value. Pay particular attention in your coding NOT to make that variable an integer. The button below will test the actual Javascript code within this page. It is identical code implementation to what is shown above.

/* Relegence Tab Functions */
function SetTab(element)
{
	liArray=document.getElementById("tabBar").childNodes;
        
        var newsTab;
        
	i=0;
	while(liArray[i])
	{
	    if(liArray[i].id =="tabBlank")
            {
                liArray[i].id="tabBlank";
		i++;
            }
            else
            {
                liArray[i].id="";
		i++;
            }
	}
        
	element.id="cur";
	
	//alert("here ac1:"+curSourceGrp);	
        var curSourceGrp= calculateSrcGrp(element);
	//alert("here ac2:"+curSourceGrp);
        document.getElementById("MasterRW").setAttribute("sourceGroup",curSourceGrp);
	document.getElementById("MasterRW").setAttribute("supersourcegroup",curSourceGrp);
        
	if(storedCluster=="on"){cluster="true";}else{cluster="false";}
       	
        if(curSourceGrp=="" || curSourceGrp =="undefined"){
	    
            document.getElementById("MasterRW").setAttribute("riversize","0");
            requestArticles("0",curSourceGrp ,curSourceGrp, 'headlines-sub', cluster, storedRelavancy, RTN_QUERYTXT, 'USA');      
        }else{
            document.getElementById("MasterRW").setAttribute("riversize",maxNewsItems);           
            requestArticles(maxNewsItems,curSourceGrp ,curSourceGrp, 'headlines-sub', cluster, storedRelavancy, RTN_QUERYTXT, 'USA');	
      
        }
        
        document.body.focus();	
}


/*DATE Functions */

var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";


var month=new Array(12);
month[0]="January";
month[1]="February";
month[2]="March";
month[3]="April";
month[4]="May";
month[5]="June";
month[6]="July";
month[7]="August";
month[8]="September";
month[9]="October";
month[10]="November";
month[11]="December";
var today = new Date();

function formatRelegenceDate(newsDate, timezoneOn) {
     //.ok
     var today = new Date();
       var timezoneoffset = today.getTimezoneOffset();
       today.setTime(today.getTime() + timezoneoffset*60*1000);
       var etOffset = -5;
       var timezone = "EST";
       if (RTN_DAYLIGHT == "true") {
           etOffset = -4;
           timezone = "EDT";
       }
       today.setTime(today.getTime() + etOffset*60*60*1000);
       var todayString = (today.getMonth()+1) + "/" + today.getDate() + "/" + today.getFullYear();
       
       var sDate = Date.parse(newsDate);
       var parsedDate = new Date();
       parsedDate.setTime(sDate);
       parsedDate.setTime(parsedDate.getTime() + timezoneoffset*60*1000);
       parsedDate.setTime(parsedDate.getTime() + etOffset*60*60*1000);
      
       var day = parsedDate.getDate();
       var month = parsedDate.getMonth() + 1;
       var year = parsedDate.getFullYear();
       if (todayString == (month + "/" + day + "/" + year))  {
           var a_p = "PM";
           var curr_hour = parsedDate.getHours();
           if (curr_hour < 12)
           {
               a_p = "AM";
           }
           if (curr_hour == 0) {
               curr_hour = 12;
           }
           if (curr_hour > 12) {
               curr_hour = curr_hour - 12;
           }
           if (timezoneOn == "true") {
               return (curr_hour+":"+checkTime(parsedDate.getMinutes()) + ":" + checkTime(parsedDate.getSeconds()) + " " + a_p + " " + timezone) ;
           } else {
               return (curr_hour+":"+checkTime(parsedDate.getMinutes()) + ":" + checkTime(parsedDate.getSeconds()) + " " + a_p);
           }
       } else {
           var yearString = new String(year);
           return(checkTime(month) + "/"+checkTime(day) + "/" + yearString.slice(2));
           yearString = null;
       }
   }
   
function getDateToday() {
    //debugger;
    var today = new Date();
    var timezoneoffset = today.getTimezoneOffset();
    today.setTime(today.getTime() + timezoneoffset*60*1000);
    var etOffset = -5;
    if (RTN_DAYLIGHT == "true") {
        etOffset = -4;
    }
    today.setTime(today.getTime() + etOffset*60*60*1000);
    return today;
}