﻿var firstrun = true; 

// INITIALIZER --------------------------------------------------- |

$(document).ready(function() {
	
    setUpScrollBar();
    resultHandlers();
	moreHandlers();
	$('#sr').append('Недавно добавлено');

	//$("#innerhead").hide();
	
	addScriptTag(buildURL("find_videos_by_tags","modified_date", "100", "ru", null, null));
					
	var tmp = $(".tabbed-collection").children().length;
	if( tmp > 1 ){
		$("ul:odd").removeClass("collection-nav");
	}
});



// SCROLLBAR ----------------------------------------------------- |
function setUpScrollBar(){
	
    $("#vp_results_scrollbar").slider({
        animate: true,
        orientaion: 'vertical',
        handle: "#vp_results_scrollbar_thumb",
        change: handleSliderChange,
        slide: handleSliderSlide
    });

}

function handleSliderChange(e, ui) {
	
    var maxScroll = $("#vp_results_items").attr("scrollHeight") - $("#vp_results_items").height();
    $("#vp_results_items").animate({ scrollTop: ui.value * (maxScroll / 100) }, 1000);

}

function handleSliderSlide(e, ui) {
	
    var maxScroll = $("#vp_results_items").attr("scrollHeight") - $("#vp_results_items").height();
    $("#vp_results_items").attr({ scrollTop: ui.value * (maxScroll / 100)});

}

// MORE VIDEOS HANDLERS ------------------------------------------ |
function moreHandlers()
{
	$('.more_links a').click(getMore);
}

function getMore()
{
	var u = "";
	
	switch ($(this).attr('id'))
	{
		             //bulidURL( command, sortBy, page, tags, text, vid )
					 
		case 'm0': 	u = buildURL("find_videos_by_tags","modified_date", "100", "ru", null, null);  //View All
					$('#sr').text('View All Videos');
		break;
		case 'm1': 	u = buildURL("find_related_videos",null , "100", null, null, _currentVideo); // Related
					$('#sr').text('Related Videos');
		break;
		case 'm2': 	u = buildURL("find_videos_by_tags","plays_trailing_week", "5", "ru" , null, null); //Top 10
					$('#sr').text('Top 5 Videos');
		break;
		case 'm3': 	u = buildURL("find_videos_by_tags","modified_date", "5", "ru" , null, null); //Recently Added
					$('#sr').text('Recently Added Videos');
		break;
	}
	
	addScriptTag(u);
}


// PLAYLIST SELECT FUNCTIONS ------------------------------------------------ |

function resultHandlers() {

    $('.vp_results_content > div').click(loadVideo);
}

