﻿/// <reference path='jquery-1.6.2.min.js' />
/// <reference path='swfobject.js' />
/// <reference path='date-pt-BR.js' />
/*
* M3Lib
* (c) 2011-2012 Marvin Martins Mendes <marvin_mendes@yahoo.com.br>
* 
* M3MTube is distributed under the MIT License
* Read more about the MIT License --> http://www.opensource.org/licenses/mit-license.php
*
* jQuery 1.4.* or higher required
*
*/


/*
* - SimpleModal -
*
* Description: show a modal dialog on the screen very simple.
*/
jQuery.fn.simpleModal = function (settings) {
    var options = {
        maskSpeed: "fast",
        dialogSpeed: "fast",
        showAfterMask: true,
        beforeshow: function () { },
        onshow: function () { },
        onclose: function () { }
    }

    options = $.extend(options, settings);

    var $this = $(this);
    var mask = $this.find(".modal-mask");
    var dialog = $this.find(".dialog");

    if (options.beforeshow) {
        options.beforeshow();
    }

    mask.fadeIn(options.maskSpeed, function () {
        if (options.showAfterMask) {
            dialog.fadeIn(options.dialogSpeed);
        }
    });
    if (!options.showAfterMask) {        
        dialog.fadeIn(options.dialogSpeed);
    }

    if (options.onshow) {
        options.onshow();
    }

    $this.find(".close").click(function (e) {
        e.preventDefault();
        mask.hide();
        dialog.hide();
        if (options.onclose) {
            options.onclose();
        }
    });

    mask.click(function (e) {
        e.preventDefault();
        mask.hide();
        dialog.hide();
        if (options.onclose) {
            options.onclose();
        }
    });
}

/*
*
* YouTube Library
*/

var ytUtility = {
    getVideo: function (item, dateFormat, imageLink, titleLink) {
        var uploadDate = ytUtility.getDate(item.uploaded); //Date.parse(item.uploaded, "yyyy-MM-ddTHH:mm:sssZ");
        var tit = item.title;

        var simg = '<img src="' + item.thumbnail.sqDefault + '" title="' + item.title + '" alt="' + item.title + '" />';
        var limg = '<img src="' + item.thumbnail.hqDefault + '" title="' + item.title + '" alt="' + item.title + '" />';

        if (imageLink != 'undefined' && imageLink) {
            simg = '<a href="#" class="video-link" rel="' + item.id + '" >' + simg + '</a>';
            limg = '<a href="#" class="video-link" rel="' + item.id + '" >' + limg + '</a>';
            if (titleLink) {
                tit = '<a href="#" class="video-link">' + item.title + '</a>';
            }
        }
        var video = {
            id: item.id,
            title: tit,
            viewCount: item.viewCount,
            duration: ytUtility.secondsToTime(item.duration),
            commentCount: item.commentCount,
            smallImage: simg,
            largeImage: limg,
            uploaded: (uploadDate) ? uploadDate.toString(dateFormat) : uploadDate,
            playerLink: item.player['default'] //cannot access item.player.default directly
        }
        return video;
    },
    getFeed: function (settings, callback) {
        var opt = {
            ytListMode: "playlists", //[ "playlists" || "users" || videos ]
            ytListId: "", //param from mode. Case users, the username of the item
            ytListOption: "", //param after listmode
            ytMaxResults: 25,
            ytStartIndex: 1,
            ytOrderby: "published", //[ "published" || "relevance" || "viewCount" || "rating" ]
            ytUrlParams: "",
            dateFormat: "dd/MM/yyyy",
            imageLink: false,
            titleLink: false
        }
        opt = jQuery.extend(opt, settings);

        var processData = function (data, fromUser) {
            var videos = [];
            if (typeof data.data != 'undefined' && data.data.items != 'undefined') {
                jQuery.each(data.data.items, function (index, value) {
                    var v = 0;
                    if (fromUser) {
                        v = ytUtility.getVideo(value, opt.dateFormat, opt.imageLink, opt.titleLink);
                    } else {
                        v = ytUtility.getVideo(value.video, opt.dateFormat, opt.imageLink, opt.titleLink);
                    }
                    videos.push(v);

                });
                return videos;
            }
        }

        var urlFeed = ["http://gdata.youtube.com/feeds/api/"];
        urlFeed.push(opt.ytListMode + "/");
        urlFeed.push(opt.ytListId);
        urlFeed.push(opt.ytListOption);
        //Data format and version
        urlFeed.push("?v=2&alt=jsonc&key=AI39si53Sfj4mX5DHDyRbuLHKLU1kDZ5b2uKiG5dgnQGcLTnOeCQj12wNq7lQHKnO4gmzRoselCU5bKlNMVa_XrY-YE0YuteVw");
        if (opt.ytMaxResults) urlFeed.push("&max-results=" + opt.ytMaxResults);
        if (opt.ytStartIndex) urlFeed.push("&start-index=" + opt.ytStartIndex);
        if (opt.ytOrderby) urlFeed.push("&orderby=" + opt.ytOrderby);
        urlFeed.push(opt.ytUrlParams);
        urlFeed.push("&callback=?");

        jQuery.getJSON(urlFeed.join(""), function (data) {
            var videos = [];
            if (data == 'undefined') return;
            if (opt.ytListMode == "playlists") {
                videos = processData(data, false);
            } else if (opt.ytListMode == "users") {
                videos = processData(data, true);
            } else if (typeof data.data != 'undefined') {
                videos = data.data;
            }
            if (callback) {
                callback(videos);
            }
        });

    },
    template: function (template, info) {
        if (typeof template === "string") {
            var result = template;
            for (var key in info) {
                var val = info[key];
                result = result.replace(new RegExp('{' + key + '}', 'g'), val === null ? '' : val);
            }
            return result;
        } else return template(info);
    },
    /**
    * Convert number of seconds into time object
    *
    * @param integer secs Number of seconds to convert
    * @return object
    */
    secondsToTime: function (secs) {
        var minutes = Math.floor(secs / 60);
        var divisor_for_minutes = secs % (60 * 60);
        var divisor_for_seconds = divisor_for_minutes % 60;
        var seconds = Math.ceil(divisor_for_seconds);
        return minutes + ":" + ytUtility.pad(seconds);
    },

    getDate: function (dt) {
        q = new String(dt);
        // string version
        s = q.substring(8, 10) + "." + q.substring(5, 7) + "." + q.substring(0, 4) + " " + q.substring(11, 16)
        // date version
        d = new Date(Date.UTC(parseInt(q.substring(0, 4)), parseInt(q.substring(5, 7)), parseInt(q.substring(8, 10)), parseInt(q.substring(11, 13)), parseInt(q.substring(14, 16))))
        return d;
    },

    pad: function (val, len) {
        val = String(val);
        len = len || 2;
        while (val.length < len) val = "0" + val;
        return val;
    }
}

