/*===============================================================================================
Authors: Jamie Maing & Warren Shea
Date: May 2008
Title: BMO Podcast Javascript & RSS Parsing Engine for BMO Financial Group
===============================================================================================*/

// Add to the arrays below when creating new pages and content. Note you have to add sections to the HTML page too for these to appear
// Types of Podcasts
var podcastType = new Array();
podcastType[0] = "homeBuyers";
podcastType[1] = "businessCoach";
podcastType[2] = "retirementYourWay";
podcastType[3] = "businessCoach - Financing and Cash Flow";
podcastType[4] = "businessCoach - Paying Taxes";
podcastType[5] = "businessCoach - Marketing and Sales";
podcastType[6] = "businessCoach - Hot topics and current trends";
podcastType[7] = "businessCoach - Exit a Business andor Retirement";
podcastType[8] = "businessCoach - Human Resources";
podcastType[9] = "businessCoach - Starting a Business";
podcastType[10] = "businessCoach - Technology";
podcastType[11] = "businessCoach - Global Markets";
podcastType[12] = "retirementYourWay - Life Planning";
podcastType[13] = "retirementYourWay - Financial Considerations";
podcastType[14] = "retirementYourWay - Health";
podcastType[15] = "retirementYourWay - Caregiving";
podcastType[16] = "retirementYourWay - Charitable Giving";
//NEW PODCAST SECTIONS REQUIRE YOU TO EDIT:
//LINE 145/146 - # of Podcasts
//LINE 377-416 - Item into the menu

// ShowHide sections (episode list) for each section - should match the DIV id on the default.html page
var podcastTypeSec = new Array();
podcastTypeSec[0] = "box-content-homeBuyers";
podcastTypeSec[1] = "box-content-businessCoach";
podcastTypeSec[2] = "box-content-retirementYourWay";
podcastTypeSec[3] = "box-content-businessCoach - Financing and Cash Flow";
podcastTypeSec[4] = "box-content-businessCoach - Paying Taxes";
podcastTypeSec[5] = "box-content-businessCoach - Marketing and Sales";
podcastTypeSec[6] = "box-content-businessCoach - Hot topics and current trends";
podcastTypeSec[7] = "box-content-businessCoach - Exit a Business andor Retirement";
podcastTypeSec[8] = "box-content-businessCoach - Human Resources";
podcastTypeSec[9] = "box-content-businessCoach - Starting a Business";
podcastTypeSec[10] = "box-content-businessCoach - Technology";
podcastTypeSec[11] = "box-content-businessCoach - Global Markets";
podcastTypeSec[12] = "box-content-retirementYourWay - Life Planning";
podcastTypeSec[13] = "box-content-retirementYourWay - Financial Considerations";
podcastTypeSec[14] = "box-content-retirementYourWay - Health";
podcastTypeSec[15] = "box-content-retirementYourWay - Caregiving";
podcastTypeSec[16] = "box-content-retirementYourWay - Charitable Giving";

// Page titles for each type of Podcast
var pageTitles = new Array();
pageTitles[0] = "A-Z Home Buyers";
pageTitles[1] = "Business Coach";
pageTitles[2] = "Retirement Planning";
pageTitles[3] = "Business Coach";
pageTitles[4] = "Business Coach";
pageTitles[5] = "Business Coach";
pageTitles[6] = "Business Coach";
pageTitles[7] = "Business Coach";
pageTitles[8] = "Business Coach";
pageTitles[9] = "Business Coach";
pageTitles[10] = "Business Coach";
pageTitles[11] = "Business Coach";
pageTitles[12] = "Retirement Planning";
pageTitles[13] = "Retirement Planning";
pageTitles[14] = "Retirement Planning";
pageTitles[15] = "Retirement Planning";
pageTitles[16] = "Retirement Planning";

// iTunes URLs
var iTunesURL = new Array();
iTunesURL[0] = "http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=252323597"; // Home Buyers
iTunesURL[1] = "http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=340241100"; // Business Coach
iTunesURL[2] = "http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=220377713"; // Retirement Your Way
iTunesURL[3] = "http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=340241100"; // Business Coach
iTunesURL[4] = "http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=340241100"; // Business Coach
iTunesURL[5] = "http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=340241100"; // Business Coach
iTunesURL[6] = "http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=340241100"; // Business Coach
iTunesURL[7] = "http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=340241100"; // Business Coach
iTunesURL[8] = "http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=340241100"; // Business Coach
iTunesURL[9] = "http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=340241100"; // Business Coach
iTunesURL[10] = "http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=340241100"; // Business Coach
iTunesURL[11] = "http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=340241100"; // Business Coach
iTunesURL[12] = "http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=220377713"; // Retirement Your Way
iTunesURL[13] = "http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=220377713"; // Retirement Your Way
iTunesURL[14] = "http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=220377713"; // Retirement Your Way
iTunesURL[15] = "http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=220377713"; // Retirement Your Way
iTunesURL[16] = "http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=220377713"; // Retirement Your Way

// HTML Page IDs - string in the URL (used to indicate content that needs to be loaded), should match .html page name
var htmlPages = new Array();
htmlPages[0] = "home";
htmlPages[1] = "whatisapodcast";
htmlPages[2] = "a-zhomebuyers";
htmlPages[3] = "businesscoach";
htmlPages[4] = "retirementplanning";

