/**
*	General Thumb Viewer Control
*   TODO: get width and height values of embed dynamically
**/

/**
*	Unfortunately need to litter the global scope in order to get a youtube reference on youtube's callback function
**/

function onYouTubePlayerReady(playerId) {
    POP.YouTubeViewer.videoReady(playerId);
}

POP.YouTubeViewer = (function () {
    var _targets, config, animate, _pageURL;

    function __init(targets, config) {
        _targets = $(targets);
        //get out if no targets
        if (_targets.length < 1) { return; }
		_pageURL = document.location.pathname;
        _config = $.extend({
            type: 'Default',
            speedIn: 400,
            speedOut: 400,
            mediaWidth: 605,
            mediaHeight: 356
        }, config || {});
        _animate = (jQuery.support.opacity) ? true : false;
        for (var i = 0, len = _targets.length; i < len; i++) {
            var type = _config.type || $(_targets[i]).data('type');
            var youTubeViewer = POP.YouTubeViewerType.factory(type);
            youTubeViewer.view($(_targets[i]), __create, null, this);
        }
    }

    function __create(obj) {
        var li = $(obj.find('.video-assets li:first')),
			thumb = $(obj.find('.video-thumbs li:first'));

        __slideLeft(li, thumb);

        __addEventListeners(obj);
    }

    function __addEventListeners(obj) {
        var thumbs = obj.find('.videos-list li');
        thumbs.bind('click', function (e) {
            e.preventDefault();
            __onThumbClick(e, obj);
        });
		//just for tracking
		var videoAssets = $('.video-assets');
		videoAssets.delegate('li', 'mouseup', function(e) {
			var videoId = $(this).data('videoid');
			__trackEvent('Videos', videoId + 'Play');
		});
		//end tracking
    }

    function __onThumbClick(e, obj) {
        var thumb = $(e.currentTarget),
			thumbIndex = thumb.index(),
			video = thumb.find('img').data('video'),
			videoAssets = $(obj.find('.video-assets')),
			current, currentIndex = 0,
			next, isCurrentThumb = false;

        isCurrentThumb = thumb.hasClass('current');
        if (!isCurrentThumb) {
            current = videoAssets.find('.current');
            if (current.length > 0) {
                thumb.siblings().removeClass('current');
                current.removeClass('current');
                __slideRight(current);
            }
            next = videoAssets.find('li:eq(' + thumbIndex + ')');
            __slideLeft(next, thumb);
			__trackEvent('Carousel', 'Videos');
        } else {
            return null;
        }
    }

    function __slideLeft(li, thumb) {
        var isLoaded = false,
			video = thumb.find('img').data('video');
        li.addClass('current');
        thumb.addClass('current');
        li.stop().animate({
            'left': '0px'
        }, _config.speedOut, function () {
            isLoaded = li.hasClass('loaded');
            if (!isLoaded) {
                li.addClass('loaded');
                __loadVideo(li, video);
            }
        });
    }

    function __slideRight(li) {
        var vplayer = li.find('object'),
			isPlaying = false;
        if (vplayer) {
            //make sure we are stopping any playing videos
            isPlaying = vplayer[0].getPlayerState();
            if (isPlaying === 1) {
                vplayer[0].stopVideo();
            }
        }
        li.stop().animate({
            'left': '632px'
        }, _config.speedIn, function () {
            //done animating
        });
    }

    function __loadVideo(li, video) {
        var time = new Date().getTime(),
			playerId = 'player-' + time,
			embedId = 'video-' + time,
			embedEl = $('<div id="' + embedId + '">This feature requires <a href="http://get.adobe.com/flashplayer/">Adobe Flash Player</a>.</div>'), //add a unique id name for the video object
			params, attributes;
		li.data('videoid', video);
        li.addClass(playerId);  //add class so we can reference this player instance
        li.html(embedEl);
        params = {
            allowScriptAccess: "always",
            wmode: "transparent",
            allowFullscreen: true
        };
        attributes = {
            id: embedId
        };
        swfobject.embedSWF('http://www.youtube.com/e/' + video + '?enablejsapi=1&playerapiid=player-' + playerId + '&wmode=transparent&rel=0', embedId, _config.mediaWidth, _config.mediaHeight, '8', null, null, params, attributes);
    }

    function __videoReady(id) {
        //console.log('ID: ' + id);
    }

	function __trackEvent(category, label) {
        //console.log('Track: ', category, label);
        _gaq.push([
			'_trackEvent',
			category,
			_pageURL,
			label
		]);
    }

    //Publicly exposed methods, properties
    return {
        init: function (targets, config) {
            __init(targets, config);
        },
        videoReady: function (id) {
            __videoReady(id);
        }
    }
} ());

/**
*	Stub functions for thumb viewer types - should be overwritten
**/

POP.YouTubeViewerType = function () { };

POP.YouTubeViewerType.prototype = {
    model: function () { },
    view: function (obj, callback, callbackParams, ctx) { }
};

/**
*	Factory methods for making different Thumb viewer Types
**/
POP.YouTubeViewerType.factory = function (type) {
    var constr = type,
		newType;

    if (typeof POP.YouTubeViewerType[constr] !== "function") {
        throw {
            name: "Error",
            message: constr + " doesn\'t exist."
        };
    }

    if (typeof POP.YouTubeViewerType[constr].prototype.model !== 'function') {
        POP.YouTubeViewerType[constr].prototype = new POP.YouTubeViewerType();
    }

    newType = new POP.YouTubeViewerType[constr]();
    return newType;
};

POP.YouTubeViewerType.Default = function () { };

POP.YouTubeViewerType.Default.prototype.model = function (obj) {
    var lis = obj.find('li'),
        len = lis.length,
		html = '<ul>';
    for(var i = 0; i < len; i++) {
        html += '<li></li>';
        //add class to take off right margin on 3rd li (3 column layout)
        if ((i + 1) % 3 === 0) {
            $(obj.find('li:eq(' + i + ')')).addClass('no-margin-right-3-col');
        }
        //add class to take off right margin on 4th li
        if ((i + 1) % 4 === 0) {
            $(obj.find('li:eq(' + i + ')')).addClass('no-margin-right');
        }
    }
    return html;
};

POP.YouTubeViewerType.Default.prototype.view = function (obj, callback, callbackParams, ctx) {
    var html = '',
	tempObj, data, listItems;

    data = this.model(obj);
    if (!data) { return; }

    tempObj = obj.clone();

    html += '<div class="clear"></div>';
    html += '<div class="video-container">';
    html += '	<div class="video-wrapper">';
    html += '		<div class="video-assets">';
    html += data;
    html += '		</div>';
    html += '	</div>';
    html += '	<div class="video-thumbs"></div>';
    html += '</div>';
    html += '<div class="clear"></div>';

    html = $(html);
    //if there are more than 1 videos add the thumbs
    listItems = tempObj.find('li');
    if (listItems.length < 2) {
        listItems.first().addClass('hidden');
    }
    html.find('.video-thumbs').append(tempObj).append('<div class="clear"></div>');
    obj.replaceWith(html);

    if (typeof callback === 'function') {
        var ctx = ctx || this;
        callback.apply(ctx, [html, callbackParams]);
    }
};


