/*var q = new Querystring();
var bcpidValue = q.get("bcpid");
var bctidValue = q.get("bctid");

function check_bcpid()//This is to fix legacy links. Swaps out player ID for the correct one
{
if (bcpidValue == "1869637852")
{
var currentUrl = location.href;
var newUrl = currentUrl.replace(/1869637852/gi,"13960334001");
location.replace(newUrl);
}
}
*/
function check_bctid(){//this checks to see if there is a specific video to play. If not, it will load the latest
//if (bctidValue == undefined){
	//alert("running bctid");
		BCgetPlaylistByID(22352577001,1,0,'startupResponse','Niche');//this loads the latest video into the player
//}else{
	//alert("there is a number");
//}
}

//check_bcpid();


onPage = 0;
startingVideo = "";
accountName = 'MJS';
playingModule = null;
topLoaded = 0;
caller="";
topPageNum = 0;
var output_json_data;
var tokenString = '';
searchResults = false;
 var playerNiche;
    var adModuleNiche;


var nicheString = '_nzgyIxn8zuYeTOJzOJFOZGqncI8uzoIRwPG48TRwM8.';


/* The publishing code is placed in your HTML file.  The player will automatically call onTemplateLoaded if the API is enabled
               in the Brightcove Studio Publishing module */
              
function onTemplateLoaded(pExperienceID) {	
playerNiche = brightcove.getExperience(pExperienceID);
		check_bctid();//checks to see if a specific video should play	
		
		//getCombinedTopVideos();
		BCgetPlaylistByID(22352577001,12,0,'playlistResponse','Niche');
	  	    // Get a reference to the Ad Module API
			    adModuleNiche = playerNiche.getModule(APIModules.ADVERTISING);
			    //Enabled External Ads
			    adModuleNiche.enableExternalAds(true);
			        
			    // Add a callback function for the external Ads event
			    adModuleNiche.addEventListener(BCAdvertisingEvent.EXTERNAL_AD, onExternalAd);
			    adModuleNiche.addEventListener(BCAdvertisingEvent.AD_COMPLETE, onAdComplete);  
				
}





function loading(){
	document.getElementById('resp').innerHTML = '<div id="loadtime"><img src="sbloader.gif" width="32" height="32" /></div>';
}

function addScriptTag(id, url, callback){
//check to see if script tag exists - if it does, remove it before writing new tag
if(document.getElementById(id)){
var child = document.getElementById(id);
var parent = child.parentNode; 
parent.removeChild(child);
}
	var scriptTag = document.createElement("script");
	scriptTag.setAttribute("type", "text/javascript");
	scriptTag.setAttribute("charset", "utf-8");
	scriptTag.setAttribute("src", url + "&callback=" + callback);
	scriptTag.setAttribute("id", id);
	var head = document.getElementsByTagName("head").item(0);
	head.appendChild(scriptTag);

}

function BCgetToken(account){
	switch (account) {
case 'TMJ': tokenString = tmjString; break;
case 'Niche': tokenString = nicheString; break;
default: tokenString = mjsString;
}
accountName = account;
return tokenString;
}

function BCgetTopVideos(pSize,pNumber,callback,account) {//this gets the top videos
BCgetToken(account);
 onPage = pNumber;
	onSize = pSize;
	onCallback = callback;
	onAccount = account;
	BCmethod = "topvideos";
	var searchString = 'http://api.brightcove.com/services/library?command=find_all_videos&page_size='+pSize+'&page_number='+pNumber+'&token='+tokenString+'&fields=id,name,thumbnailURL,playsTrailingWeek,tags,publishedDate&sort_by=plays_trailing_week&get_item_count=true';
	addScriptTag("topVideos"+account,searchString, callback);
}

function BCgetRelatedVideos(titleID,pSize,pNumber,callback,account) {
BCgetToken(account);
//loading(callback);
var searchString = 'http://api.brightcove.com/services/library?command=find_related_videos&sort_by=PUBLISH_DATE&sort_order=DESC&video_id='+titleID+'&page_size='+pSize+'&page_number='+pNumber+'&token='+tokenString+'';
	addScriptTag("relatedVideos",searchString, callback);
	
}