jQuery.fn.ytPlayer = function (settings) {
    var opt = {
        id: 0,
        playerWidth: "640",
        playerHeight: "390",
        playerUrlParams: "playerMode=normal&autoplay=0&fs=1", // additional information pass trhow YouTube url
        useSwfobject: false,
        playerParams: { allowScriptAccess: "always", allowfullscreen: "true" }
    }
    opt = jQuery.extend(opt, settings);
    if (opt.id) {
        if (opt.useSwfobject) {
            var url = ["http://www.youtube.com/v/"];
            url.push(opt.id);
            if (opt.playerUrlParams) {
                url.push("?" + opt.playerUrlParams);
            }
            $(this).html("<div id='" + $(this).attr("id") + "-video-holder" + "'></div>");
            var atts = { id: $(this).attr("id") + "-video" };
            swfobject.embedSWF(url.join(""), $(this).attr("id") + "-video-holder", opt.playerWidth, opt.playerHeight, "8", null, null, opt.playerParams, atts);
        } else {
            var url = ["http://www.youtube.com/embed/"];
            url.push(opt.id);
            if (opt.playerUrlParams) {
                url.push("?" + opt.playerUrlParams);
            }
            var $videoFrame = $("<iframe></iframe>");
            $videoFrame.attr("frameborder", "0");
            $videoFrame.attr("width", opt.playerWidth);
            $videoFrame.attr("height", opt.playerHeight);
            $videoFrame.attr("src", url.join(""));

            $(this).html($videoFrame);
        }
    }
    return $(this);
}