// HTML Page Navigation Names - use to change titles of the HTML pages in the iframe
var htmlPageNavNames = new Array();
htmlPageNavNames[0] = "BMO Podcasts";
htmlPageNavNames[1] = "Podcast FAQs";
htmlPageNavNames[2] = "A to Z Home Buyers";
htmlPageNavNames[3] = "Business Coach";
htmlPageNavNames[4] = "Retirement Planning";

// Other changeable variables in the default.html - advanced users only
var runningText = "Running Time:";
var temporaryRunningText = "Loading...";
var boxFrameHeight = "315px";
var boxOuterFrameHeight = "auto";
var transcriptBoxHeight = "220px";
var transcriptHeight = "173px";
var searchURL = "http://findit.bmo.com/search?site=bmo_en&client=bmo_en&output=xml_no_dtd&proxystylesheet=bmo_en&filter=0&q=";
var downloadText = "Download audio in MP3 format";
var lowerBoxTitle = "Transcript";

// Header Data in the RSS Feed
var headerData = new Array();
headerData[0] = "title";
headerData[1] = "link";
headerData[2] = "description";
headerData[3] = "copyright";
headerData[4] = "pubDate";
headerData[5] = "lastBuildDate";
headerData[6] = "docs";
headerData[7] = "generator";
headerData[8] = "managingEditor";
headerData[9] = "webMaster";

// Episode Data in the RSS Feed
var episodeData = new Array();
episodeData[0] = "title";
episodeData[1] = "link";
episodeData[2] = "description";
episodeData[3] = "pubDate";
episodeData[4] = "enclosure";
episodeData[5] = "guid";

// Variable for RSS Feed loader
var xmlDocRSS; // for XML Read
var xmlDocGET; //for Get
var xmlDocSAVE; //for Save
var xmlhttpRSS; // for XML Read
var xmlhttpGET; //for Get
var xmlhttpSAVE; //for Save

// Variables used in parseXML() function
var menuItemNum=3;// Number of podcast sections - this is for the arrows to change and point down.
var menuItemNum_Buscoach=9;
var menuItemNum_RYW=5;
var podListLimit=5; // default limit on the items in the left navigation
var podListLimitBusCoach=3; // default limit on the items in the left navigation
var podListLimitRYW=3; // default limit on the items in the left navigation
var myItem;
var myItemURL;
var myItemLink = "";
var k=1;
var j=0;
var getNumEpisodes=0;
var busCoachWrite=1;
var rywWrite=1;
var x;
var limitPodListCounter=0;
var currentEpisode;
var startingPodcastURL;
var startingTranscriptURL;
var nameOfRSS;
var showYearCasts;
var saveMP3URL;
var textfromflash;
var podSection;
var myHTMLCode = "";
var titleText = ""; //episode box header
var summaryText = ""; //episode box summary
var podcastMP3Link = ""; //download box mp3
var episodeLinks = ""; //episode list in menu/naviation
var keepCheckingTime = true; // Variable for time checker
var newquerystring = "";

/*********************************************PAGE LOAD********************************************/
// load these follow functions on page load
function pageLoad() {
  setupMainContent();
  loadRSSFiles();
  setupDirectLinks(); //in file "direct_links.js"
}

// Sets up the object for an HTML PAGE to be loaded - NOT THE TRANSCRIPTS
function setupMainContent(){
  var url = location.href;
  var profile = url.substring(url.indexOf("?")+1,url.indexOf("&"));

  for(i=0;i<htmlPages.length;i++){
    var temp = document.getElementById("box-content-transcript-iframe");
    if (profile == htmlPages[i]){
      document.getElementById("text1").style.display="none";
    }
    else if(nameOfRSS == "whatisapodcast"){
      document.getElementById("box-content-transcript-iframe").src="whatisapodcast.html";
      document.getElementById("titleToChange").innerHTML = htmlPageNavNames[1];
    }
  }
}

function loadRSSFiles(){
  // Check to see what podcast should be opened
  var url = location.href;
  var profile = url.substring(url.indexOf("?")+1,url.indexOf("&"));
  if(profile){
    nameOfRSS = profile;
  }
  for(i=0; i<podcastType.length; i++){
    var tempName = "RSS/"+podcastType[i]+".xml";    
    startXMLDOM(tempName);    
    getNumEps(podcastType[i]);
    parseXML(podcastType[i]);    
  }
}
/*********************************************PAGE LOAD********************************************/


/*********************************************RSS LOAD & PARSING***********************************/
// Get XML http request
function startXMLDOM(xml_file)
{ xmlhttpRSS=null;
  if (window.ActiveXObject) { // code for IE6, IE5
    xmlhttpRSS=new ActiveXObject("Microsoft.XMLHTTP");
    xmlhttpRSS.open("GET",xml_file,false);
    xmlhttpRSS.onreadystatechange=state_Change;
    xmlhttpRSS.send(null);
  }
  else if (BrowserDetect.browser == "Firefox") {    
    xmlDocRSS=document.implementation.createDocument("","",null);
    xmlDocRSS.async=false;
    xmlDocRSS.load(xml_file);
  }
  else {
    xmlhttpRSS=new XMLHttpRequest();
    xmlhttpRSS.onreadystatechange=state_Change;
    xmlhttpRSS.open("GET",xml_file,false);    
    xmlhttpRSS.send(null);
  }
}