function BCgetPlaylistByID(playlistID,pSize,pNumber,callback,account) {//this returns videos based on the Brightcove playlist ID
BCgetToken(account);
    onPage = pNumber;
	onString = playlistID;
	onSize = pSize;
	onCallback = callback;
	onAccount = account;
	BCmethod = "playlist";
 var searchString = 'http://api.brightcove.com/services/library?command=find_playlist_by_id&playlist_id='+playlistID+'&video_fields=id,name,publishedDate,thumbnailURL,lastModifiedDate,tags&get_item_count=true&token='+tokenString+'';
	addScriptTag("playlistByID"+callback,searchString,callback); 
	//alert(onString);
}

function BCgetVideosByText(textString,pSize,pNumber,callback,account) {
	//loading(callback);
	BCgetToken(account);
var searchString = 'http://api.brightcove.com/services/library?command=find_videos_by_text&text='+textString+'&page_size='+pSize+'&page_number='+pNumber+'&fields=id,name,thumbnailURL,playsTrailingWeek,tags,publishedDate&get_item_count=true&token='+tokenString+'';
	addScriptTag("VideosByText",searchString,callback);
}

function BCgetVideosByTags(tagString,pSize,pNumber,callback,account) {
	loading('resp');
	BCgetToken(account);	 
	onPage = pNumber;
	onString = tagString;
	onSize = pSize;
	onCallback = callback;
	onAccount = account;
	BCmethod = "video";
var searchString = 'http://api.brightcove.com/services/library?command=find_videos_by_tags&or_tags='+tagString+'&page_size='+pSize+'&page_number='+pNumber+'&sort_by=MODIFIED_DATE&sort_order=DESC&get_item_count=true&token='+tokenString+'';
	addScriptTag("VideosByTag",searchString,callback);
	
}

function checkCredit(info,account){
for (var i=0; i<info.length; i++) {	
if(info[i] =='SportsBubbler'){return true;}
	} 	
}



function findCredit(info,account){
for (var i=0; i<info.length; i++) {	
switch(info[i]){
		case 'MJS': return("JSOnline"); break;
		case 'TMJ': return('TODAY&acute;S TMJ4'); break;
		case 'Wisconsin Trails': return("Wisconsin Trails"); break;	
		case 'SportsBubbler': return("SportsBubbler"); break;
		case 'SB': return("SportsBubbler"); break;
		case 'CNI': return("MyCommunityNOW"); break;
		case 'Lake Country': return("Lake Country"); break;
		case 'Milwaukee Home': return("Milwaukee Home"); break;
		case 'KMIR': return("KMIR-TV in Palm Springs"); break;
		case 'WGBA': return("WGBA-TV in Green Bay"); break;
	} 	
}//If no tags match above, then these will be used as default. 
if (account == 'MJS'){
return("JSOnline");
}else{
	if (account == 'TMJ'){
		return("TODAY&acute;S TMJ4");
}else{
		if (account == 'Niche'){
		return("Journal Interactive");
} else{return("JSOnline"); }
}}}

//////////////////////////////////////
function getTopVideos(increment){//this is what happens when people press the arrow buttons in the most popular box
var pageLimit = 4;
if (searchResults){pageLimit = (Math.ceil(totalCount/5)-1) }
//alert(pageLimit);
if (topPageNum < pageLimit && increment >0 ||topPageNum > 0 && increment < 0){
	topPageNum = topPageNum + increment;
	caller="topList";
	if (searchResults){
		//alert("search "+topPageNum);
		caller="";
		topVideoResponse(searchVideosComplete,topPageNum);
	}else{
topVideoResponse(topListComplete,topPageNum);
}}
}

function displaySearchResults(jsonData){//this just takes the search results and formats it for displaying
	var totalCount= jsonData["total_count"];
searchVideosComplete = new Array();
	for (var i=0; i<totalCount; i++) { 
	var title = jsonData["items"][i];
	if (checkCredit(title.tags)){	
	jsonData2 = new Object();	
	searchVideosComplete.push(title);	
	jsonData2.items = searchVideosComplete;
	}
	}
	jsonData2.total_count = searchVideosComplete.length;
	//alert(searchVideosComplete.length);
	videoResponse(jsonData2);
}

