//globals
var player;
var content;
var video;
var experience;
var menu;
var advertising;
var proxy       = "http://api.connectok.com/json/?method=BrightCoveProxy.GetProxy";
var reqLibrary  = "http://api.brightcove.com/services/library?";
var activeSearchTerm = "";
var activePageNumber = 0;
var activePagButton = "pag0";
var pagType = "category";
var j = 4;
var activeLineupDTO;
var searchDTO;
var isBrowserIE6 = navigator.userAgent;
isBrowserIE6 = isBrowserIE6.search("MSIE 6");
var jURL = "http://" + hostname + "/gcal/videoGuide.php";
var currentSchedule = 0;
var playlistIndex = 1;
var recentlyPlayed = "";
var currentlyPlaying;

// called when template loads, this function stores a reference to the player and modules.
// Then event listeners will be added for when the template is ready and when a user 
// clicks on a video.
function onTemplateLoaded(pEvent) {
	player = bcPlayer.getExperience("myExperience");
	video = player.getModule(APIModules.VIDEO_PLAYER);
	content = player.getModule(APIModules.CONTENT);
	experience = player.getModule(APIModules.EXPERIENCE);
	menu = player.getModule(APIModules.MENU);
	advertising = player.getModule(APIModules.ADVERTISING);
	experience.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
	//video.addEventListener(BCVideoEvent.STREAM_START, onStreamStart);
	//video.addEventListener(BCVideoEvent.VIDEO_COMPLETE, onVideoComplete);
	content.addEventListener(BCContentEvent.VIDEO_LOAD, onVideoLoad);
	advertising.addEventListener(BCAdvertisingEvent.AD_START, onAdStart);
	// New media event added in BC 3.2 update
	video.addEventListener(BCMediaEvent.BEGIN, onMediaBegin);
	video.addEventListener(BCMediaEvent.COMPLETE, onMediaComplete);
}

function onAdStart(event) {
	document.getElementById('videoTitle').innerHTML = "Sponsor Message";
	document.getElementById('videoDesc').innerHTML = "";
	document.getElementById('videoPubDate').innerHTML = "";
	document.getElementById('videoLength').innerHTML = "";
}

function onTemplateReady(event) {
	playTitleFromList(myPlaylist[0]);
}

// This function gets the video details and sends the videos info to Omniture
function onMediaBegin() {
    var isMenuOpen = menu.isMenuPageShowing();
    if(isMenuOpen) {
        video.closeMenuPage();
    }
   	var titleDTO = video.getCurrentVideo();
	recentlyPlayed = titleDTO.id;
   	s.pageName='Video Play: ' + titleDTO.displayName;
   	s.prop8='Video Play: ' + titleDTO.displayName;
   	var s_code=s.t();
   	if(s_code)document.write(s_code);
    var YWATracker = YWA.getTracker("1000942893616");
    YWATracker.submit();
	// This API call populates info about the currently playing video
	var reqCommand  = "command=find_video_by_id";
	var reqParams   = "&video_id=" + titleDTO.id + "&fields=name,shortDescription,publishedDate,length,playsTotal";
	var reqCallBack = "&callback=videoDetailsResponse";
	var req         = proxy + "&url=" + escape(reqLibrary + reqCommand +  reqParams + reqCallBack);
	bObj            = new JSONscriptRequest(req, 0);
	bObj.buildScriptTag();
	bObj.addScriptTag();
}

function videoDetailsResponse(jsonData) {
	document.getElementById('videoTitle').innerHTML = jsonData.name;
	document.getElementById('videoDesc').innerHTML = jsonData.shortDescription;
	document.getElementById('videoPubDate').innerHTML = "Published: " + formatBCDateFull(jsonData.publishedDate);
	document.getElementById('videoLength').innerHTML = "Duration: " + formatTime(jsonData.length);
	document.getElementById('videoViews').innerHTML = "(" + jsonData.playsTotal + " views)<br />";
}

// handles click event from list items 
function playTitleFromList(id) {
    content.getVideoAsynch(id);
	currentlyPlaying = id;
}

