var buttons;
var buttonsPreloaded = false;
function preloadButtons() {
    if (!document.images ) { return; }
    buttons = new Array();

    /* Top Navigation */
    buttons["topnav01"] = new Object();
    buttons["topnav01"].normal = new Image(66, 32);
    buttons["topnav01"].normal.src = "/images/topnav1_off.gif";
    buttons["topnav01"].hover = new Image(66, 32);
    buttons["topnav01"].hover.src = "/images/topnav1_on.gif";

    buttons["topnav02"] = new Object();
    buttons["topnav02"].normal = new Image(104, 32);
    buttons["topnav02"].normal.src = "/images/topnav2_off.gif";
    buttons["topnav02"].hover = new Image(104, 32);
    buttons["topnav02"].hover.src = "/images/topnav2_on.gif";

    buttons["topnav03"] = new Object();
    buttons["topnav03"].normal = new Image(104, 32);
    buttons["topnav03"].normal.src = "/images/topnav3_off.gif";
    buttons["topnav03"].hover = new Image(104, 32);
    buttons["topnav03"].hover.src = "/images/topnav3_on.gif";

    buttons["topnav04"] = new Object();
    buttons["topnav04"].normal = new Image(62, 32);
    buttons["topnav04"].normal.src = "/images/topnav4_off.gif";
    buttons["topnav04"].hover = new Image(62, 25);
    buttons["topnav04"].hover.src = "/images/topnav4_on.gif";

    buttons["topnav05"] = new Object();
    buttons["topnav05"].normal = new Image(70, 32);
    buttons["topnav05"].normal.src = "/images/topnav5_off.gif";
    buttons["topnav05"].hover = new Image(70, 25);
    buttons["topnav05"].hover.src = "/images/topnav5_on.gif";
    
    buttons["topnav06"] = new Object();
    buttons["topnav06"].normal = new Image(87, 32);
    buttons["topnav06"].normal.src = "/images/topnav6_off.gif";
    buttons["topnav06"].hover = new Image(87, 25);
    buttons["topnav06"].hover.src = "/images/topnav6_on.gif";
    
    buttons["topnav07"] = new Object();
    buttons["topnav07"].normal = new Image(56, 32);
    buttons["topnav07"].normal.src = "/images/topnav7_off.gif";
    buttons["topnav07"].hover = new Image(56, 25);
    buttons["topnav07"].hover.src = "/images/topnav7_on.gif";
    
    buttons["topnav08"] = new Object();
    buttons["topnav08"].normal = new Image(99, 32);
    buttons["topnav08"].normal.src = "/images/topnav8_off.gif";
    buttons["topnav08"].hover = new Image(99, 25);
    buttons["topnav08"].hover.src = "/images/topnav8_on.gif";
    /* all done */
    
    buttonsPreloaded = true;
    return;
}

function stickButton(buttonName) {
    if (!document.images) { return; }
    if (!buttonsPreloaded) { return; }
    if (!buttonName || buttonName == "") { return; }
    var target = $(buttonName);
    if (target) {
        eval("buttons['" + buttonName + "']." + "normal.src = buttons['" + buttonName + "']." + "hover.src");
        target.src = eval("buttons['" + buttonName + "']." + "hover.src");
    }
    return;
}
function switchButton(buttonName, buttonState) {
    if (!document.images) { return; }
    if (!buttonsPreloaded) { return; }
    if (!buttonName || buttonName == "") { return; }
    if (!buttonState || buttonState == "") { return; }
    if (document.getElementById) {
        var target = document.getElementById(buttonName);
    } else if (document.all) {
        var target = document.all(buttonName);
    } else if (document.layers) {
        var target = document.images[buttonName];
    }
    if (target) {
        target.src = eval("buttons['" + buttonName + "']." + buttonState + ".src");
    }
    return;
}

/* Function for clearning a text field onfocus */
function clearText(thefield){
    if (thefield.defaultValue==thefield.value)
    thefield.value = ""
}
/*******************************************************************
* JavaScript RSS Reader
*************************/