// Once XML is loaded, update action value for form
function state_Change()
{ if (xmlhttpRSS.readyState==4) {// 4 = "loaded"
    if (xmlhttpRSS.status==200) {// 200 = "OK"
      xmlDocRSS = xmlhttpRSS.responseXML;
    } else {//alert("Problem retrieving XML data:" + xmlhttp.statusText);
    }
  }
}

// Parses the XML and counts the number of episodes in the XML
function getNumEps(nameOfRSS){
  // Prints the header from the RSS file
  j=0;
  try{
    while(xmlDocRSS.getElementsByTagName(episodeData[0])[j].childNodes[0].nodeValue){
      j++;
    }
  }
  catch(e){
  }
  getNumEpisodes=j;
}

// Parses the XML and spits it out into the proper DIVs on the HTML page
function parseXML(nameOfRSS){
  // Prints the header from the RSS file
  try{
    while(xmlDocRSS.getElementsByTagName(episodeData[0])[k].childNodes[0].nodeValue){
      for(x in episodeData){
        myHTMLCode += "<p><i><b>"+ episodeData[x] + ":</b></i><br />"; 
        if (nameOfRSS == "businessCoach" && busCoachWrite==1) {
          busCoachWrite=0;
          episodeLinks += "<div id=\"busCoachSorting\">Sort by: <a href=\"javascript:showHide('recent','show');showHide('themes','hide');boldNoBold('recentdecoration','bold');boldNoBold('themesdecoration','nobold');\"><span id=\"recentdecoration\" style=\"font-weight: bold;\">most recent</span></a> or <a href=\"javascript:showHide('themes','show');showHide('recent','hide');boldNoBold('recentdecoration','nobold');boldNoBold('themesdecoration','bold');\"><span id=\"themesdecoration\">topics</span></a></div><div id=\"recent\" style=\"display: block;\">"
        }    
        if (nameOfRSS == "retirementYourWay" && rywWrite==1) {
          rywWrite=0;
          episodeLinks += "<div id=\"rywSorting\">Sort by: <a href=\"javascript:showHide('recent2','show');showHide('themes2','hide');boldNoBold('recentdecoration2','bold');boldNoBold('themesdecoration2','nobold');\"><span id=\"recentdecoration2\" style=\"font-weight: bold;\">most recent</span></a> or <a href=\"javascript:showHide('themes2','show');showHide('recent2','hide');boldNoBold('recentdecoration2','nobold');boldNoBold('themesdecoration2','bold');\"><span id=\"themesdecoration2\">topics</span></a></div><div id=\"recent2\" style=\"display: block;\">"
        }    
        // Enclosure tag in the RSS
        if (episodeData[x] == "enclosure") {
        }
        // GUID tag in the RSS
        else if(episodeData[x] == "guid") {
          myItem = xmlDocRSS.getElementsByTagName(episodeData[x])[k-1].childNodes[0].nodeValue;
          //myHTMLCode += "<a href=\"javascript:javascript_to_flash('" + myItem + "');\">"+myItem+"</a>";
          if (k == "1") {
            podcastMP3Link += "<a href='" + myItem + "'>Podcast audio in MP3 format</a>";
          }
        }
        // All other tags in the RSS
        else {
          myItem = xmlDocRSS.getElementsByTagName(episodeData[x])[k].childNodes[0].nodeValue;
          myItemLink = xmlDocRSS.getElementsByTagName(episodeData[1])[k].childNodes[0].nodeValue;
          if (episodeData[x] == "title") {
            myItemURL = xmlDocRSS.getElementsByTagName(episodeData[5])[k-1].childNodes[0].nodeValue;
          }
          myHTMLCode += myItem;
          if (k == "1") {
            startingPodcastURL = myItemURL;
            startingTranscriptURL = "transcripts - " + nameOfRSS + "/" + nameOfRSS + "-" + (xmlDocRSS.getElementsByTagName(episodeData[0]).length-k) + ".htm";
            if (episodeData[x] == "title") {
              titleText += myItem;
            }
            if (episodeData[x] == "description") {
              summaryText += myItem;
            }
          }
          if (episodeData[x] == "title") {
            if (nameOfRSS.substring(0,16) == "businessCoach - ") {
              if(limitPodListCounter<podListLimitBusCoach){
                episodeLinks += "<div class='episodeLinks'><a id='" + myItemURL + "' href='javascript:;' onclick=\"javascript_to_flash('" + myItemURL + "','" + (getNumEpisodes-k) +"', '"+ nameOfRSS + "', '0');\"'>"+myItem+"</a></div>";
                if((limitPodListCounter==(podListLimitBusCoach-1))){
                  episodeLinks += "<div class='episodeLinksHidden' id='"+ nameOfRSS +"Hidden'>";
                }
                limitPodListCounter++;
              }
              else{
                episodeLinks += "<div class='episodeLinks'><a id='" + myItemURL + "' href='javascript:;' onclick=\"javascript_to_flash('" + myItemURL + "','" + (getNumEpisodes-k) +"', '"+ nameOfRSS + "', '0');\"'>"+myItem+"</a></div>";
              }        
            } else if (nameOfRSS.substring(0,20) == "retirementYourWay - ") {
              if(limitPodListCounter<podListLimitRYW){
                episodeLinks += "<div class='episodeLinks'><a id='" + myItemURL + "' href='javascript:;' onclick=\"javascript_to_flash('" + myItemURL + "','" + (getNumEpisodes-k) +"', '"+ nameOfRSS + "', '0');\"'>"+myItem+"</a></div>";
                if((limitPodListCounter==(podListLimitRYW-1))){
                  episodeLinks += "<div class='episodeLinksHidden' id='"+ nameOfRSS +"Hidden'>";
                }
                limitPodListCounter++;
              }
              else{
                episodeLinks += "<div class='episodeLinks'><a id='" + myItemURL + "' href='javascript:;' onclick=\"javascript_to_flash('" + myItemURL + "','" + (getNumEpisodes-k) +"', '"+ nameOfRSS + "', '0');\"'>"+myItem+"</a></div>";
              }        
            } else {
              if(limitPodListCounter<podListLimit){
                episodeLinks += "<div class='episodeLinks'><a id='" + myItemURL + "' href='javascript:;' onclick=\"javascript_to_flash('" + myItemURL + "','" + (getNumEpisodes-k) +"', '"+ nameOfRSS + "', '0');\"'>"+myItem+"</a></div>";
                if((limitPodListCounter==(podListLimit-1))){
                  episodeLinks += "<div class='episodeLinksHidden' id='"+ nameOfRSS +"Hidden'>";
                }
                limitPodListCounter++;
              }
              else{
                episodeLinks += "<div class='episodeLinks'><a id='" + myItemURL + "' href='javascript:;' onclick=\"javascript_to_flash('" + myItemURL + "','" + (getNumEpisodes-k) +"', '"+ nameOfRSS + "', '0');\"'>"+myItem+"</a></div>";
              }
            }
          }
        }
      }
      x=0;
      k++;
    }
  }
  catch(e){
  currentEpisode=k-1;
  var temppodListLimit;
  if (nameOfRSS.substring(0,16) == "businessCoach - ")
	temppodListLimit = podListLimitBusCoach;
  else if (nameOfRSS.substring(0,20) == "retirementYourWay - ")
	temppodListLimit = podListLimitRYW;
  else
    temppodListLimit = podListLimit;
	
  if(currentEpisode <=temppodListLimit){ // If it is less than 5 episodes...
    // Write only the episodes  
    document.getElementById("box-content-"+nameOfRSS).innerHTML = episodeLinks;
  }
  // If more than 5 episodes...
  else{
    // Write the "More" and "Archive" links in the left navigation
    if(showYearCasts == "thisYear"){
    // Enable below code for Phase 2
    }else{
      // To show all of a year example: default.html?retirementYourWay&thisYear$
      episodeLinks += "</div>"; //closes off recent   
      episodeLinks += "<div id='"+nameOfRSS+"moreDiv' class='moreDiv'><a id='moreLink' href='javascript:showHide(\""+nameOfRSS+"moreDiv\",\"hide\");showHide(\""+ nameOfRSS +"Hidden\");'>More</a></div>";
      episodeLinks += "</div>"; //closes off recent   
      if (nameOfRSS == "businessCoach") {
        episodeLinks += "      <div id=\"themes\" style=\"display:none;\">";
        episodeLinks += "        <div id=\"Accordion2\" class=\"Accordion2\" style=\"display:block;\" onmousemove=\"this.blur();\">"
        episodeLinks += "          <div class=\"AccordionPanelTab2\" onmouseup=\"javascript:updateRSSButton('homeBuyers');arrowDown('1','busCoach');\"><img id=\"list_busCoach1\" src=\"images/listArrow2.gif\" alt=\"arrow\" /> Financing & Cash Flow</div>"
        episodeLinks += "          <div class=\"AccordionPanelContent2\" id=\"box-content-businessCoach - Financing and Cash Flow\">Loading...</div>"
        episodeLinks += "          <div class=\"AccordionPanelTab2\" onmouseup=\"javascript:updateRSSButton('homeBuyers');arrowDown('2','busCoach');\"><img id=\"list_busCoach2\" src=\"images/listArrow2.gif\" alt=\"arrow\" /> Paying Taxes</div>"
        episodeLinks += "          <div class=\"AccordionPanelContent2\" id=\"box-content-businessCoach - Paying Taxes\">Loading...</div>"
        episodeLinks += "          <div class=\"AccordionPanelTab2\" onmouseup=\"javascript:updateRSSButton('homeBuyers');arrowDown('3','busCoach');\"><img id=\"list_busCoach3\" src=\"images/listArrow2.gif\" alt=\"arrow\" /> Marketing & Sales</div>"
        episodeLinks += "          <div class=\"AccordionPanelContent2\" id=\"box-content-businessCoach - Marketing and Sales\">Loading...</div>"
        episodeLinks += "          <div class=\"AccordionPanelTab2\" onmouseup=\"javascript:updateRSSButton('homeBuyers');arrowDown('4','busCoach');\"><img id=\"list_busCoach4\" src=\"images/listArrow2.gif\" alt=\"arrow\" /> Hot topics & current trends</div>"
        episodeLinks += "          <div class=\"AccordionPanelContent2\" id=\"box-content-businessCoach - Hot topics and current trends\">Loading...</div>"
        episodeLinks += "          <div class=\"AccordionPanelTab2\" style=\"height:30px;\" onmouseup=\"javascript:updateRSSButton('homeBuyers');arrowDown('5','busCoach');\"><img id=\"list_busCoach5\" src=\"images/listArrow2.gif\" alt=\"arrow\" /> Exit a Business &/or<br />&nbsp;&nbsp;&nbsp;Retirement</div>"
        episodeLinks += "          <div class=\"AccordionPanelContent2\" id=\"box-content-businessCoach - Exit a Business andor Retirement\">Loading...</div>"
        episodeLinks += "          <div class=\"AccordionPanelTab2\" onmouseup=\"javascript:updateRSSButton('homeBuyers');arrowDown('6','busCoach');\"><img id=\"list_busCoach6\" src=\"images/listArrow2.gif\" alt=\"arrow\" /> Human Resources</div>"
        episodeLinks += "          <div class=\"AccordionPanelContent2\" id=\"box-content-businessCoach - Human Resources\">Loading...</div>"
        episodeLinks += "          <div class=\"AccordionPanelTab2\" onmouseup=\"javascript:updateRSSButton('homeBuyers');arrowDown('7','busCoach');\"><img id=\"list_busCoach7\" src=\"images/listArrow2.gif\" alt=\"arrow\" /> Starting a Business</div>"
        episodeLinks += "          <div class=\"AccordionPanelContent2\" id=\"box-content-businessCoach - Starting a Business\">Loading...</div>"
        episodeLinks += "          <div class=\"AccordionPanelTab2\" onmouseup=\"javascript:updateRSSButton('homeBuyers');arrowDown('8','busCoach');\"><img id=\"list_busCoach8\" src=\"images/listArrow2.gif\" alt=\"arrow\" /> Technology</div>"
        episodeLinks += "          <div class=\"AccordionPanelContent2\" id=\"box-content-businessCoach - Technology\">Loading...</div>"
        episodeLinks += "          <div class=\"AccordionPanelTab2\" onmouseup=\"javascript:updateRSSButton('homeBuyers');arrowDown('9','busCoach');\"><img id=\"list_busCoach9\" src=\"images/listArrow2.gif\" alt=\"arrow\" /> Global Markets</div>"
        episodeLinks += "          <div class=\"AccordionPanelContent2\" id=\"box-content-businessCoach - Global Markets\">Loading...</div>"
        episodeLinks += "        </div>"
        episodeLinks += "      </div>"
      }
      if (nameOfRSS == "retirementYourWay") {
        episodeLinks += "      <div id=\"themes2\" style=\"display:none;\">";
        episodeLinks += "        <div id=\"Accordion3\" class=\"Accordion2\" style=\"display:block;\" onmousemove=\"this.blur();\">"
        episodeLinks += "          <div class=\"AccordionPanelTab2\" onmouseup=\"javascript:updateRSSButton('retirementYourWay');arrowDown('1','ryw');\"><img id=\"list_ryw1\" src=\"images/listArrow2.gif\" alt=\"arrow\" /> Life Planning</div>"
        episodeLinks += "          <div class=\"AccordionPanelContent2\" id=\"box-content-retirementYourWay - Life Planning\">Loading...</div>"
        episodeLinks += "          <div class=\"AccordionPanelTab2\" onmouseup=\"javascript:updateRSSButton('retirementYourWay');arrowDown('2','ryw');\"><img id=\"list_ryw2\" src=\"images/listArrow2.gif\" alt=\"arrow\" /> Financial Considerations</div>"
        episodeLinks += "          <div class=\"AccordionPanelContent2\" id=\"box-content-retirementYourWay - Financial Considerations\">Loading...</div>"
        episodeLinks += "          <div class=\"AccordionPanelTab2\" onmouseup=\"javascript:updateRSSButton('retirementYourWay');arrowDown('3','ryw');\"><img id=\"list_ryw3\" src=\"images/listArrow2.gif\" alt=\"arrow\" /> Health</div>"
        episodeLinks += "          <div class=\"AccordionPanelContent2\" id=\"box-content-retirementYourWay - Health\">Loading...</div>"
        episodeLinks += "          <div class=\"AccordionPanelTab2\" onmouseup=\"javascript:updateRSSButton('retirementYourWay');arrowDown('4','ryw');\"><img id=\"list_ryw4\" src=\"images/listArrow2.gif\" alt=\"arrow\" /> Caregiving</div>"
        episodeLinks += "          <div class=\"AccordionPanelContent2\" id=\"box-content-retirementYourWay - Caregiving\">Loading...</div>"
        episodeLinks += "          <div class=\"AccordionPanelTab2\" onmouseup=\"javascript:updateRSSButton('retirementYourWay');arrowDown('5','ryw');\"><img id=\"list_ryw5\" src=\"images/listArrow2.gif\" alt=\"arrow\" /> Charitable Giving</div>"
        episodeLinks += "          <div class=\"AccordionPanelContent2\" id=\"box-content-retirementYourWay - Charitable Giving\">Loading...</div>"
        episodeLinks += "        </div>"
        episodeLinks += "      </div>"
      }
    }
    document.getElementById("box-content-"+nameOfRSS).innerHTML = episodeLinks;
  }
  episodeLinks = "";
  limitPodListCounter=0;
  k=1;
  currentEpisode=k-1;
  }
}
/*********************************************RSS LOAD & PARSING***********************************/