function loadVideoContent(jsonData2) {

    var ci = jsonData2; // Current Item (ci) : Data associated with selected video
   
	var _movVideoURL = ci.renditions;
	var qtDownload;
	var wmvDownload;
	
		/*
			@Properties list for each video object [in index order] 
		 
			id, name, shortDescription, longDescription, creationDate, publishedDate, lastModifiedDate, linkURL
			linkText, tags, videoStillURL, thumbnailURL, referenceId, length, economics
			playsTotal, playsTrailingWeek, FLVURL, renditions, FLVFullLength
		*/
	
	// 1. Get Video time and convert it from (ms) to mm:ss | Set other video details
		
	var min = Math.floor((ci.length / (1000*60)));
	var sec = Math.ceil((ci.length % (1000*60)) / 1000);
	if(sec < 10){ sec = "0" + sec;}
	
	var time = min + ":" + sec;
	
	// 2. Checks for any Quicktime (H.264 ".MP4" file formate) and Windows Media (WMV) video files for downloading and sets the value.
	
	// ----------------------------------------------------- //
	for (var i = 0; i < _movVideoURL.length; i++) {
	
		var mvSearch = _movVideoURL[i].url;
		
		if (mvSearch == null || mvSearch == undefined){
			
			mvSearch != "";
			qtDownload = "";
			
			}
		
		if (_movVideoURL.length < 5){qtDownload = "";}
	
		else if (mvSearch != null || mvSearch != undefined){
			
				var url0 = _movVideoURL[0].url;
				var url1 = _movVideoURL[1].url;
				var url2 = _movVideoURL[2].url;
				var url3 = _movVideoURL[3].url;
				var url4 = _movVideoURL[4].url;
				
				if (url0.search(".mp4") != -1){qtDownload = url0;}
				if (url1.search(".mp4") != -1){qtDownload = url1;}
				if (url2.search(".mp4") != -1){qtDownload = url2;}
				if (url3.search(".mp4") != -1){qtDownload = url3;}
				if (url4.search(".mp4") != -1){qtDownload = url4;}
			}
		}
	// Checks the WMV Download Link and sets the value	
	if (ci.linkURL == null || ci.linkURL == undefined){wmvDownload = "";}
	else {wmvDownload = ci.linkURL;}
	
	// ----------------------------------------------------- //
	
	var ciTL = (ci.name).length;
	var videoTitle = (ci.name).slice(0,(ciTL-4));
	
	//var vdescString = '<div class="vlegend"><div class="ccIcon"></div><div class="cctext">Closed Captions/Subtitles</div></div>'
	$('.vtitle').empty();
	$('.vtime').empty();
	
	$('.vtitle').append(videoTitle);
	$('.vtime').text(time);
	$('.vtime').append('<br />');
	
	
	
	if (qtDownload == "" || wmvDownload == "" || qtDownload == undefined || wmvDownload == undefined || qtDownload == null || wmvDownload == null){
		
		$('.vdesc').empty();
		$('.vdesc').text(ci.shortDescription);
		//$('.vdesc').append(vdescString);
	
		}
		
	if (qtDownload != "" && qtDownload != undefined){
		
		$('.vdesc').empty();
		$('.vdesc').append(ci.shortDescription + '<br /><h5 class="vdownload">Сгрузить видео | <a class="dlink" title="'+ ci.name + ' download' + '" href="' + qtDownload + '">Программа Quicktime</a></h5>');
		//$('.vdesc').append(vdescString);
		}
	
	if (wmvDownload != "" && wmvDownload != undefined){
		
		$('.vdesc').empty();
		$('.vdesc').append(ci.shortDescription + '<br /><h5 class="vdownload">Сгрузить видео | <a class="dlink" title="'+ ci.name + ' download' + '" href="' + ci.linkURL + '">Формат WMV</a></h5>');
		//$('.vdesc').append(vdescString);
		}
	
	if (wmvDownload != "" && qtDownload != "" && wmvDownload != undefined && qtDownload != undefined){
		
		$('.vdesc').empty();
		$('.vdesc').append(ci.shortDescription + '<br /><h5 class="vdownload">Сгрузить видео | <a class="dlink" title="'+ ci.name + ' download' + '" href="' + ci.linkURL + '">Формат WMV</a> | <a class="dlink" title="'+ ci.name + ' download' + '" href="' + qtDownload + '">Программа Quicktime</a></h5>');
		//$('.vdesc').append(vdescString);
		}
 }

function loadVideo() {

	// 1. Fliter video Data for Selected Video
	
    var vp = $(this).attr('name'); //Video position in JSON Array and Results List
    var ci = _globalJD[vp]; // Current Item (ci) : Data associated with selected video
    _currentVideo = ci.id;
	loadVideoContent(ci);
	
		/*
			@Properties list for each video object [in index order] 
		 
			id, name, shortDescription, longDescription, creationDate, publishedDate, lastModifiedDate, linkURL
			linkText, tags, videoStillURL, thumbnailURL, referenceId, length, economics
			playsTotal, playsTrailingWeek, FLVURL, renditions, FLVFullLength
		*/	
	
	// 2. Load new Flash videos
	
	var swf = null;
	var f= "";
	var m = "amgAS3VideoPlayer400";
	
	if (navigator.appName.indexOf("Microsoft") != -1) {
			swf  = window[m];
         } else {
            swf = document[m];
         }
	
	swf.exContentLoad(ci.id);
	
 }

 
// BRIGHTCOVE QUERY SETUP --------------------------------------------------- |

var _globalJD = null; 			//Stores values from Brightcove for Global use. Value set in the 'response' function
var _currentVideo = null;		//Stores a the video id for the currently playing video. Set in 'loadVideo' function

// Build Query String to access Brightcove API
function buildURL(command,sortBy, page, tags, text, vid){
	
	var url = ""
	
	url += "http://api.brightcove.com/services/library?";
	url += "command=" + command + "&";
	
	if (tags != null){ url += "and_tags=" + tags + "&";}
	if (text != null){ url += "text=" + text + "&";}
	if (vid != null) { url += "video_id=" + vid + "&";}
	
	url += "token=" + "MF-unhYayyy7RkxgNn1psfugUQztJH08j0xPwP6McAI." + "&";
	url += "fields=null";
	
	if (sortBy != null) {url += "&sort_by="+ sortBy + "&";}
	
	url += "page_size=" + page + "&";
	url += "callback=response";
	
	return url;
}
 