function videoResponse(jsonData) {	
	var resp = document.getElementById("resp");
	var totalCount= jsonData["total_count"];
	if (BCmethod =="topvideo"){totalCount = 50};//this limits the number of top videos to 50
	pageNum = Math.ceil(totalCount/12);
	document.getElementById('pages').innerHTML = (" page "+(onPage+1)+" of "+pageNum+" ");		
	
	var relText = document.getElementById("relatedText");
	if(BCmethod == "search"){
			var plural = "videos";
		if(totalCount=="1"){plural = "video";}
		relText.innerHTML = 'Search Results: '+totalCount+' '+plural+' found';
		//searchResults = false;
	}else{
		relText.innerHTML = 'Videos';
}	
	resp.innerHTML = "";	
	if (BCmethod =="search"){
	var startNum = onPage*12;
	}else{startNum = 0;}
	for (var i=startNum; i<(startNum+12); i++) { 
		var title = jsonData["items"][i];
	     title.account = onAccount;
		 title.Credit = findCredit(title.tags, onAccount);
		var str = "";
		str += '<div class="BCtitle" onClick="playTitlezz('+title.id+',\'' + title.account +'\',\'' + title.Credit  +'\')">';
		str += '<div class="thumb"><img src="' + title.thumbnailURL + '"/></div>';
		str += '<p class="displayName">' + title.name + '</p>';
		var newDate = new Date(title.publishedDate * 1);
	str += '<p class="displayDate">' + newDate.toLocaleDateString(); +' </p>';		
		str += '</div>';
		resp.innerHTML += str;
	}
	
}

function playlistResponse(jsonData) {	
//	alert(jsonData["videos"].length);
	var resp = document.getElementById("resp");
	var totalCount= jsonData["videos"].length;
    pageNum = Math.ceil(totalCount/12);
	document.getElementById('pages').innerHTML = ("page "+(onPage+1)+" of "+pageNum);	
	
	resp.innerHTML = "";
	for (var i=(onPage*12); i<((onPage*12)+12); i++) { //for (var i=0; i<jsonData["videos"].length; i++) {	
		var title = jsonData["videos"][i];	
		 title.account = onAccount;
		 title.Credit = findCredit(title.tags, onAccount);
		var str = "";
		str += '<div class="BCtitle" onClick="playTitlezz('+title.id+',\'' + title.account +'\',\'' + title.Credit  +'\')">';
		str += '<div class="thumb"><img src="' + title.thumbnailURL + '"/></div>';
		str += '<p class="displayName">' + title.name + '</p>';
		var newDate = new Date(title.publishedDate * 1);
	str += '<p class="displayDate">' + newDate.toLocaleDateString(); +' </p>';		
		str += '</div>';
		resp.innerHTML += str;
	}
}

//this runs on startup if there is no specific video
function startupResponse(jsonData){
	var title = jsonData["videos"][0];
	output_json_data = title.id;

	var videoPlayerModule = playerNiche.getModule(APIModules.VIDEO_PLAYER);
			videoPlayerModule.cueVideo(title.id);
			
}


function prevPage(){
	if (onPage > 0){
		loading();
	onPage--;
	if(BCmethod == "search"){
		videoResponse(jsonData2);
	}else{
	if (BCmethod == "video"){
	BCgetVideosByTags(onString,12,onPage,onCallback,onAccount);
}else if(BCmethod =="playlist"){
		BCgetPlaylistByID(onString,12,onPage,onCallback,onAccount);
	}else{
		BCgetTopVideos(12,onPage,onCallback,onAccount)
	}
}}}

function nextPage(){
	if (onPage < (pageNum-1)){
		loading();
	onPage++;
	if(BCmethod == "search"){
		videoResponse(jsonData2);
	}else{
	if (BCmethod == "video"){
	BCgetVideosByTags(onString,12,onPage,onCallback,onAccount);
}else if(BCmethod =="playlist"){
		BCgetPlaylistByID(onString,12,onPage,onCallback,onAccount);
	}else{
		BCgetTopVideos(12,onPage,onCallback,onAccount)
	}
}}}