jQuery.fn.ytListVideo = function (settings) {
    var opt = {
        playerHolder: null, //placeholder for the player
        playerWidth: "640",
        playerHeight: "390",
        playerParams: { allowScriptAccess: "always", allowfullscreen: "true" },
        playerUrlParams: "playerMode=normal&autoplay=0&fs=1",
        ytListMode: "playlists", //[ "playlists" || "users" || videos ]
        ytListId: "", //param from mode. Case users, the username of the item
        ytListOption: "", //param after listmode
        ytMaxResults: 25, // 0 or null to hide
        ytStartIndex: 1, // 0 or null to hide
        ytOrderby: "published", //[ "published" || "relevance" || "viewCount" || "rating" ]
        ytUrlParams: "",
        dateFormat: "dd/MM/yyyy",
        titleLink: false,
        groupTemplate: "<ul>{0}</ul>",
        groupCount: 0, //repeat a group item when reach this value. 0 to never repeat
        //Fields in item template
        //can be a function: see ytUtility.getVideo
        //{id}, {title}, {viewCount}, {duration}, {commentCount}, {smallImage}, {largeImage}, {uploaded}
        itemTemplate: "<li><div>{smallImage}</div><div>{title}</div></li>",
        callback: function (videos) { },
        onclick: function (e, v) { }, // function (e, v) => e : event object v: video or video id
        videoIdOnClick: true // return video or video's id on click
    }
    opt = jQuery.extend(opt, settings);
    var $this = $(this);
    var $player = 0;
    if (opt.playerHolder) {
        $player = $(opt.playerHolder);
    }

    var processData = function (data, fromUser) {
        var videos = [];
        if (typeof data.data != 'undefined' && data.data.items != 'undefined') {
            var lines = [];
            var groups = [];
            var gc = 1; //group count
            var reachIndex = 0;

            jQuery.each(data.data.items, function (index, value) {

                var v = 0;
                if (fromUser) {
                    v = ytUtility.getVideo(value, opt.dateFormat, $player, opt.titleLink);
                } else {
                    v = ytUtility.getVideo(value.video, opt.dateFormat, $player, opt.titleLink);
                }
                if (typeof opt.itemTemplate !== 'function') {
                    lines.push(ytUtility.template(opt.itemTemplate, v));
                } else {
                    lines.push(ytUtility.template(opt.itemTemplate(index, v), v));
                }

                videos.push(v);
                //new group
                if (opt.groupCount > 0 && gc >= opt.groupCount) {
                    var gp = opt.groupTemplate.replace(/\{0\}/g, lines.join('\r\n'));
                    groups.push(gp);
                    gc = 0;
                    lines = [];
                }
                gc++;
            });

            if (lines.length > 0) {
                var gp = opt.groupTemplate.replace(/\{0\}/g, lines.join('\r\n'));
                groups.push(gp);
            }

            $this.append(groups.join('\r\n'));

            return videos;
        }
    }

    var linkInitialize = function () {
        if ($player) {
            $(".video-link").click(function (e) {
                e.preventDefault();
                var vid = $(this).attr("rel");
                $player.ytPlayer({
                    id: vid,
                    playerWidth: opt.playerWidth,
                    playerHeight: opt.playerHeight,
                    playerParams: opt.playerParams,
                    playerUrlParams: opt.playerUrlParams
                });
                if (opt.onclick) {
                    if (opt.videoIdOnClick) {
                        opt.onclick(e, vid);
                    } else {
                        ytUtility.getFeed({
                            ytListMode: "videos",
                            ytListId: vid,
                            ytListOption: "",
                            ytMaxResults: false,
                            ytStartIndex: false,
                            ytOrderby: false,
                            ytUrlParams: "",
                            dateFormat: "dd/MM/yyyy",
                            imageLink: false,
                            titleLink: false
                        }, function (data) {
                            opt.onclick(e, data);
                        });
                    }
                }
            });
        }
    }

    var urlFeed = ["http://gdata.youtube.com/feeds/api/"];
    urlFeed.push(opt.ytListMode + "/");
    urlFeed.push(opt.ytListId);
    urlFeed.push(opt.ytListOption);
    //data format and version
    //key registered by Marvin Mendes
    urlFeed.push("?v=2&alt=jsonc&key=AI39si53Sfj4mX5DHDyRbuLHKLU1kDZ5b2uKiG5dgnQGcLTnOeCQj12wNq7lQHKnO4gmzRoselCU5bKlNMVa_XrY-YE0YuteVw");
    urlFeed.push("&max-results=" + opt.ytMaxResults);
    urlFeed.push("&start-index=" + opt.ytStartIndex);
    urlFeed.push("&orderby=" + opt.ytOrderby);
    urlFeed.push(opt.ytUrlParams);
    urlFeed.push("&callback=?");

    jQuery.getJSON(urlFeed.join(""), function (data) {
        var videos = [];
        if (data == 'undefined') return;
        if (opt.ytListMode == "playlists") {
            videos = processData(data, false);
        } else if (opt.ytListMode == "users") {
            videos = processData(data, true);
        }
        linkInitialize();
        if (opt.callback) {
            opt.callback(videos);
        }
    });

    return $this;
}