//OBJECTS
//objects inside the RSS2Item object
function RSS2Enclosure(encElement) {
    if (encElement == null) {
        this.url = null;
        this.length = null;
        this.type = null;
    } else {
        this.url = encElement.getAttribute("url");
        this.length = encElement.getAttribute("length");
        this.type = encElement.getAttribute("type");
    }
}
function RSS2Guid(guidElement) {
    if (guidElement == null) {
        this.isPermaLink = null;
        this.value = null;
    } else {
        this.isPermaLink = guidElement.getAttribute("isPermaLink");
        this.value = guidElement.childNodes[0].nodeValue;
    }
}
function RSS2Source(souElement) {
    if (souElement == null) {
        this.url = null;
        this.value = null;
    } else {
        this.url = souElement.getAttribute("url");
        this.value = souElement.childNodes[0].nodeValue;
    }
}
//object containing the RSS 2.0 item
function RSS2Item(itemxml)
{
    //required
    this.title;
    this.link;
    this.description;
    //optional vars
    this.author;
    this.comments;
    this.pubDate;
    //optional objects
    this.category;
    this.enclosure;
    this.guid;
    this.source;
    var properties = new Array("title", "link", "description", "author", "comments", "pubDate");
    var tmpElement = null;
    for (var i=0; i<properties.length; i++)
    {
        try {
            tmpElement = itemxml.getElementsByTagName(properties[i])[0];
            if (tmpElement != null  && tmpElement.childNodes[0] != null)
                eval("this."+properties[i]+"=tmpElement.childNodes[0].nodeValue");
        } catch (e) {
            eval("this."+properties[i]+"=''");
        }        
    }
    this.category = new RSS2Category(itemxml.getElementsByTagName("category")[0]);
    this.enclosure = new RSS2Enclosure(itemxml.getElementsByTagName("enclosure")[0]);
    this.guid = new RSS2Guid(itemxml.getElementsByTagName("guid")[0]);
    this.source = new RSS2Source(itemxml.getElementsByTagName("source")[0]);
}
//objects inside the RSS2Channel object
function RSS2Category(catElement) {
    if (catElement == null) {
        this.domain = null;
        this.value = null;
    } else {
        this.domain = catElement.getAttribute("domain");
        this.value = catElement.childNodes[0].nodeValue;
    }
}
//object containing RSS image tag info
function RSS2Image(imgElement) {
    if (imgElement == null) {
    this.url = null;
    this.link = null;
    this.width = null;
    this.height = null;
    this.description = null;
    } else {
        imgAttribs = new Array("url","title","link","width","height","description");
        for (var i=0; i<imgAttribs.length; i++)
            if (imgElement.getAttribute(imgAttribs[i]) != null)
                eval("this."+imgAttribs[i]+"=imgElement.getAttribute("+imgAttribs[i]+")");
    }
}
//object containing the parsed RSS 2.0 channel
function RSS2Channel(rssxml)
{
    //required
    this.title;
    this.link;
    this.description;
    //array of RSS2Item objects
    this.items = new Array();
    //optional vars
    this.language;
    this.copyright;
    this.managingEditor;
    this.webMaster;
    this.pubDate;
    this.lastBuildDate;
    this.generator;
    this.docs;
    this.ttl;
    this.rating;
    //optional objects
    this.category;
    this.image;
    var chanElement = rssxml.getElementsByTagName("channel")[0];
    var itemElements = rssxml.getElementsByTagName("item");
    for (var i=0; i<itemElements.length; i++) {
        Item = new RSS2Item(itemElements[i]);
        this.items.push(Item);
        //chanElement.removeChild(itemElements[i]);
    }
    var properties = new Array("title", "link", "description", "language", "copyright", "managingEditor", "webMaster", "pubDate", "lastBuildDate", "generator", "docs", "ttl", "rating");
    var tmpElement = null;
    for (var i=0; i<properties.length; i++)
    {
        try {
            tmpElement = chanElement.getElementsByTagName(properties[i])[0];
            if (tmpElement != null  && tmpElement.childNodes[0] != null)
                eval("this."+properties[i]+"=tmpElement.childNodes[0].nodeValue");
        } catch (e) {
            eval("this."+properties[i]+"=''");
        }   
    }
    this.category = new RSS2Category(chanElement.getElementsByTagName("category")[0]);
    this.image = new RSS2Image(chanElement.getElementsByTagName("image")[0]);
}