// Write new Script tag to header
function addScriptTag(url) {
    
	$('#topVideos').remove();
	
	var scriptTag = document.createElement("script");
	
    scriptTag.setAttribute("type", "text/javascript");
    scriptTag.setAttribute("charset", "utf-8");
    scriptTag.setAttribute("src", url);
    scriptTag.setAttribute("id", "topVideos");

    var head = document.getElementsByTagName("head").item(0);
    head.appendChild(scriptTag);

}

// Rebuild video results list
// 'addScriptTag' callback
function response(jsonData) {

    $('.vp_results_content').empty();

    _globalJD = jsonData["items"];

    var container = $('.vp_results_content');

    for (var i = 0; i < _globalJD.length; i++) {

        var title = _globalJD[i];
		
		var ciTL = (title.name).length;
		var videoTitle = (title.name).slice(0,(ciTL-4));

        var str = "";

        str += '<div name="' + i + '" class="playlist_item"  ><a title="' + videoTitle + '" href="#pi' + i + '" rel="#pi' + i + '">';
        str += '<div class="vi"><img src="' + title.thumbnailURL + '" width="120px" height="70px"/></div>';
        str += '<div class="vd">';
        str += '<span class="result_title">' + videoTitle + '</span>';
        str += '<p class="result_desc">' + title.shortDescription + '</p>';
        str += '</div>';
        str += '</a></div>';

        $('.vp_results_content').append(str);

    }

    resultHandlers();
    
	if (firstrun == true){ loadFP(_globalJD[0].id); }
	firstrun = false;

}

// Used to repsond to videoId in query string
function getFirstVideo(url) {

	var scriptTag = document.createElement("script");
	
    scriptTag.setAttribute("type", "text/javascript");
    scriptTag.setAttribute("charset", "utf-8");
    scriptTag.setAttribute("src", url);
    scriptTag.setAttribute("id", "getFirst");

    var head = document.getElementsByTagName("head").item(0);
    head.appendChild(scriptTag);

}

// Callback method for 'getFirst'
// Updates video description
function loadFirstVideo(jsonData)
{
    
	var ci = jsonData;
	loadVideoContent(ci);
	
}


// SWF Object load Flash Player
function loadFP(id){
	
		var vid = "";
	
		if (swfobject.getQueryParamValue("videoId") == null || swfobject.getQueryParamValue("videoId") == undefined || swfobject.getQueryParamValue("videoId") == ""){

		    vid = id;
		    loadFirstVideo(_globalJD[0]);
			
		} else {

			vid = swfobject.getQueryParamValue("videoId");
			getFirstVideo(' http://api.brightcove.com/services/library?command=find_video_by_id&video_id=' + vid + '&token=MF-unhYayyy7RkxgNn1psfugUQztJH08j0xPwP6McAI.&callback=loadFirstVideo');
		}
	
		var flashvars = {

				allowFullScreen: "true",
				autoStart: "false",
				playlist: "",
				playerWidth: "400",
				EmbedCode: "on",
				swliveconnect: "true",
				copyUrl: document.location,
				flashId: "amgAS3VideoPlayer400",
				language: "ru"

		};
		
		_currentVideo = vid;
		flashvars.videoId = vid;

		var params = {
				allowFullScreen: "true",
				bgcolor: "#000000",
				allowScriptAccess: "always",
				swliveconnect: "true"
		};

		var attributes = {
				name: "amgAS3VideoPlayer400",
				id: "amgAS3VideoPlayer400"
		};

		//swfobject.embedSWF("http://agtest.static.getusinfo.com/brightcove/brightcove3/amgas3videoplayer400.swf", "altContent", "400", "350", "8.0.0.0", "http://www.america.gov/media/expressInstall.swf", flashvars, params, attributes);
		swfobject.embedSWF("http://www.america.gov/amgas3videoplayer400.swf", "altContent", "400", "350", "8.0.0.0", "http://www.america.gov/media/expressInstall.swf", flashvars, params, attributes);
}