//autoplays a video when it is loaded
function onVideoLoad(event) {
    video.loadVideo(event.video.id);
}

//detects end of video and then autoplays next video
function onMediaComplete(event) {
	if(currentlyPlaying == recentlyPlayed) { //if these are equal it means the video started streaming and not just the end of a bumper
		if (recentlyPlayed == myPlaylist[playlistIndex]) {//test to make sure you don't play the same video 2 times in a row
			playlistIndex = (playlistIndex > 2) ? 0 : playlistIndex + 1;
		}
		playTitleFromList(myPlaylist[playlistIndex]);
		playlistIndex = (playlistIndex > 2) ? 0 : playlistIndex + 1;
	}
}

function toggleVideoSearch() {
   	document.getElementById('videoSearchBar').style.display = (document.getElementById('videoSearchBar').style.display != 'none' ? 'none' : 'block');
   	document.getElementById('ok_subnav').style.display = (document.getElementById('ok_subnav').style.display != 'none' ? 'none' : 'block');
   	document.getElementById('featured_vids').style.display = (document.getElementById('featured_vids').style.display != 'none' ? 'none' : 'block');
   	document.getElementById('galleryList').style.display = (document.getElementById('galleryList').style.display != 'none' ? 'none' : 'block');
}

function searchCall(searchTerm, pageNumber) {
	activeSearchTerm = searchTerm;
	pagType = "search";
    j = 0;
    reqCommand      = "command=find_videos_by_text";
    reqParams       = "&text=" + encodeURI(searchTerm);
	reqPages    	= "&page_size=14&page_number=" + encodeURIComponent(pageNumber);
    reqCallBack     = "&callback=searchResponse";
    req             = proxy + "&url=" + escape(reqLibrary + reqCommand + reqParams + reqPages + reqCallBack);
    bObj            = new JSONscriptRequest(req, pageNumber);
    bObj.buildScriptTag();
    bObj.addScriptTag();
}

function searchResponse(jsonData) {
    searchDTO = jsonData;
    numOfVideos = jsonData["items"].length;
	document.getElementById("recent_vids").innerHTML = activeSearchTerm + " VIDEOS";
	if(numOfVideos == 0) {
		document.getElementById("vids_col").innerHTML = "Sorry no videos were found for your search.";
		return;
	}
    document.getElementById("vids_col").innerHTML = "";
    document.getElementById("vids_col2").innerHTML = "";
    var resp = document.getElementById("vids_col");
    var limit1 = j + 7;
    var limit2 = j + 14;
        // add an additional condition to test if j is  less than numOfVideos. j + ((activePagButton-1) * multiplier) Multiplier is 1
        //                                                                              on pag 1-3 and 2 on 4-6
    while (j < limit1) {
        var title = jsonData["items"][j];
        var str = "";
        str += '<div class="title item'+[j]+'" onClick="location.href=\'/multimedia/video/'+title.id+'\';">';
        str += '<div class="titleHolder">';
        str += '<div class="imageHolder">';
        str += '<div class="playThumb"><img src="http://static.newsok.biz/sites/newsok5/images/rollover_thumb.png" /></div>';
        str += '<div class="thumb"><img src="' + title.thumbnailURL + '"/></div>';
        str += '</div>';
        str += '<p class="displayName">';
        if (title.name.length > 25) {
            str += title.name.substring(0, 25).replace(/\s+\w+$/, '...');
        } else {
            str += title.name;
        }
        str += '</p>';
        str += '<p class="desc">';
        str += '<strong style="color:#41608B;">' + formatBCDate(title.publishedDate) + '</strong> ';
        if (title.shortDescription.length > 70) {
            str += title.shortDescription.substring(0, 70).replace(/\s+\w+$/, '...')
        } else {
            str += title.shortDescription
        }
        str += '</p>';
        str += '<div class="clear"></div>';
        str += '</div>';
        str += '<div class="clear"></div>';
        str += '</div>';
        resp.innerHTML += str;
        j++;
    }
    resp = document.getElementById("vids_col2");
    while (j < limit2) {
        var title = jsonData["items"][j];
        var str = "";
        str += '<div class="title item'+[j]+'" onClick="location.href=\'/multimedia/video/'+title.id+'\';">';
        str += '<div class="titleHolder">';
        str += '<div class="imageHolder">';
        str += '<div class="playThumb"><img src="http://static.newsok.biz/sites/newsok5/images/rollover_thumb.png" /></div>';
        str += '<div class="thumb"><img src="' + title.thumbnailURL + '"/></div>';
        str += '</div>';
        str += '<p class="displayName">';
        if (title.name.length > 25) {
            str += title.name.substring(0, 25).replace(/\s+\w+$/, '...');
        } else {
            str += title.name;
        }
        str += '</p>';
        str += '<p class="desc">';
        str += '<strong style="color:#41608B;">' + formatBCDate(title.publishedDate) + '</strong> ';
        if (title.shortDescription.length > 70) {
                str += title.shortDescription.substring(0, 70).replace(/\s+\w+$/, '...')
        } else {
                str += title.shortDescription
        }
        str += '</p>';
        str += '<div class="clear"></div>';
        str += '</div>';
        str += '<div class="clear"></div>';
        str += '</div>';
        resp.innerHTML += str;
        j++;
    }
}

