﻿var playerRef;
function YoutubePlayer(opts) {
    // required, verify
    if (opts.playerId) { this.playerId = opts.playerId; } else { throw "MissingArgumentException"; }
    if (opts.videoHeight) { this.videoHeight = opts.videoHeight; } else { throw "MissingArgumentException"; }
    if (opts.videoWidth) { this.videoWidth = opts.videoWidth; } else { throw "MissingArgumentException"; }

    // optional, don't verify
    if (opts.controlId) { this.controlId = opts.controlId; }
    if (opts.sliderId) { this.sliderId = opts.sliderId; }
    if (opts.timerId) { this.timerId = opts.timerId; }
    if (opts.descriptionId) { this.descriptionId = opts.descriptionId; }
    if (opts.shareId) { this.shareId = opts.shareId; }
    if (opts.infoId) { this.infoId = opts.infoId; }
    if (opts.relatedVideoId) { this.relatedVideoId = opts.relatedVideoId; }
    if (opts.viewcountId) { this.viewcountId = opts.viewcountId; }

    this.playerUrl = "http://www.youtube.com/v/"
    this.playerUrlQueryString = "?enablejsapi=1&fs=1&iv_load_policy&rel=0&showinfo=0&showsearch=0";

    this.player;
    this.control;
    this.slider;
    this.timer;
    this.intervalId;
    this.videoTotalTime;
    this.videoId;

    playerRef = this;
}

YoutubePlayer.prototype.initPlayer = function(videoId) {
    if (!this.initialized) {
        this.initialized = true;
        this.videoId = videoId;
        var params = { allowScriptAccess: 'always', wmode: 'transparent', allowFullScreen: 'true' };
        var atts = { id: this.playerId };
        swfobject.embedSWF(this.playerUrl + videoId + this.playerUrlQueryString, this.playerId, this.videoWidth, this.videoHeight, "8", null, null, params, atts);

        if (this.sliderId) {
            this.slider = $('#' + this.sliderId);

            var caller = this;
            this.slider.slider({
                change: function(event, ui) {
                    if (event.originalEvent) {
                        caller.player.seekTo(ui.value, true);
                        caller.playVideo();
                    }
                },
                slide: function(event, ui) {
                    caller.pauseVideo();
                }
            });
            this.slider.progressbar();
        }
        if (this.controlId) { this.control = $('#' + this.controlId); }
        if (this.timerId) { this.timer = $('#' + this.timerId); }
    } else {
        this.loadVideo(videoId);
    }
}

YoutubePlayer.prototype.loadVideo = function(videoId) {
    // this breaks if you use jquery!
    if (videoId && videoId != '') { this.videoId = videoId; }
    this.player = swfobject.getObjectById(this.playerId);
    
	if ( this.player != null && this.player.cueVideoById != null ) {
		//this.player.stopVideo();
		this.player.cueVideoById(this.videoId);
	}

    var caller = this;
    var json_str = 'http://gdata.youtube.com/feeds/api/videos/' + this.videoId + '?v=2&alt=jsonc';

    $.ajax({
        type: "GET",
        url: json_str,
        dataType: "jsonp",
        success: function(result) {
            //if (result) {

            var data = result.data;
            var duration = timeToString(data.duration) + ' mins';

            if (caller.descriptionId) { $('#' + caller.descriptionId).html(data.description); }
            if (caller.viewcountId) { $('#' + caller.viewcountId).html(data.viewCount); }
            if (caller.infoId) {
                var info = $('#' + caller.infoId);
                info.html('<span class="title">' + data.title + '</span><span class="time">' + duration + '</span><span class="time">' + data.viewCount + ' Views</span>');
            }
            if (caller.shareId) {
                var share = $('#' + caller.shareId);
                share.append('<div id="shareVideo" class="addthis_toolbox share_btn_fb"><a class="addthis_button_email"></a><a class="addthis_button_twitter"></a><a class="addthis_button_facebook"></a></div>');
                addthis.toolbox('#shareVideo', {}, { url: 'http://www.youtube.com/v/' + data.id, title: data.title });
            }

            if (caller.slider) {
                caller.slider.slider('option', 'max', data.duration);
                caller.slider.slider('option', 'value', 0);
                caller.slider.progressbar('option', 'value', 0);
            }
            caller.videoTotalTime = data.duration;
            caller.relatedVideoSearch(caller, data.title);
            caller.playVideo();
        }
    });
    return false;
}