// Take returned variable to put into "Running Time"
function calculateTime(textfromflash, loadingText){
  podcastMin = Math.floor(textfromflash/60);
  podcastSec = Math.floor(((textfromflash/60) - podcastMin)*60);
  document.getElementById("box-right-ep-info-running-value").innerHTML = "<span id='box-right-ep-info-running'>"+ runningText +"</span> "+ podcastMin +" min " + podcastSec + " sec ";
}

// Change the styling on the box to fit larger pages that are NOT transcripts
function changePage(myPage){
  for(s=0;s<htmlPages.length;s++){
    if(htmlPages[s]==myPage){
      document.getElementById('box-content-transcript-iframe').src = myPage+".html";
      document.getElementById("text1").style.display="none";
      document.getElementById("box-content-transcript-iframe").style.height = boxFrameHeight;
      document.getElementById("text2").style.height = boxOuterFrameHeight;
      document.getElementById("titleToChange").innerHTML = htmlPageNavNames[s];
      document.getElementById("main-title").innerHTML = htmlPageNavNames[s];
      document.getElementById("title").innerHTML = "";
    }
  }
}

// Sends URL to the flash player - Part 1
function javascript_to_flash(texttoflash, episodeNum, nameOfRSS, autoplay) {
  // Make the Episode Summary Appear
  document.getElementById("text1").style.display="block";
  // Change size of the transcript area
  document.getElementById("box-content-transcript-iframe").style.height = transcriptHeight;
  //document.getElementById("text2").style.display = "none"; // 220px
  document.getElementById("text2").style.height = transcriptBoxHeight; // 220px
  // Make the episode title appear
  document.getElementById("title").style.display="block";
  // Change title on the center area
  for(r=0;r<podcastType.length;r++){
    if(podcastType[r]==nameOfRSS){
      document.getElementById("main-title").innerHTML = pageTitles[r];
    }
  }
  // Load appropriate podcast text into boxes
  var tempHTML = "";
  startXMLDOM("RSS/"+nameOfRSS+".xml");
  getNumEps();
  try{
    for(i=0; i<episodeData.length;i++){
      if (episodeData[i] == "title") { //change title
        tempHTML = xmlDocRSS.getElementsByTagName(episodeData[i])[(getNumEpisodes-episodeNum)].childNodes[0].nodeValue;
        document.getElementById("title").innerHTML = tempHTML;
      }
      else if (episodeData[i] == "link") { //change transcript
        if (nameOfRSS.substring(0,16) == "businessCoach - ") {
          startingTranscriptURL = "transcripts - businessCoach/" + xmlDocRSS.getElementsByTagName(episodeData[i])[(getNumEpisodes-episodeNum)].childNodes[0].nodeValue;    
          document.getElementById('box-content-transcript-iframe').src = startingTranscriptURL;
        } else if (nameOfRSS.substring(0,20) == "retirementYourWay - ") {
          startingTranscriptURL = "transcripts - retirementYourWay/" + xmlDocRSS.getElementsByTagName(episodeData[i])[(getNumEpisodes-episodeNum)].childNodes[0].nodeValue;
          document.getElementById('box-content-transcript-iframe').src = startingTranscriptURL;
        } else {   
          startingTranscriptURL = "transcripts - " + nameOfRSS + "/" + xmlDocRSS.getElementsByTagName(episodeData[i])[(getNumEpisodes-episodeNum)].childNodes[0].nodeValue;
          document.getElementById('box-content-transcript-iframe').src = startingTranscriptURL;;
        }
      }
      else if (episodeData[i] == "description") { //episode summary
        tempHTML = xmlDocRSS.getElementsByTagName(episodeData[i])[(getNumEpisodes-episodeNum)].childNodes[0].nodeValue;
        document.getElementById("box-right-ep-info-content").innerHTML = tempHTML;
      }
      else if (episodeData[i] == "guid") { //download link
        tempHTML = xmlDocRSS.getElementsByTagName(episodeData[i])[(getNumEpisodes-episodeNum)-1].childNodes[0].nodeValue;
        document.getElementById("box-right-download-mp3").innerHTML = "<a id='box-right-download-link' href='" + tempHTML + "');>"+downloadText+"</a>";
      }
      else if (episodeData[i] == "enclosure") {
        //do nothing - don't need the data from this tag to be loaded at the moment
      }
    }
  }
  catch(err){
  }

  // Make "Loading" text appear during download
  document.getElementById("box-right-ep-info-running-value").innerHTML = temporaryRunningText;
  document.getElementById("titleToChange").innerHTML = lowerBoxTitle;
  // Load the proper podcast into the flash player
  setTimeout("thisMovie('extinterfaceexample').asFunc('"+texttoflash+"','"+autoplay+"')",0);
  // Update Ratings  
  getRatings(texttoflash, "E");    
}

