/**
* Handles always selecting the highest rendition when the player determines a new rendition can be played.
*/

var _player;
var _experienceModule;

var hqPresent = false, hdPresent = false;

/**
* Event handler for when the player the player first loads.
*
* @param  id  The HTML ID of the player.
*/
function onTemplateLoaded(id) {
    _player = brightcove.getExperience(id);
    _experienceModule = _player.getModule("experience");
    _experienceModule.addEventListener("templateReady", onTemplateReady);
	
	
    var _menuModule = _player.getModule("menu");
    _menuModule.addEventListener("videoRequest", switchToVideo);

    onTemplateReady();
}

function switchToVideo(event) {
	location.href = "/video/byId/" + event.args.id;
	return false;
}

/**
* Event handler for when the player is ready for interaction.
*
* @param  event  Event dispatched by player experience module.
*/
function onTemplateReady(event) {
//    _experienceModule.removeEventListener("templateReady", onTemplateReady);
    var videoPlayer = _player.getModule("videoPlayer");
    if (videoPlayer) {
        // set callback function for rendition selection
        videoPlayer.setRenditionSelectionCallback(selectRendition);
    }
}

/**
* The callback invoked whenever the player reaches a point when a new selection can be selected. This will occur on initial playback
* as well, for streaming videos, when there are multiple buffering events or when the screen size changed, as when going full screen.
* This method must take an object as an argument and return an int value that represents the index of the rendition to play.
*
* @param  context  The context that the player uses to select a new rendition. This object includes the following properties:
*           video  The video currently playing to which the renditions belong.
*           currentRendition  The currently selected rendition for the video.
*           renditions  An Array of renditions for the video to choose from.
*           detectedBandwidth  The last detected bandwidth value.
*           screenWidth  The pixel width of the video screen in which the rendition will play.
*           screenHeight  The pixel height of the video screen in which the rendition will play.
*
* @returns  The index of the rendition in the renditions list for the video player to play.
*/
function selectRendition(context) {
	var renditions = context.renditions;
    var renditionIndex = -1;
    var size = 0;
	hqPresent = false;
	hdPresent = false;
	
	var screenWidth = context.screenWidth;
	if ($("#main_content").hasClass("video-wide") && screenWidth < 720) {
		screenWidth = 933;
	}
	
	var currentDelta = 9999;
	var currentEncodingRate = 0;

    for (var i = 0; i < renditions.length; i++) {
		var delta = renditions[i].frameWidth - screenWidth;
		if (delta == 0 && renditions[i].encodingRate > currentEncodingRate) {
			renditionIndex = i;
			currentDelta = 0;
			currentEncodingRate = renditions[i].encodingRate;
		}
	
		if (delta > 0 && delta < currentDelta) {
			renditionIndex = i;
			currentDelta = delta;
			currentEncodingRate = renditions[i].encodingRate;
		}

		if (renditions[i].frameWidth > 624) {
			hqPresent = true;
		}
		if (renditions[i].frameWidth > 1279) {
			hdPresent = true;
		}
		
		if (renditionIndex == -1) {
			renditionIndex = i;  // select at least something
		}
    }

	setupHDButton(hqPresent, hdPresent);
//	console.log("selected " + renditions[renditionIndex].frameWidth + " for " + screenWidth)
//	describeRendition(renditions[renditionIndex]);
	return renditionIndex;
}

/**
* Traces out the values of rendition for testing.
*
* @param  rendition  The rendition to traces values for.
* @param  index  The index in the renditions array where this rendition is found.
*/
function describeRendition(rendition) {
    var message = ("size: " + rendition.size);
    message += ("\nframeWidth: " + rendition.frameWidth);
    message += ("\nframeHeight: " + rendition.frameHeight);
    message += ("\nencodingRate: " + rendition.encodingRate);
}