YoutubePlayer.prototype.playVideo = function() {
    if (this.player && this.player.playVideo) {
        if (this.control) {
            this.control.unbind('click', playVideo);
            this.control.bind('click', pauseVideo);
            $('#' + this.controlId).css('backgroundPosition', '0px -36px');
        }
        this.player.playVideo();
        if (this.intervalId) { clearInterval(this.intervalId); }
        this.intervalId = setInterval(updateVideoStatus, 333);
    }
}

YoutubePlayer.prototype.pauseVideo = function() {
    if (this.player && this.player.pauseVideo) {
        this.player.pauseVideo();
        if (this.control) {
            this.control.unbind('click', pauseVideo);
            this.control.bind('click', playVideo);
            $('#' + this.controlId).css('backgroundPosition', '0px 0px');
        }
        if (this.intervalId) { clearInterval(this.intervalId); }
        this.intervalId = null;
    }
}

YoutubePlayer.prototype.stopVideo = function() {
    if (this.player && this.player.stopVideo) {
        this.player.stopVideo();
        if (this.intervalId) { clearInterval(this.intervalId); }
        this.intervalId = null;
        if (this.control) {
            $('#' + this.controlId).css('backgroundPosition', '0px 0px');
        }
    }
}

YoutubePlayer.prototype.relatedVideoSearch = function(title) {
    var caller = this;
    if (this.relatedVideoId) {
		var json_str = 'http://gdata.youtube.com/feeds/api/videos?q=' + encodeURI(title) + '&orderby=published&max-results=4&author=NittoChannel&v=2&alt=jsonc';
		$.ajax ({
			type: "GET",
			url: json_str,
			dataType: "jsonp",
			success: function (result) {
				//$.getJSON('http://gdata.youtube.com/feeds/api/videos?q=' + encodeURI(title) + '&orderby=published&max-results=4&author=NittoChannel&v=2&alt=jsonc', function(result) {
				//if (result && result.data) {
                var data = result.data.items;
                var slides = '<div>';
                for (i = 0; i < data.length; i++) {
                    slides += '<img class="video_clip" src="' + data[i].thumbnail.sqDefault + '" onclick="javascript:loadVideo(\'' + data[i].id + '\')" />';
                }
                slides += '</div>';
                $('#' + caller.relatedVideoId).html(slides);
            }
        });
    }
}

function timeToString(time) {
    var seconds = time % 60;
    var minutes = (time - seconds) / 60;
    var placeholder = '';
    if (seconds < 10) {
        placeholder = '0';
    }
    var duration = minutes + ':' + placeholder + seconds;
    return duration;
}

function updateVideoStatus() {
    var state = 0;

    if (playerRef.player.getPlayerState) {
        state = playerRef.player.getPlayerState();
    }

    // -1 = unstarted
    // 1 = playing
    if (state == 0 || state == 2) {
        if (playerRef.intervalId) {
            clearInterval(playerRef.intervalId);
            playerRef.intervalId = null;
        }
    } else if (playerRef.slider) {
        var time = playerRef.player.getCurrentTime();
        var bytesLoaded = playerRef.player.getVideoBytesLoaded();
        var startBytes = playerRef.player.getVideoStartBytes();
        var totalBytes = playerRef.player.getVideoBytesTotal();
        var startSecond = Math.round((startBytes / totalBytes) * playerRef.videoTotalTime);
        var loadedSecond = Math.round(((startBytes + bytesLoaded) / totalBytes) * playerRef.videoTotalTime);
        var percentageLoaded = (loadedSecond / playerRef.videoTotalTime) * 100;
        playerRef.slider.slider('option', 'value', time);
        playerRef.slider.progressbar('option', 'value', percentageLoaded);
        playerRef.timer.html(timeToString(Math.round(time)));
    }
}