// Make transcript title appear
function showTranscriptTitle(){
  document.getElementById("box-content-transcript").style.display = "block";
}

// Sends URL to the flash player - Part 2
function thisMovie(movieName) {
  var isIE = navigator.appName.indexOf("Microsoft") != -1;
  return (isIE) ? window[movieName] : document[movieName];
}

function updateRSSButton(myRSS){
  for(w=0;w<podcastType.length;w++){
    if(podcastType[w]==myRSS){
      document.getElementById('RSSFooterLink').href = "RSS/"+myRSS+".xml";
      document.getElementById('iTunesLink').disabled = false;
      document.getElementById('iTunesLink').style.display = "block";
      document.getElementById('iTunesLink').href = iTunesURL[w];
    }
  }
  newquerystring = myRSS;
}

function showLangURL(){
  var currentQueryString;
  var currentLocation = location.href;
  if (currentLocation.indexOf("?") > 0)  //if no querystring
     currentQueryString = currentLocation.substring(currentLocation.indexOf("?")+1,currentLocation.length);	
  var urlswitch = currentLocation.replace("en","fr");
  if (currentLocation.indexOf("?") > 0) //if no querystring
      currentLocationWithoutQuerystring = urlswitch.substring(0, currentLocation.indexOf("?"));
  else
      currentLocationWithoutQuerystring = urlswitch
  var newLocation;
  if (currentQueryString == undefined && newquerystring == "")
	  newLocation = urlswitch;
  else
	  newLocation = currentLocationWithoutQuerystring + "?" + newquerystring;
  location.replace(newLocation);
}

