/**
 * @author Brandon Aaskov, modified by Michael Bosworth to use mootools
 *
 * ? Brightcove Inc 2007.  This document and its contents are intended for use solely in connection with
 * custom services being provided by Brightcove and cannot be used for any other reason or in any other
 * context without Brightcove?s prior written permission.
 */

var bc_playlist = [];
var bc_bodyZoneCheckboxes = [];
var bc_equipmentCheckboxes = [];
var bc_times = [];
var bc_workouts = [];
var chosenTime = 15;
var isIE6 = (BrowserDetect.browser == "Explorer" && BrowserDetect.version == "6") ? true : false;
var playlistArray = [];
var currentPlaylist = null;
var currentPlaylisti = 0;

jQuery(window).load(function(){

	/*
	createLibraryAPICall({
		method: "find_playlists_for_player_id",
		playerId: "1336737867",
		pageNumber: 0,
		pageSize: 100,
		callback: "buildMoreWorkouts"
	});
	*/
    /*
        Fitness Magazine: Lose the Baby Weight - 160531
        Fitness Magazine: The Celebrity Workout - 160530
        Fitness Magazine: 4-Week All-Over Makeover - 160529
        Fitness Magazine: 20-Minute Miracle Workout - 160528
        http://dev.bhg.com/partners/grab/grabApi.jsp?methodUrl=/guides/99/channels/329/channel_items
     */
	createLibraryAPICall({
		method: "/guides/99/channels/329/channel_items",
		callback: "buildMoreWorkouts"
	});

});




function buildMoreWorkouts(pItem){
    var i = 0, l = pItem.length;
    for( i; i<l; i++ ){
        playlistArray.push(pItem[i]);
    }
    mdp.GrabDataHandler = [];
    mdp.GrabDataHandler[currentPlaylisti] = new mdp.app.GrabDataHandler('mdp.GrabDataHandler[' + currentPlaylisti+']');
    currentPlaylist = playlistArray[currentPlaylisti];
    mdp.GrabDataHandler[currentPlaylisti].getVideosByPlaylistId( currentPlaylist['channel_item']['playlist_id'], 'makePlaylistObject' );
    /*
     [Object { channel_item=Object}, Object { channel_item=Object}, Object { channel_item=Object}, Object { channel_item=Object}]

    */

}

function makePlaylistObject( obj ){
    /*
    console.log( 'makePlaylistObject - ' + playlistArray.length );
    console.log( obj );
    console.log(currentPlaylist);
    /**/
    var time = 0;
    var bodyZones = [];
    var equipment = [];
    var videoIds = '';
    var i = 0, l = obj.length;
    var thumbnail ='';
    var desc = '';

    for( i; i<l; i++ ){
        if(i == 0){
            thumbnail = obj[i]['video']['thumbnail_url'];
            desc = obj[i]['video']['short_description'];
        }
        var timeTag = false;
        videoIds += ',' + obj[i]['video']['id'];
        var kwArr = obj[i]['video']['keywords'].split(', ');
        kwArr.each(function(value) {
            var keyword = value.split("-");
            if (keyword[0] == "target" && keyword[1]) {
                bodyZones.push(keyword[1]);
            }
            if (keyword[0] == "equipment" && keyword[1]) {
                equipment.push(keyword[1]);
            }
            if (keyword[0] == "time" && keyword[1]) {
                timeTag = true;
                time += keyword[1] * 100; /*time in milliseconds*/
            }
        });
        if(!timeTag) {
            time += obj[i]['video']['duration'];
        }
    }

    bodyZones = bodyZones.uniq(); /*remove duplicates*/
    equipment = equipment.uniq(); /*remove duplicates*/

    /*build a playlist item based on the video object we got back*/
    bc_workouts.push(new bc_LineupItem( {
        videoIds: videoIds.substr(1),
        displayName: currentPlaylist['channel_item']['name'],
        time: time,
        thumbnail: obj[0]['video']['thumbnail_url'],
        description: obj[0]['video']['short_description'],
        bodyZones: bodyZones,
        equipment: equipment,
        selected: false
    }));

    currentPlaylisti++;
    if(currentPlaylisti < playlistArray.length) {
        mdp.GrabDataHandler[currentPlaylisti] = new mdp.app.GrabDataHandler('mdp.GrabDataHandler[' + currentPlaylisti+']');
        currentPlaylist = playlistArray[currentPlaylisti];
        mdp.GrabDataHandler[currentPlaylisti].getVideosByPlaylistId( currentPlaylist['channel_item']['playlist_id'], 'makePlaylistObject' );
    } else {
        drawMoreWorkouts(bc_workouts);
    }
    /**/
}