function playTitlezz(id,pAccount,pCredit) {
	if(pAccount){
		accountName = pAccount;
	}
	switch (accountName) {
case 'TMJ': togglePlayer('tmjPlayer','mjsPlayer','nichePlayer');
			var videoPlayerModule = playerTMJ.getModule(APIModules.VIDEO_PLAYER);
			videoPlayerModule.loadVideo(id);
			var videoPlayerModule2 = playerMJS.getModule(APIModules.VIDEO_PLAYER);
			videoPlayerModule2.pause();
			var videoPlayerModule3 = playerNiche.getModule(APIModules.VIDEO_PLAYER);
			videoPlayerModule3.pause();
			if(pCredit){
				document.getElementById("playerTitle").innerHTML=pCredit;
			}else{
			document.getElementById("playerTitle").innerHTML="TODAY'S TMJ4";
			}
			break;
case 'Niche': //togglePlayer('nichePlayer','tmjPlayer','mjsPlayer');
			var videoPlayerModule = playerNiche.getModule(APIModules.VIDEO_PLAYER);
			videoPlayerModule.loadVideo(id);
			var videoPlayerModule2 = playerMJS.getModule(APIModules.VIDEO_PLAYER);
			videoPlayerModule2.pause();
			var videoPlayerModule3 = playerTMJ.getModule(APIModules.VIDEO_PLAYER);
			videoPlayerModule3.pause();
			if(pCredit){
				document.getElementById("playerTitle").innerHTML=pCredit;
			}else{
			document.getElementById("playerTitle").innerHTML="Journal Interactive";
			}
			break;
default: togglePlayer('mjsPlayer','tmjPlayer','nichePlayer');
			var videoPlayerModule = playerMJS.getModule(APIModules.VIDEO_PLAYER);
			videoPlayerModule.loadVideo(id);
			var videoPlayerModule2 = playerTMJ.getModule(APIModules.VIDEO_PLAYER);
			videoPlayerModule2.pause();			
			var videoPlayerModule3 = playerNiche.getModule(APIModules.VIDEO_PLAYER);
			videoPlayerModule3.pause();
			if(pCredit){
				document.getElementById("playerTitle").innerHTML=pCredit;
			}else{
			document.getElementById("playerTitle").innerHTML="JSOnline";
			}
}
//var relText = document.getElementById("relatedText");
location.href = "#BCtop";
} 

function togglePlayer(showID,hideID1,hideID2)
{
document.getElementById(hideID1).style.zIndex = "10";
document.getElementById(hideID2).style.zIndex = "20";
document.getElementById(showID).style.zIndex = "50";
}


///////////////////////////////////////////////Search code
function replace_space_with_comma(string){
//trim whitespace on both ends
var string = string.replace(/^\s+|\s+$/g, '');
//replace whitespace with comma
string = string.replace(/\s+|,\s+|\s+,/gi," ");
//return string - haha! lolz!
return string;

}
function searchForVideos(){
var searchString = document.getElementById('inputBox').value;
searchString = searchString.replace(/^\s+|\s+$/g, '');
searchResults = true;
if(searchString == "Search for Videos"|| searchString =="") { 
alert('Please enter text in the Search box'); 
}else{
topPageNum=0;
onPage = 0;
BCmethod = "search";
searchString = replace_space_with_comma(searchString);
BCgetVideosByText(searchString,100,0,"displaySearchResults","Niche");
} 
}

function clickclear(thisfield, defaulttext) {
if (thisfield.value == "Search for Videos") {
thisfield.value = "";
}
}