//	svitch video player to HD mode
function switchVideoPlayerMode() {
	var container = $("#videoplayerContainerSQ");
	if (!$("#main_content").hasClass("video-wide")) {

//		unloadVideo();

		$("#main_content").addClass("video-wide");
		$("#videoplayerObjectSQ")
			.css({
				width: container.attr("dim:width_hd"),
				height: container.attr("dim:height_hd")
			})
			.attr({
				width: container.attr("dim:width_hd"),
				height: container.attr("dim:height_hd")
			});

/*		
		$("#videoBlockSQ").addClass("hidden");

		createVideoPlayer ({
			id: "videoplayerObjectHD",
			playerId: 57165271001,  //sq=51422382001  hd=57165271001
			videoId: $("#videoplayerContainerSQ").attr("video_id"),
			containerId: "videoplayerContainerHQ",
			linkBaseUrl: $("#videoplayerContainerSQ").attr("linkBaseURL"),
			width: 933,
			height: 570
		});

		$("#videoBlockHQ").removeClass("hidden");
*/		
	} else {
		$("#main_content").removeClass("video-wide");		
		$("#videoplayerObjectSQ")
			.css({
				width: container.attr("dim:width"),
				height: container.attr("dim:height")
			})
			.attr({
				width: container.attr("dim:width"),
				height: container.attr("dim:height")
			});

/*	
		unloadVideo();

		createVideoPlayer ({
			id: "videoplayerObjectSQ",
			playerId: 51422382001,
			videoId: $("#videoplayerContainerSQ").attr("video_id"),
			containerId: "videoplayerContainerSQ",
			linkBaseUrl: $("#videoplayerContainerSQ").attr("linkBaseURL"),
			width: 624,
			height: 397
		});
*/		
	}

	setupHDButton(hqPresent, hdPresent);
}

function setupHDButton(hqPresent, hdPresent) {
	var icon = $("#videoplayer-hq-icon");

	if (!icon.data("switch-setup")) {
		icon.data("switch-setup", true);
		if (hqPresent) {
			icon.addClass("clickable").unbind().click(switchVideoPlayerMode);
		}
		if (hdPresent) {
			icon.addClass("hd");
		}
	}
	
	if (hqPresent) {
		icon.attr("title", "Switch to high quality");
	}

	if (hdPresent) {
		icon.attr("title", "Switch to High Definition");
	}
	
	if ($("#main_content").hasClass("video-wide")) {
		if (hdPresent) {
			icon.addClass("hd-pressed");
		} else {
			icon.addClass("pressed");
		}
		icon.attr("title", "Switch to normal quality")
	} else {
		icon.removeClass("pressed hd-pressed")
		if (hqPresent || hdPresent) {
//			icon.show();
			setupHdIconFading();
		}
	}
}


function unloadVideo() {
	var experienceTitle = "videoplayerObjectSQ";
/*	
	if (!$("#videoBlockHQ").hasClass("hidden")) {
		experienceTitle = "videoplayerObjectHD";
		$("#videoBlockHQ").addClass("hidden");
		$("#videoBlockSQ").removeClass("hidden");
		$.scrollTo($("#videoBlockSQ"));
	} else {
		$.scrollTo($("#videoBlockHQ"));
	}

	try {
		if (brightcove) {
			brightcove.removeExperience(experienceTitle);
		}
	} catch (err) {};
*/
	$("#main_content").removeClass("video-wide");
	$("#" + experienceTitle).remove();
}

function createVideoPlayer(options) {
	if (brightcove != undefined) {
		var player = brightcove.createElement("object");
		player.id = options.id;
	
		options.autoStart = "true";
		options.bgcolor = "#000000";
		options.wmode = "transparent";
		options.isVid = "true";
		var parameter;
		for (var i in options) {
		     parameter = brightcove.createElement("param");
		     parameter.name = i;
		     parameter.value = options[i];
		     player.appendChild(parameter);
		}
		brightcove.createExperience(player, $("#" + options.containerId)[0], true);
		return player;
	}
	
}





function setupHdIconFading () {
	var container = $("#videoplayerContainerSQ");
	var icon = $("#videoplayer-hq-icon");
	var autoHideHandler;
	var mode;

	var resetAutohide = function (){
		window.clearTimeout(autoHideHandler);
		autoHideHandler = window.setTimeout(hideIcon, 5000);
	}
	
	var hideIcon = function (){
		if (mode != "hiding") {
			mode = "hiding";
			icon.stop().fadeTo(150, 0, function(){
				icon.css("opacity", 0);
			});
		}
	}
	
	var showIcon = function (){
		if (mode != "showing") {
			mode = "showing";
			icon.stop().fadeTo(150, 1, function(){
				icon.css("opacity", "");
			});
		}
		resetAutohide();
	}
	container.hover(showIcon, hideIcon);
	container.mousemove(showIcon);
}