// Custom popup for the footer links
function customPopup(url, features) {
  window.open(url, '', features);
}

// Changes arrows to point down in the left menu
var last_click_type = "";
var last_click_num;
function arrowDown(num,menuType){
  var menuNumber; 
  if(last_click_type != ""){
	
	  if(last_click_type == menuType && last_click_num == num){
		  
		  if(document.getElementById("list_"+menuType+num).src.indexOf("images/listArrow2d.gif") != -1){
			  document.getElementById("list_"+menuType+num).src = "images/listArrow2.gif";
		  }else{
			  document.getElementById("list_"+menuType+num).src = "images/listArrow2d.gif";
		  }
		  return true;
	  }
  }
  last_click_type = menuType;
  if (menuType == "main") {
	last_click_num = num;
    menuNumber = menuItemNum;
  }
  else if (menuType == "busCoach") {
    menuNumber = menuItemNum_Buscoach;
	last_click_num = num;
  }
  else if (menuType == "ryw") {
    menuNumber = menuItemNum_RYW;
	last_click_num = num;
  }
  for(u=1; u<=menuNumber;u++){
    document.getElementById("list_"+menuType+u).alt = "arrow";
    document.getElementById("list_"+menuType+u).src = "images/listArrow2.gif";
  }
  document.getElementById("list_"+menuType+num).src = "images/listArrow2d.gif";
  document.getElementById("list_"+menuType+num).alt = "arrow";
}