//PROCESSES
//uses xmlhttpreq to get the raw rss xml
function getRSS(divId, url, number) {
    
    if (!number) { number = 0; }
    
    new Ajax.Request(url, { 
        method: 'get', 
        onSuccess: function(transport) {
            processRSS(divId, transport.responseXML, number); 
        }, onException: function (transport) {
        }, onFailure: function (transport) {
        } 
    });
}
//processes the received rss xml
function processRSS(divId, rssxml, number)
{
    RSS = new RSS2Channel(rssxml);
    showRSS(divId, RSS, number);
}
//shows the RSS content in the browser
function showRSS(divId, RSS, number)
{
    //default values for html tags used
    var imageTag = "<img id='chan_image'";
    var startItemTag = "";
    var startTitle = "<b>";
    var endTitle = "</b> ";    
    var startLink = "<a href='";
    var endLink = "</a><br>";    
    var startDescription = "<p>";
    var endDescription = "</p>&nbsp;";
    var endTag = "</div>";
    // //populate channel data
    // var properties = new Array("title","link","description","pubDate","copyright");
    // for (var i=0; i<properties.length; i++)
    // {
    //     eval("$('chan_"+properties[i]+"').innerHTML = ''");
    //     curProp = eval("RSS."+properties[i]);
    //     if (curProp != null)
    //         eval("$('chan_"+properties[i]+"').innerHTML = curProp");
    // }
    // //show the image
    // document.getElementById("chan_image_link").innerHTML = "";
    // if (RSS.image.src != null)
    // {
    //     $("chan_image_link").href = RSS.image.link;
    //     $("chan_image_link").innerHTML = imageTag
    //         +" alt='"+RSS.image.description
    //         +"' width='"+RSS.image.width
    //         +"' height='"+RSS.image.height
    //         +"' src='"+RSS.image.url
    //         +"' "+"/>";
    // }
    //populate the items
    $(divId).innerHTML = "";
    if (number == 0) {
        number = RSS.items.length;
    }
    for (var i=0; i < number; i++)
    {
        item_html = startItemTag;
        try {
            item_html += (RSS.items[i].link == null) ? "" : startLink + RSS.items[i].link + "'>";
            item_html += (RSS.items[i].title == null) ? "" : startTitle + RSS.items[i].title + endTitle;
            item_html += (RSS.items[i].link == null) ? "" : endLink;        
            item_html += (RSS.items[i].description == null) ? "" : startDescription + RSS.items[i].description + endDescription;
            item_html += (RSS.items[i].link == null) ? "" : ' ' + startLink + RSS.items[i].link + "'>More&nbsp;&raquo;</a><div class='sp8px'></div>";
        
            $(divId).innerHTML += item_html;
        } catch (e) {
            $(divId).innerHTML += '';
        }  
    }
    //we're done
    //document.getElementById("chan").style.visibility = "visible";
    return true;
}


//PROCESSES
//uses xmlhttpreq to get the raw rss xml
function getRSSList(divId, url, number) {
    
    if (!number) { number = 0; }
    
    new Ajax.Request(url, { 
        method: 'get', 
        onSuccess: function(transport) {
            processRSSList(divId, transport.responseXML, number); 
        }, onException: function (transport) {
        }, onFailure: function (transport) {
        } 
    });
}
//processes the received rss xml
function processRSSList(divId, rssxml, number)
{
    RSS = new RSS2Channel(rssxml);
    showRSSList(divId, RSS, number);
}

//shows the RSS content in the browser
function showRSSList(divId, RSS, number)
{
    //default values for html tags used
    var startBlock = "";
    var startLink = "<li><a href='";
    var endLink = "</a></li>";    
    var endBlock = "";
    $(divId).innerHTML = "";
    if (number == 0) {
        number = RSS.items.length;
    }
    $(divId).innerHTML += startBlock;
    for (var i=0; i < number; i++)
    {
        try {
            item_html = "";
            item_html += (RSS.items[i].link == null) ? "" : startLink + RSS.items[i].link + "'>";
            item_html += (RSS.items[i].title == null) ? "" : RSS.items[i].title;
            item_html += (RSS.items[i].link == null) ? "" : endLink;        
            $(divId).innerHTML += item_html;
        } catch (e) {
            $(divId).innerHTML += '';
        }  
    }
    $(divId).innerHTML += endBlock;
    //we're done
    return true;
}