function getSchedule(myPag) {
	if(myPag!=0){
		document.getElementById('dailySchedule').innerHTML = "<div id='scheduleLoading'></div>";
		currentSchedule += myPag;
		jQuery.post(jURL, { day: currentSchedule }, function(data) {document.getElementById('dailySchedule').innerHTML = data;}, 'text');
	}
	var today = new Date();
	var myTime = new Date(today.getYear(), today.getMonth(), today.getDate()-0+currentSchedule);
	myTime = myTime.getTime();
	document.getElementById("changeDay").innerHTML = formatBCDate(myTime, 2);
}

function pagCall(el) {
    var pageNumber = el.innerHTML;
    pageNumber = Number(pageNumber) - 1;
    if(pageNumber == activePageNumber) {
        return;
    } else {
        activePageNumber = pageNumber;
    }
    el.className='pagination page_selected';
    document.getElementById(activePagButton).className = 'pagination';
    activePagButton=el.id;
    document.getElementById("vids_col").innerHTML = "";
    document.getElementById("vids_col2").innerHTML = "";
    if(pagType == "category") {
       	j = (pageNumber * 14) + 4;
		if(typeof(activeLineupDTO)!="undefined") {
			categoryResponse(activeLineupDTO);
		} else {
			categoryCall();
		}
	} else if(pagType == "search") {
		searchCall(activeSearchTerm, activePageNumber);
	}
}

function nextPag() {
    if(activePageNumber != 5) {
		activePageNumber++;
	} else {
		return;
	}
    document.getElementById("vids_col").innerHTML = "";
    document.getElementById("vids_col2").innerHTML = "";
    if(pagType == "category") {
      	j = activePageNumber * 14;
		if(typeof(activeLineupDTO)!="undefined") {
			categoryResponse(activeLineupDTO);
		} else {
			categoryCall();
		}
	} else if(pagType == "search") {
		searchCall(activeSearchTerm, activePageNumber);
	}
        document.getElementById(activePagButton).className = "pagination";
        activePagButton = "pag" + activePageNumber.toString();
        document.getElementById(activePagButton).className = "pagination page_selected";
}

function prevPag(currentPag) {
	if(activePageNumber > 0) {
		activePageNumber--;
	} else {
		return;
	}
    j = j - 28;
    document.getElementById("vids_col").innerHTML = "";
    document.getElementById("vids_col2").innerHTML = "";
    if(pagType == "category") {
		categoryResponse(activeLineupDTO);
	} else if(pagType == "search") {
		searchCall(activeSearchTerm, activePageNumber);
	}
    document.getElementById(activePagButton).className = "pagination";
    activePagButton = "pag" + activePageNumber.toString();
    document.getElementById(activePagButton).className = "pagination page_selected";
}