function drawMoreWorkouts(pPlaylist)
{


	var htmlString = "";
	pPlaylist.each(function(pItem)
	{
		var name = (pItem.getName().toLowerCase().indexOf("fitness magazine: ") == -1) ? pItem.getName() : pItem.getName().substr(18);
		htmlString += "<li>\n";
		htmlString += "\t<img src='"+pItem.getThumbnail()+"' onclick='javascript:saveWorkout(\""+pItem.getId()+"\");' />\n";
		htmlString += "\t<h2>"+name+"</h2>\n";
		htmlString += "\t<span class='length'>"+Math.round(pItem.getTime()/1000/60)+" Minutes</span>\n";
		htmlString += "\t<span class='hr'></span>";
		htmlString += "</li>\n";
	});
	$("#workouts").innerHTML = htmlString;

	$("#workoutsContainer").css('visibility','visible');
}

function createLibraryAPICall()
{
	var url = {};
	var args = $H(arguments[0]);

	args.keys().each(function(pKey, pIndex)
	{
		if(pKey == "method") {
            url.method = args.values()[pIndex];
        }
		if(pKey == "callback") {
            url.callback = args.values()[pIndex];
        }
		if(pKey == "pageNumber") {
            url.pageNumber = args.values()[pIndex];
        }
		if(pKey == "fields") {
            url.fields = args.values()[pIndex];
        }
		if(pKey == "id") {
            url.id = args.values()[pIndex];
        }
		if(pKey == "videoIds") {
            url.videoIds = args.values()[pIndex];
        }
	});

/*	var apiCall = "http://api.brightcove.com/services/library?command=" + url.method + "&callback=" + url.callback + "&player_id=" + url.playerId + "&page_number=" + url.pageNumber + "&page_size="+url.pageSize+"&token=" + apiToken + "";//&ncflush*/
	var apiCall = "/partners/grab/grabApi.jsp?methodUrl=" + url.method + "&callback=" + url.callback + "";

	var scriptElem = document.createElement('script');
    scriptElem.setAttribute('src', apiCall);
    scriptElem.setAttribute('type','text/javascript');
    document.getElementsByTagName('head')[0].appendChild(scriptElem);
}




function getIndexFromId(pElementId)
{
	var index;
	bc_playlist.each(function(pItem, pIndex)
	{
		if(pItem.getId() == pElementId) {
            index = pIndex;
        }
	});

	return index;
}


function saveWorkout(pElementId)
{
	var index = getIndexFromId(pElementId);

	bc_playlist.each(function(pItem)
	{
		if (pItem.getId() == pElementId)
		{
			var time;
			if (Math.round(pItem.getTime()/1000/60) > 45) {
                time = 60;
            }
			if (Math.round(pItem.getTime()/1000/60) <= 45) {
                time = 45;
            }
			if (Math.round(pItem.getTime()/1000/60) <= 30) {
                time = 30;
            }
			if (Math.round(pItem.getTime()/1000/60) <= 20) {
                time = 20;
            }
			if (Math.round(pItem.getTime()/1000/60) <= 15) {
                time = 15;
            }

			var cookieData = "videoIds=" + pItem.videoIds.join(",") + "&bodyZones="+pItem.getBodyZones()+"&equipment="+pItem.getEquipment()+"&time=" +time+"";
			var expiryDate = new Date();
			expiryDate.setTime(expiryDate.getTime() + (365 * 24 * 60 * 60 * 1000)); //1 year from now
			setCookie(
			{
				name: "bcFitnessMagazine",
				data: cookieData,
				expires: expiryDate
			});
		}
	});

	window.location = "/app/buildaworkout/member/watchworkout.jsp";
}