// Show and hides the left panel sections
function showHide(div,command){
  if (command == 'show'){
    document.getElementById(div).style.display = 'block';
  }
  else if (command == 'hide'){
    document.getElementById(div).style.display = 'none';
  }
  else{
    if(document.getElementById(div).style.display == 'block'){
      document.getElementById(div).style.display = 'none';
    }
    else{
      document.getElementById(div).style.display = 'block';
    }
  }
}

// Show and hides the left panel sections
function boldNoBold(span,command){
  if (command == 'bold'){
    document.getElementById(span).style.fontWeight = 'bold';
  }
  else {
    document.getElementById(span).style.fontWeight = 'normal';
  }
}

// When the search button is clicked, send the user to the findit.bmo.com page
function gotoGoogleSearch(){
  searchText = document.getElementById("searchInput").value;
  location.href=searchURL+searchText;
}

/*********************************************RATINGS***********************************/
function saveRatings(filename, lang, rating) {
  var url = "http://www.bmo.com/rating/podcast/saveRatings.jsp?filename=" + filename + "&lang=" + lang + "&rating=" + rating;
  var filename_cookie=getCookie(filename);
  if (filename_cookie !=null && filename_cookie !="") {
    document.getElementById("calltoaction").innerHTML = "You have already rated this podcast";
  }
  else {
    xmlhttpSAVE=null;
    if (window.XMLHttpRequest) {    // code for IE7, Firefox, Opera, etc.
      xmlhttpSAVE=new XMLHttpRequest();
    } else if (window.ActiveXObject) {    // code for IE6, IE5
      xmlhttpSAVE=new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlhttpSAVE!=null) {
      xmlhttpSAVE.onreadystatechange=getJSONratingsSave;
      xmlhttpSAVE.open("GET",url,true);
      xmlhttpSAVE.send(null);
    } else {
      //alert("Your browser does not support XMLHTTP.");
    }
	setCookie(filename,"E",365);

    var ratings_html = "";
    for ( i=0; i < 5; i++) {
      if ((i+0.5) <= rating && rating < (i+1)) //half
        ratings_html += "<img src=\"images/star_half.gif\" border=\"0\" id=\"star_" + (i+1) + "_id\">"
      else if (rating <= (i+0.5)) //empty
        ratings_html += "<img src=\"images/star_empty.gif\" border=\"0\" id=\"star_" + (i+1) + "_id\">"
      else //full
        ratings_html += "<img src=\"images/star_full.gif\" border=\"0\" id=\"star_" + (i+1) + "_id\">"
    } 
    document.getElementById("rating_stars").innerHTML = ratings_html;
    document.getElementById("calltoaction").innerHTML = "You have rated this podcast!";  
  } 
}