function doSearchForVideos(){
	// search bar
	if (!document.getElementById("searchbar")) return false;
	var gotcontainer = document.getElementById("searchbar");
	// input elements
	if (!gotcontainer.getElementsByTagName("input")) return false;
	var gotinputs = gotcontainer.getElementsByTagName("input");
	// attach input event handlers
	for (var i=0;i<gotinputs.length;i++)
	{
		gotinputs[i].onkeypress = function onEnterpress(e)
		{
			//define any varible
			var KeyPress;
			if(!e) e = window.event;
			KeyPress = e.keyCode ? e.keyCode : e.which;
			//13 is the key code of enter key
			if(KeyPress == 13)
			{
			searchForVideos();
				return false;
			}else{
				return true;
			}
		}
	}
}


    function onExternalAd(evt) {
        // In this specific example, evt.ad contains the synchedBanner XML
          // Create an XML doc with externalAd XML sent by the player
        var adXML = getXMLDoc(evt.ad);
       
        //Extract specific XML nodes for a video Ad
        var videoAd = getVideoAd(adXML);
        //Extract specific XML nodes for a Banner
        var collapsedAd = getCollapsedBanner(adXML);
        var expandedAd = getExpandedBanner(adXML);
        
        // Render a video Ad using the Adverstising module
        adModuleNiche.showAd(videoAd); 
        
        // Add an external banner to the HTML page using JS
        var expandedBanner = document.getElementById("adspace");
        var expandedBannerHTML = "<a href='" + expandedAd.expandedBannerClickURL + "' target='_blank' ><img src='" + expandedAd.expandedBannerURL + "' /></a>"; 
        //writes out the regular anchor/tag to the externalBanner div
        expandedBanner.innerHTML = expandedBannerHTML;

/*//this is commented out because there is no leaderboard on the SB video page
        var collapsedBanner = document.getElementById("ad");
       var collapsedBannerHTML = "<a href='" + collapsedAd.collapsedBannerClickURL + "' target='_blank' ><img src='" + collapsedAd.collapsedBannerURL + "' /></a>"; 
        //writes out the regular anchor/tag to the externalBanner div
        collapsedBanner.innerHTML = collapsedBannerHTML;
		*/
    }

    function onAdComplete(evt) {
        // Remove the banner on Ad Complete    
        var externalBanner = document.getElementById("externalBanner");        
//        externalBanner.innerHTML ="";
    }
    
    // Parses a synchedBanner ad XML and creates a video Ad 
    // Change accordingly to the XML that you are trafficking as external ad.
    function getVideoAd(adXML){
	 
        var videoAd = new Object();
       
        videoAd.type = "videoAd";
        
        var nodeItems = adXML.firstChild.childNodes.length;
        var currentNode = adXML.firstChild.firstChild;
        
        //get the root node attributes
        videoAd.duration = (adXML.firstChild.getAttribute("duration")) ? adXML.firstChild.getAttribute("duration") : 15;
        if(adXML.firstChild.getAttribute("trackStartURLs")) videoAd.trackStartURLs = adXML.firstChild.getAttribute("trackStartURLs").split(",");
        if(adXML.firstChild.getAttribute("trackMidURLs") ) videoAd.trackMidURLs = adXML.firstChild.getAttribute("trackMidURLs").split(",");
        if(adXML.firstChild.getAttribute("trackEndURLs") ) videoAd.trackEndURLs = adXML.firstChild.getAttribute("trackEndURLs").split(",");
        if(adXML.firstChild.getAttribute("trackPointURLs") ) videoAd.trackPointURLs = adXML.firstChild.getAttribute("trackPointURLs").split(",");
        videoAd.trackPointTime = (adXML.firstChild.getAttribute("trackPointTime") ) ? adXML.firstChild.getAttribute("trackPointTime") : 0;
    
        for(var i = 0; i < nodeItems; i++)
        {
            //checks to see if the current nodes are in our Rich Media Templates and assigns them if they exist
            if(currentNode.nodeName == "videoURL" && currentNode.firstChild) videoAd.videoURL = currentNode.firstChild.nodeValue; 
            if(currentNode.nodeName == "videoClickURL" && currentNode.firstChild) videoAd.videoClickURL = currentNode.firstChild.nodeValue;            
            currentNode = currentNode.nextSibling;
        }
        
        return videoAd;
    }    

    // Parses a synchedBanner ad XML and returns an object with the collapse banner URL and click URL
    // Change accordingly to the XML format that you traffic as external ad
	
    function getCollapsedBanner(adXML){
		
 
  var collapsedAd = new Object(); 
        
        var nodeItems = adXML.firstChild.childNodes.length;
        var currentNode = adXML.firstChild.firstChild;
            
        for(var i = 0; i < nodeItems; i++)
        {
            // Get only the collapseBanner attributes 
            if(currentNode.nodeName == "collapsedBannerURL" && currentNode.firstChild) collapsedAd.collapsedBannerURL = currentNode.firstChild.nodeValue;
            if(currentNode.nodeName == "collapsedBannerClickURL" && currentNode.firstChild) collapsedAd.collapsedBannerClickURL = currentNode.firstChild.nodeValue;
            currentNode = currentNode.nextSibling;
        }
                
        return collapsedAd;
		
    }    

    function getExpandedBanner(adXML){
        var expandedAd = new Object(); 
        
        var nodeItems = adXML.firstChild.childNodes.length;
        var currentNode = adXML.firstChild.firstChild;
            
        for(var i = 0; i < nodeItems; i++)
        {
            // Get only the collapseBanner attributes 
            if(currentNode.nodeName == "expandedBannerURL" && currentNode.firstChild) expandedAd.expandedBannerURL = currentNode.firstChild.nodeValue;
            if(currentNode.nodeName == "expandedBannerClickURL" && currentNode.firstChild) expandedAd.expandedBannerClickURL = currentNode.firstChild.nodeValue;
            currentNode = currentNode.nextSibling;
        }
                
        return expandedAd;
    }    

    function getXMLDoc(pXML){
    
        var adXML;
        if (window.ActiveXObject) {
            //parses the XML for IE browsers
            adXML = new ActiveXObject("Microsoft.XMLDOM");
            adXML.async = false;
            adXML.loadXML(pXML);
        }
        else //parses the XML for Mozilla browsers
            if (window.XMLHttpRequest) {
                adXML = (new DOMParser()).parseFromString(pXML, "text/xml"); 
            }
    return adXML;        
    }