function getNextOn()
    {
        // get next guest on BNN
        new Ajax.PeriodicalUpdater('nexton', '/NextOn.aspx',
        {
            method: 'GET',
            postBody: '',
            frequency: 1000,
            decay: 2
        });
    }

function getNextOnFlipper()
    {
        // get next guest on BNN
        new Ajax.PeriodicalUpdater('nextonflipper', '/NextOnFlipper.aspx',
        {
            method: 'GET',
            postBody: '',
            frequency: 1000,
            decay: 2
        });
    }
function GetMarketCallTonightGuestInfo()
    {
        // get next guest on BNN
        new Ajax.PeriodicalUpdater('marketcalltonightguestinfo', '/MarketCallGuestInfo.aspx?showid=7',
        {
            method: 'GET',
            postBody: '',
            frequency: 1000,
            decay: 2
        });
    }

function GetMarketCallGuestInfo()
    {
        // get next guest on BNN
        new Ajax.PeriodicalUpdater('marketcallguestinfo', '/MarketCallGuestInfo.aspx?showid=2',
        {
            method: 'GET',
            postBody: '',
            frequency: 1000,
            decay: 2
        });
    }
var featured_wrapper = null;
function getFeatureSegmentFlipper()
    {
        new Ajax.Request('/FeaturedSegmentsFlipper.aspx', {
          method:'get',
          onSuccess: function(transport){
            var flipperData = transport.responseText;
            var flipperDiv = $('featuresegmentflipper');
            flipperDiv.innerHTML = flipperData;
            featured_wrapper = new Glider('featured-wrapper', {duration:1});
          }
        });
    }