function categoryCall() {
    document.getElementById("vids_col").innerHTML = "";
    document.getElementById("vids_col2").innerHTML = "";
	var proxy		= "http://api.connectok.com/json/?method=BrightCoveProxy.GetProxy&limit=88";
	var reqCommand	= "command=find_videos_by_tags";
	var reqParams   = "&sort_by=MODIFIED_DATE&sort_order=DESC";
	var reqCallBack	= "&callback=categoryResponse";
	var req        	= proxy + "&url=" + escape(reqLibrary + reqCommand + tagString + reqParams + reqCallBack);
    // Create a new request object
    bObj            = new JSONscriptRequest(req, 0);
    // Build the dynamic script tag
    bObj.buildScriptTag();
    // Add the script tag to the page
    bObj.addScriptTag();
	document.getElementById(activePagButton).className = "pagination";
	document.getElementById(activePagButton).className = "pagination page_selected";
}
// Define the callback function, which writes out the HTML
// from the json request.
function categoryResponse(jsonData) {
	pagType = "category";
	activeLineupDTO = jsonData;
	numOfVideos = activeLineupDTO["items"].length;
	var resp = document.getElementById("vids_col");
	var limit1 = j + 7;
	var limit2 = j + 14;
	// add an additional condition to test if j is  less than numOfVideos. j + ((activePagButton-1) * multiplier) Multiplier is 1
	//										on pag 1-3 and 2 on 4-6
	while (j < limit1) {
		var title = jsonData["items"][j];
		var str = "";
		str += '<div class="title item'+[j]+'" onClick="location.href=\'/multimedia/video/'+title.id+'\';">';
		str += '<div class="titleHolder">';
		str += '<div class="imageHolder">';
		str += '<div class="playThumb"><img src="http://static.newsok.biz/sites/newsok5/images/rollover_thumb.png" /></div>';
		str += '<div class="thumb"><img src="' + title.thumbnailURL + '"/></div>';
		str += '</div>';
		str += '<p class="displayName">';
		if (title.name.length > 50) {
			str += title.name.substring(0, 50).replace(/\s+\w+$/, '...');
		} else {
			str += title.name;
		}
		str += '</p>';
		str += '<p class="desc">';
		str += '<strong style="color:#41608B;">' + formatBCDate(title.publishedDate) + '</strong> ';
		if (title.shortDescription.length > 65) {
			str += title.shortDescription.substring(0, 65).replace(/\s+\w+$/, '...')
		} else {
			str += title.shortDescription
		}
		str += '</p>';
		str += '<div class="clear"></div>';
		str += '</div>';
		str += '<div class="clear"></div>';
		str += '</div>';
		resp.innerHTML += str;
		j++;
	}
	resp = document.getElementById("vids_col2");
        while (j < limit2) {
                var title = jsonData["items"][j];
                var str = "";
                str += '<div class="title item'+[j]+'" onClick="location.href=\'/multimedia/video/'+title.id+'\';">';
                str += '<div class="titleHolder">';
                str += '<div class="imageHolder">';
                str += '<div class="playThumb"><img src="http://static.newsok.biz/sites/newsok5/images/rollover_thumb.png" /></div>';
                str += '<div class="thumb"><img src="' + title.thumbnailURL + '"/></div>';
                str += '</div>';
                str += '<p class="displayName">';
                if (title.name.length > 50) {
                        str += title.name.substring(0, 50).replace(/\s+\w+$/, '...');
                } else {
                        str += title.name;
                }
                str += '</p>';
                str += '<p class="desc">';
                str += '<strong style="color:#41608B;">' + formatBCDate(title.publishedDate) + '</strong> ';
                if (title.shortDescription.length > 65) {
                        str += title.shortDescription.substring(0, 65).replace(/\s+\w+$/, '...')
                } else {
                        str += title.shortDescription
                }
                str += '</p>';
                str += '<div class="clear"></div>';
                str += '</div>';
                str += '<div class="clear"></div>';
                str += '</div>';
                resp.innerHTML += str;
		j++;
        }
}
function popularCall(popularSince) {
        document.getElementById("vids_col").innerHTML = "";
        document.getElementById("vids_col2").innerHTML = "";
        var proxy       = "http://api.connectok.com/json/?method=BrightCoveProxy.GetProxy&limit=4";
        var reqLibrary  = "http://api.brightcove.com/services/library?";
        var reqCommand  = "command=find_videos_by_tags";
        var reqParams   = "&and_tags=home&sort_by=PLAYS_TRAILING_WEEK";
        var reqCallBack = "&callback=popularResponse";
        var req         = proxy + "&url=" + escape(reqLibrary + reqCommand + reqParams + reqCallBack);
	j = 0;
        // Create a new request object
        bObj            = new JSONscriptRequest(req, 0);
        // Build the dynamic script tag
        bObj.buildScriptTag();
        // Add the script tag to the page
        bObj.addScriptTag();
	document.getElementById(activePagButton).className = "pagination";
	activePagButton = "pag0";
	document.getElementById(activePagButton).className = "pagination page_selected";
}
// Define the callback function, which writes out the HTML
// from the json request.
function popularResponse(jsonData) {
	pagType = "category";
	activeLineupDTO = jsonData;
	numOfVideos = activeLineupDTO["items"].length;
	var resp = document.getElementById("vids_col");
	var limit1 = j + 7;
	var limit2 = j + 14;
	// add an additional condition to test if j is  less than numOfVideos. j + ((activePagButton-1) * multiplier) Multiplier is 1
	//										on pag 1-3 and 2 on 4-6
	while (j < limit1) {
		var title = jsonData["items"][j];
		var str = "";
		str += '<div class="title item'+[j]+'" onClick="location.href=\'/multimedia/video/'+title.id+'\';">';
		str += '<div class="titleHolder">';
		str += '<div class="imageHolder">';
		str += '<div class="playThumb"><img src="http://static.newsok.biz/sites/newsok5/images/rollover_thumb.png" /></div>';
		str += '<div class="thumb"><img src="' + title.thumbnailURL + '"/></div>';
		str += '</div>';
		str += '<p class="displayName">';
		if (title.name.length > 50) {
			str += title.name.substring(0, 50).replace(/\s+\w+$/, '...');
		} else {
			str += title.name;
		}
		str += '</p>';
		str += '<p class="desc">';
		str += '<strong style="color:#41608B;">' + formatBCDate(title.publishedDate) + '</strong> ';
		if (title.shortDescription.length > 65) {
			str += title.shortDescription.substring(0, 65).replace(/\s+\w+$/, '...')
		} else {
			str += title.shortDescription
		}
		str += '</p>';
		str += '<div class="clear"></div>';
		str += '</div>';
		str += '<div class="clear"></div>';
		str += '</div>';
		resp.innerHTML += str;
		j++;
	}
	resp = document.getElementById("vids_col2");
        while (j < limit2) {
                var title = jsonData["items"][j];
                var str = "";
                str += '<div class="title item'+[j]+'" onClick="location.href=\'/multimedia/video/'+title.id+'\';">';
                str += '<div class="titleHolder">';
                str += '<div class="imageHolder">';
                str += '<div class="playThumb"><img src="http://static.newsok.biz/sites/newsok5/images/rollover_thumb.png" /></div>';
                str += '<div class="thumb"><img src="' + title.thumbnailURL + '"/></div>';
                str += '</div>';
                str += '<p class="displayName">';
                if (title.name.length > 50) {
                        str += title.name.substring(0, 50).replace(/\s+\w+$/, '...');
                } else {
                        str += title.name;
                }
                str += '</p>';
                str += '<p class="desc">';
                str += '<strong style="color:#41608B;">' + formatBCDate(title.publishedDate) + '</strong> ';
                if (title.shortDescription.length > 65) {
                        str += title.shortDescription.substring(0, 65).replace(/\s+\w+$/, '...')
                } else {
                        str += title.shortDescription
                }
                str += '</p>';
                str += '<div class="clear"></div>';
                str += '</div>';
                str += '<div class="clear"></div>';
                str += '</div>';
                resp.innerHTML += str;
		j++;
        }
}