function getJSONratingsSave() {
  if (xmlhttpSAVE.readyState == 4) {
    if (xmlhttpSAVE.status==200) {// 200 = "OK"
      xmlDocSAVE = xmlhttpSAVE.responseText; 
      updatePageSave(xmlDocSAVE);
    } else {  //alert("Problem retrieving XML data:" + xmlhttp.statusText);
    }
  }
}

function updatePageSave(response){  
  var mp3_info = JSON.parse(response);   
  document.getElementById("overall-rating").innerHTML = mp3_info.aggregate;
}

var global_filename;
function getRatings(filename, lang) {
  showHide('rating','show');
  var newfilename = remove(filename, "media/homeBuyers/");
  newfilename = remove(newfilename, "media/businessCoach/");
  newfilename = remove(newfilename, "media/retirementYourWay/"); //removing directories
  global_filename = newfilename; //setting globalfilename for updatePage
  var url = "http://www.bmo.com/rating/podcast/getRatings.jsp?filename=" + newfilename + "&lang=" + lang;  
  
  xmlhttpGET=null;
  if (window.XMLHttpRequest) {    // code for IE7, Firefox, Opera, etc.
    xmlhttpGET=new XMLHttpRequest();
  } else if (window.ActiveXObject) {    // code for IE6, IE5
    xmlhttpGET=new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (xmlhttpGET!=null) {
    xmlhttpGET.onreadystatechange=getJSONratings;
    xmlhttpGET.open("GET",url,true);
    xmlhttpGET.send(null);
  } else {
    //alert("Your browser does not support XMLHTTP.");
  }
}

function getJSONratings() {
  if (xmlhttpGET.readyState == 4) {
    if (xmlhttpGET.status==200) {// 200 = "OK"
      xmlDocGET = xmlhttpGET.responseText; 
      updatePage(xmlDocGET);
      document.getElementById("calltoaction").innerHTML = "Rate this Podcast";
    } else {  //alert("Problem retrieving XML data:" + xmlhttp.statusText);
    }
  }
}

function updatePage(response){  
  var filename = global_filename;
  var mp3_info = JSON.parse(response);
    
  var ratings_html = "<table width=\"100%\"><tr><td width=\"25%\"><div id=\"calltoaction\" style=\"font-size: 11px;\">&nbsp;</div></td><td width=\"50%\" style=\"text-align: center;\"><div id=\"rating_stars\">";
  for ( i=0; i < 5; i++) {
    ratings_html += "<a href=\"javascript:saveRatings('" + filename + "', 'E', '" + (i+1) + "');\"><img src=\"images/star_empty.gif\" border=\"0\" id=\"star_" + (i+1) + "_id\" onmouseover=\"javascript:showStar(" + (i+1) + ");\" onmouseout=\"javascript:restoreStar();\"></a>"
  } 
  ratings_html += "</div></td><td width=\"25%\" style=\"text-align: right;vertical-align: middle;\"> <span style=\"font-size: 11px; text-align: right;\">Overall Rating<br /><div id=\"overall-rating\" style=\"display: inline;\">" + mp3_info.aggregate + "</div>&nbsp;stars</span></td></tr></table>"
  if (mp3_info.errorcode == "ERR100") { //If there's an error pulling the mp3 information, don't show stars, show error message
    ratings_html = "Data Retrieval Error";
  }
  document.getElementById("rating").innerHTML = ratings_html;
}

function showStar(num_stars) {
  var id_key;
  for (k=0; k < num_stars; k++) {
    id_key = 'star_' + (k+1) +  '_id';
    document.getElementById(id_key).src = "images/star_full.gif";
  }
  for ( j=num_stars; j < 5; j++) {
    id_key = 'star_' + (j+1) +  '_id';
    document.getElementById(id_key).src = "images/star_empty.gif";
  }
}

function restoreStar() {
  var id_key;
  for ( i=0; i < 5; i++) {
    id_key = 'star_' + (i+1) +  '_id';
    document.getElementById(id_key).src = "images/star_empty.gif";
  }
}

function remove(s, t) {
  /*  remove t from s*/
  i = s.indexOf(t);
  r = "";
  if (i == -1) return s;
  r += s.substring(0,i) + remove(s.substring(i + t.length), t);
  return r;
}


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.toUTCString());
}

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 "";
}