/*******************************************************************
* JavaScript Font Sizer 
* (c) DB Design, All rights are reserved
* http://phpscriptindex.com, phpsales@gmail.com
********************************************************************
* Script will allow user to visually change font size. Font size 
* will persist thru page change using a cookie.
********************************************************************
* Directions: Change fontElementId var to the element id you wish to
* allow users to change font sizes. 
********************************************************************
* Tip: Next span element inside normal div to inherit parent style
* but enable use to change font size.
*******************************************************************
* FireFox 2.0.0.3 Tested
* MS IE 7 Tested
* Netscape 8.1.2 Tested
* Opera 9.1 Tested
******************************************************************/
var fontElementId1 = "textResize1"; //CHANGE ME TO YOUR FIRST ELEMENT ID
var fontElementId2 = "textResize2"; //CHANGE ME TO YOUR SECOND ELEMENT ID
//DO NOT MODIFY BELOW
/* Module Change Font (string) */
function changeFont(fontClass){
    var element1 = document.getElementById(fontElementId1);
    //var element2 = document.getElementById(fontElementId2);
    element1.className = fontClass;
    //element2.className = fontClass;
    setCookie("fontSize", fontClass, 5);
}        
/* Module Set Default Font Size (void) */
function setDefaultFontSize(){
    var fontSize = getCookie("fontSize")
    if(fontSize){
        var element1 = document.getElementById(fontElementId1);
        //var element2 = document.getElementById(fontElementId2);
        element1.className = fontSize;
        //element2.className = fontSize;
    }
}
/* Module Set Cookie (string, string, int) -- http://www.w3schools.com/js/js_cookies.asp */
function setCookie(c_name,value,expiredays){
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
/* Module Get Cookie (string) -- http://www.w3schools.com/js/js_cookies.asp */
function getCookie(c_name){
    if(document.cookie.length>0){
        c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1){ 
            c_start=c_start + c_name.length+1;
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return false;
}


var tv_wrapper = null;
function getTVClips(bid, type, options)
{
    var jsonrequest = "";
    if (options != undefined && options != "") {
        var jsonrequest = "{\"bid\": \""+bid+"\", \"pubsetServiceId\": \"" + options + "\"}";
    } else {
        var jsonrequest = "{\"bid\": \""+bid+"\"}";
    }
    var clipbinURL = '/tvclips/tvclipsrss.aspx';    
    var packagebinURL = '/tvclips/alternative_tvclipsrss.aspx';
    var featuredBinURL = '/tvclips/featured_tvclipsrss.aspx';
    var dataUrl = clipbinURL;
    if (type == 'TODAY') {
        dataUrl = featuredBinURL;
    } else if (type == 'PKG') {
        dataUrl = packagebinURL;
    }

    new Ajax.Request(dataUrl, {
      method:'post',
      postBody:jsonrequest,
      requestHeaders: {Accept: 'application/json'},
      onSuccess: function(transport){
        var tvclips = transport.responseText.evalJSON();
        
        $('tvclipscomponent').innerHTML = "";
        
        var count = 1;
        /*
        To link to a Bin (usually a show):
        http://watch.bnn.ca/Redirect/?ShowId=xxx
        To link to an PubSet (usually a season)
        http://watch.bnn.ca/Redirect/?SeasonId=xxx
        To link to a Video Package (usually an episode)
        http://watch.bnn.ca/Redirect/?EpisodeId=xxx
        To link to a Clip
        http://watch.bnn.ca/Redirect/?ClipId=xxx
        */
        if (tvclips.tvclipsdata != null && tvclips.tvclipsdata.length > 0) {
            for(var i in tvclips.tvclipsdata)
            {
                var url = "";
                if(tvclips.tvclipsdata[i].type == "CLIP" || tvclips.tvclipsdata[i].type == "2")
                    url = "http://watch.bnn.ca/Redirect/?ClipId=" + tvclips.tvclipsdata[i].id ;
                if(tvclips.tvclipsdata[i].type == "VIDEO")
                    url = "http://watch.bnn.ca/Redirect/?EpisodeId=" + tvclips.tvclipsdata[i].id ;
                
                if(tvclips.tvclipsdata[i].title != null)
                    $('tvclipscomponent').innerHTML += "<div class=\"tvClipsVids\" id=\"section0"+count+"\"><a target=\"_blank\" href=\""+url+"\"><img src=\""+tvclips.tvclipsdata[i].imgUrl+"\" width=\"128\" height=\"80\" alt=\"\" /><div>"+tvclips.tvclipsdata[i].title+"</div></a></div>";
                count++;                
            }
            $('tvclipscomponent').innerHTML += "<br clear=\"all\" /><img src=\"images/spacer.gif\" width=\"568\" height=\"5\" alt=\"\" />";
            tv_wrapper = new Glider('tv-wrapper', {sectionClass: 'div.tvClipsVids', displayedElements:4});
            $('tvclips').show();
        } else {
            $('tvclips').hide();
        }
      }
    });
}

function switchTVClipsBin(linkId, bid) {
//    $(linkId).class = "";
    getTVClips(bid)
}

function getTVClipsAlt(bid)
{
    var jsonrequest = "{\"bid\": \""+bid+"\"}";
    
    new Ajax.Request('tvclips/tvclipsrss.aspx', {
      method:'post',
      postBody:jsonrequest,
      requestHeaders: {Accept: 'application/json'},
      onSuccess: function(transport){
        var tvclips = transport.responseText.evalJSON();
        
        $('alttvclipscomponent').innerHTML = "";
        
        var count = 1;
        var limit = (tvclips.tvclipsdata.length> 4) ? 4 : tvclips.tvclipsdata.length

        for (i = 0; i < limit; i++) {
            var url = "";
            if(tvclips.tvclipsdata[i].type == "CLIP")
                url = "http://watch.bnn.ca/Redirect/?ClipId=" + tvclips.tvclipsdata[i].id ;
            if(tvclips.tvclipsdata[i].type == "VIDEO")
                url = "http://watch.bnn.ca/Redirect/?EpisodeId=" + tvclips.tvclipsdata[i].id ;
                
            if(tvclips.tvclipsdata[i].title != null)
                $('alttvclipscomponent').innerHTML += '<div class="tvClipsAltBox"><a href="' + url + '" target="blank"><img src="' + tvclips.tvclipsdata[i].imgUrl + '" width="140" height="100" alt="" /></a><h5><a href="' + url + '">' + tvclips.tvclipsdata[i].title + '</a></h5><div>' + tvclips.tvclipsdata[i].description + '</div></div>';
            count++;                
        }
      }
    });
}
  
function getLatestClip(bid)
{
    var jsonrequest = "{\"bid\": \""+bid+"\"}";
    
    new Ajax.Request('tvclips/tvclipsrss.aspx', {
      method:'post',
      postBody:jsonrequest,
      requestHeaders: {Accept: 'application/json'},
      onSuccess: function(transport){
        var tvclips = transport.responseText.evalJSON();
        
        $('latestcliplink').innerHTML = "";
        
        if (tvclips.tvclipsdata.length > 0) {
            var url = "";
            if(tvclips.tvclipsdata[0].type == "CLIP")
                url = "http://watch.bnn.ca/Redirect/?ClipId=" + tvclips.tvclipsdata[0].id ;
            if(tvclips.tvclipsdata[0].type == "VIDEO")
                url = "http://watch.bnn.ca/Redirect/?EpisodeId=" + tvclips.tvclipsdata[0].id ;
                
            if(tvclips.tvclipsdata[0].title != null)
                $('latestcliplink').innerHTML += '<a href="' + url + '" class="whiteLinkMed" target="blank">' + tvclips.tvclipsdata[0].title + '</a>';
        }
      }
    });
}
  

function initPoll()
        {
       
            new Ajax.Updater('poll', '/poll/poll.aspx',
            {
                method: 'post',
                parameters: {question: question, answer1_text: answer1_text, answer2_text: answer2_text}                
            });
        }
function submitpoll()
{
    if($('pollAnswer_0').checked == true || $('pollAnswer_1').checked == true)
    {
        new Ajax.Request('/poll/pollsubmit.aspx', {
        method: 'post',
        parameters: {question: question, answer1: $('pollAnswer_0').checked, answer2: $('pollAnswer_1').checked},
          onSuccess: function(transport) {
            showResults();
          }            
        });        
    }
}
function showResults()
{
    new Ajax.Request('/poll/pollresults.aspx', {
        method: 'post',
        parameters: {question: question, answer1_text: answer1_text, answer2_text: answer2_text}, 
      onSuccess: function(transport){
        var pollData = transport.responseText;
        var pollDiv = $('poll');
        pollDiv.innerHTML = pollData;
        $('poll_submit').hide();
        $('poll_view').hide();
      }
    });
}
 
//**** Popular Stories Tracking
function track(title_text, teaser_text) {
    var id = window.getCookie('bnn.tracking');
    var teaser = removeHTMLTags(teaser_text);
    if (id ==null || id == "") {
        id = new UUID();
        window.setCookie('bnn.tracking', id, 365);    
    }
        new Ajax.Request('/tracker/tracker.aspx', {
            method: 'post',
            parameters: {url: location.href, userid: id, title: title_text, teaser: teaser}
        });        
}
function removeHTMLTags(strInputCode){
    /* 
    This line is optional, it replaces escaped brackets with real ones, 
    i.e. < is replaced with < and > is replaced with >
    */    
    strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1){
        return (p1 == "lt")? "<" : ">";
    });

    var strInputCode1 = strInputCode.replace(/&(nbsp|amp);/g, "");
    var strTagStrippedText = strInputCode1.replace(/<\/?[^>]+(>|$)/g, "");
    return strTagStrippedText;    
}

function search()
{
    var filter = "";
    
    if($('cbVideo').checked == true)
        filter += "&video=true";
     
    if($('cbNews').checked == true)
        filter += "&news=true";
    
    if($('searchBnnStock').checked == true)
        window.location = "stock.aspx?pi_symbol=" + $('TextBoxSearch').value;            
    else                    
        window.location = "search.aspx?search=" + $('TextBoxSearch').value + filter;
} 
function footerSearch()
{
    var filter = "";
    
    if($('cbVideo2').checked == true)
        filter += "&video=true";
     
    if($('cbNews2').checked == true)
        filter += "&news=true";
    
    if($('searchBnnStock2').checked == true)
        window.location = "stock.aspx?pi_symbol=" + $('TextBoxSearch2').value;            
    else                    
        window.location = "search.aspx?search=" + $('TextBoxSearch2').value + filter;
}