﻿/// <reference path="../jquery-1.4.4-vsdoc.js" />

var zoomHelper = {
    maxWidth: 0,
    maxHeight: 0,
    items: null,
    currentItemIndex: 0,
    mediaType: "",
    $zoomContainer: null,
    $logoIcon: null,
    $logoText: null,
    $zoomClose: null,
    $logoVisit: null,
    $zoomVideoContainer: null,
    $zoomVideoFrame: null,
    $zoomPhotoContainer: null,
    $zoomPrev: null,
    $loadingIndicator: null,
    initHeader: function (zoomContainerId, logoIconId, logoTextId, zoomCloseId, logoVisitId, onHide) {
        this.$zoomContainer = $("#" + zoomContainerId);
        this.$logoIcon = $("#" + logoIconId);
        this.$logoText = $("#" + logoTextId);
        this.$zoomClose = $("#" + zoomCloseId).click(function () {
            zoomHelper.$loadingIndicator.hide();
            zoomHelper.$zoomVideoContainer.hide();
            zoomHelper.$zoomPhotoContainer.hide();
            zoomHelper.$zoomContainer.hide();
            zoomHelper.$zoomVideoFrame.attr("src", "none");

            if (onHide !== undefined && typeof onHide == "function") {
                onHide();
            }
        });
        this.$logoVisit = $("#" + logoVisitId);

    },
    initOther: function (zoomVideoId, zoomPhotoId, zoomPrevId, zoomNextId, loadingIndicatorId) {
        var zvc = this.$zoomVideoContainer = $("#" + zoomVideoId);
        this.$zoomVideoFrame = $("iframe", zvc);
        var zpc = this.$zoomPhotoContainer = $("#" + zoomPhotoId);
        var padding = 0.98;
        this.maxWidth = zpc.parent().parent().parent().width() * padding;
        this.maxHeight = zpc.parent().height() * padding;
        var _this = this;

        var detectPressKitMediaType = function (src) {
            if (src == null || src == '' || src.indexOf('/Areas/Dashboard/Views/Shared/Controls/Upload/') >= 0) {
                return -1; //resume or undefined
            }

            if ((/\.*youtube.com/i).test(src) || (/vimeo.com/i).test(src)) {
                return 0;
            } else {
                return 1;
            }
        };

        this.$zoomPrev = $("#" + zoomPrevId).click(function () {
            var prevIndex = _this.currentItemIndex;
            var index = prevIndex - 1;
            if (index < 0) index = _this.items.length - 1;

            if (_this.mediaType === "presskit") {
                var prevType = detectPressKitMediaType(_this.items[prevIndex].src);
                while (prevType != detectPressKitMediaType(_this.items[index].src)) {
                    index--;
                    if (index < 0) {
                        index = _this.items.length - 1;
                    }
                }

                if (_this.currentItemIndex == index) {
                    return; // one item
                }
            }

            _this.currentItemIndex = index;
            _this.showItem();
        });

        this.$zoomNext = $("#" + zoomNextId).click(function () {
            var prevIndex = _this.currentItemIndex;
            var index = prevIndex + 1;
            if (index > _this.items.length - 1) index = 0;

            if (_this.mediaType === "presskit") {
                var prevType = detectPressKitMediaType(_this.items[prevIndex].src);
                while (prevType != detectPressKitMediaType(_this.items[index].src)) {
                    index++;
                    if (index > _this.items.length - 1) {
                        index = 0;
                    }
                }

                if (_this.currentItemIndex == index) {
                    return; // one item
                }
            }

            _this.currentItemIndex = index;
            _this.showItem();
        });
        this.$loadingIndicator = $("#" + loadingIndicatorId);
    },
    init: function (logoIconSrc, logoText, logoVisitHref, logoVisitText) {
        this.$logoIcon.attr("src", logoIconSrc);
        this.$logoText.html(logoText);
        this.$logoVisit.attr("href", logoVisitHref).html(logoVisitText);
    },
    showItem: function () {
        if (!this.items || this.items.length < 1 || this.mediaType == "") return;
        zoomHelper.$zoomVideoContainer.hide();
        zoomHelper.$zoomPhotoContainer.hide();
        var lind = this.$loadingIndicator.show();
        var $photoImage, _this = this;


        var mediaOnLoadPhoto = function () {
            var width, height, scale, left, top;
            var setToCenter = function (container) {
                container.css({ "left": left, "top": top });
            };
            lind.hide();

            width = $photoImage.width();
            height = $photoImage.height();
            _this.$zoomPhotoContainer.html($photoImage);
            setToCenter(_this.$zoomPhotoContainer);
            zoomHelper.$zoomPhotoContainer.show();
        };

        var mediaOnLoadVideo = function () {
            var width, height, scale, left, top;
            var setToCenter = function (container) {
                container.css({ "left": left, "top": top });
            };
            lind.hide();

            width = _this.$zoomVideoFrame.attr("width");
            height = _this.$zoomVideoFrame.attr("height");
            setToCenter(_this.$zoomVideoContainer);
            zoomHelper.$zoomVideoContainer.show();
        };

        var src = this.items[this.currentItemIndex].id;
        if (this.mediaType === "photo") {
            $photoImage = $("<img />");
            $photoImage.load(mediaOnLoadPhoto);
            $photoImage.attr("src", src);
            var cap = '';
            if (this.items[this.currentItemIndex].hasAttribute('data-caption')) {
                cap = this.items[this.currentItemIndex].getAttribute('data-caption');
                if (cap)
                    if (cap.length > 150)
                        cap = cap.substr(0, 150) + '...';
                $('.zoom-caption').html(cap);
            }
            if (this.items[this.currentItemIndex].hasAttribute('data-copyright')) {
                cap = this.items[this.currentItemIndex].getAttribute('data-copyright');
                if (cap)
                    if (cap.length > 150)
                        cap = cap.substr(0, 150) + '...';
                $('.zoom-copyright').html(cap);
            }
        }
        else if (this.mediaType === "youtube") {
            this.$zoomVideoFrame.load(mediaOnLoadVideo);
            src = 'http://www.youtube.com/embed/' + src;
            this.$zoomVideoFrame.attr("src", src);
        }
        else if (this.mediaType === "vimeo") {
            this.$zoomVideoFrame.load(mediaOnLoadVideo);
            src = 'http://player.vimeo.com/video/' + src;
            this.$zoomVideoFrame.attr("src", src);
        }
        else if (this.mediaType === "presskit") {
            if ((/\.*youtube.com/i).test(src)) {
                this.$zoomVideoFrame.load(mediaOnLoadVideo);
                var yIds = /\?v=([a-z0-9\-_]+)\&?/i;
                var yId = yIds.exec(src)[1];
                src = 'http://www.youtube.com/embed/' + yId;
                this.$zoomVideoFrame.attr("src", src);
            } else if ((/vimeo.com/i).test(src)) {
                this.$zoomVideoFrame.load(mediaOnLoadVideo);
                var vIds = /.*vimeo.com\/([a-z0-9\-_]+)/i;
                var vId = vIds.exec(src)[1];
                src = 'http://player.vimeo.com/video/' + vId;
                this.$zoomVideoFrame.attr("src", src);
            } else {
                $photoImage = $("<img />");
                $photoImage.load(mediaOnLoadPhoto);
                $photoImage.attr("src", src);
            }

        } else return;

        this.$zoomContainer.show();
    },
    apply: function (items, photoSrc, youtubeSrc, vimeoSrc, presskitSrc, onShow) {
        $('.zoom-caption').html('');
        $('.zoom-copyright').html('');
        this.items = items;
        var index, src;
        if (photoSrc && photoSrc !== "") {
            this.mediaType = "photo";
            src = photoSrc;
        } else if (youtubeSrc && youtubeSrc !== "") {
            this.mediaType = "youtube";
            src = youtubeSrc;
        } else if (vimeoSrc && vimeoSrc !== "") {
            this.mediaType = "vimeo";
            src = vimeoSrc;
        } else if (presskitSrc && presskitSrc !== "") {
            this.mediaType = "presskit";
            src = presskitSrc;
        }

        $.grep(items, function (v, i) {
            var result = (v.id === src);
            if (result) index = i;
            return result;
        });
        this.currentItemIndex = index;
        this.showItem();

        if (onShow !== undefined && typeof onShow == "function") {
            onShow();
        }
    }
};

var ThumbnailsModel = function (thumbnailSrc, zoomSrc, title) {
    this.thsrc = thumbnailSrc;
    this.zsrc = zoomSrc;
    this.title = title;
};

var feedHelpers = {
    flickr: {
        loadData: function (source, url /* or feedId */, responseHandler) {
            if (source === "server") {
                $.ajax({
                    url: "/website/feeds/flickr/" + url,
                    type: 'POST',
                    success: function (result) {
                        var data = [];
                        $.each(result, function (i, v) {
                            data[data.length] = new ThumbnailsModel(v.ThumbnailSrc, v.ZoomSrc, v.Title);
                        });
                        responseHandler(data);
                    }
                });
            } else {     // google
                var feed = new google.feeds.Feed(url);
                feed.includeHistoricalEntries();
                feed.setNumEntries(100);
                feed.setResultFormat(google.feeds.Feed.JSON_FORMAT);
                feed.load(function (result) {
                    var thumbnailSrc, zoomSrc, data = [];
                    $.each(result.feed.entries, function (i, v) {
                        if (!v.content) return;
                        thumbnailSrc = $('img', $(v.content)).attr('src');
                        var ids = /([a-z0-9\/.:]+_[a-z0-9]+)_m(.jpg|jpeg|png)\&?/i;
                        var groups = ids.exec(thumbnailSrc);
                        zoomSrc = groups[1] + groups[2];
                        data[data.length] = new ThumbnailsModel(thumbnailSrc, zoomSrc, v.title);
                    });
                    responseHandler(data);
                });
            }
        }
    },
    youtube: {
        loadData: function (source, url, responseHandler) {
            var feed = new google.feeds.Feed(url);
            feed.includeHistoricalEntries();
            feed.setNumEntries(100);
            feed.setResultFormat(google.feeds.Feed.JSON_FORMAT);
            feed.load(function (result) {
                var thumbnailSrc, zoomSrc, data = [];
                $.each(result.feed.entries, function (i, v) {
                    if (!v.content) return;
                    thumbnailSrc = $('img', $(v.content)).attr('src');
                    var ids = /\?v=([a-z0-9\-_]+)\&?/i;
                    zoomSrc = ids.exec(v.link)[1];
                    data[data.length] = new ThumbnailsModel(thumbnailSrc, zoomSrc, v.title);
                });
                responseHandler(data);
            });
        }
    },
    vimeo: {
        loadData: function (source, url, responseHandler) {
            var feed = new google.feeds.Feed(url);
            feed.includeHistoricalEntries();
            feed.setNumEntries(100);
            feed.setResultFormat(google.feeds.Feed.JSON_FORMAT);
            feed.load(function (result) {
                var thumbnailSrc, zoomSrc, data = [];
                $.each(result.feed.entries, function (i, v) {
                    if (!v.content) return;
                    thumbnailSrc = $('img', $(v.content)).attr('src');
                    var ids = /([0-9]+)/;
                    zoomSrc = ids.exec(v.link)[0];
                    data[data.length] = new ThumbnailsModel(thumbnailSrc, zoomSrc, v.title);
                });
                responseHandler(data);
            });
        }
    },
    manager: {
        player: null,
        feeds: [],
        initMediaplayer: function (containerId, width, height) {
            if (this.player == null) {
                this.player = new Mediaplayer();
                this.player.create(containerId, width, height);
            }
        },
        onFeedButtonClick: function (index) {
            if (this.player == null) return;
            this.player.reset();
            var feed = this.feeds[index];
            if (feed) feed.resetPlaylist();
        },
        onFeedClose: function () {
            if (this.player != null) {
                this.player.reset();
            }
        }
    }
};

function BandcampFeed() {
    this.bandTemplateId = null;
    this.smallAlbumTemplateId = null;
    this.bigAlbumTemplateId = null;
    this.trackAlbumTemplateId = null;
    this.albums = null;
    this.$bigAlbumHtml = null;
    this.$albumThumbnails = null;
}
BandcampFeed.prototype = {
    initTemplate: function (bandTemplateId, smallAlbumTemplateId, bigAlbumTemplateId, trackAlbumTemplateId) {
        this.bandTemplateId = "#" + bandTemplateId;
        this.smallAlbumTemplateId = "#" + smallAlbumTemplateId;
        this.bigAlbumTemplateId = "#" + bigAlbumTemplateId;
        this.trackAlbumTemplateId = "#" + trackAlbumTemplateId;
    },
    initVisit: function (url, $visits) {
        var prefix = "http://";
        var index = url.indexOf(prefix);
        if (index < 0) url = prefix + url;
        $visits.attr("href", url);
    },
    create: function (feedId, index, $feedResult) {
        feedHelpers.manager.feeds[index] = this;
        var _this = this;
        var onThumbnailClick = function () {
            var player = feedHelpers.manager.player;
            player.reset();
            var albumIndex = $(this).attr("num");
            albumIndex = Number(albumIndex);
            if (_this.$bigAlbumHtml) _this.$bigAlbumHtml.remove();
            _this.$bigAlbumHtml = $(_this.bigAlbumTemplateId).tmpl(_this.albums[albumIndex]);
            var tracks = _this.albums[albumIndex].Tracks;
            $.each(tracks, function (i, v) { v.index = i; v.provider = "sound"; });
            var $tracksHtml = $(_this.trackAlbumTemplateId).tmpl(tracks);
            $($tracksHtml[$tracksHtml.length - 1]).css("borderBottom", "1px solid #666");
            $("div.playlist", _this.$bigAlbumHtml).html($tracksHtml);
            $feedResult.append(_this.$bigAlbumHtml); //.css("height", "auto");
            player.loadPlaylist(tracks, $tracksHtml);
        };
        var responseHandler = function (data) {
            if (!data) {
                data = { BandName: "", Albums: [] };
            }
            _this.albums = data.Albums;
            $.each(_this.albums, function (i, v) { v.index = i; });
            var $bandHtml = $(_this.bandTemplateId).tmpl(data);
            var $albumsHtml = $(_this.smallAlbumTemplateId).tmpl(_this.albums);
            $("div.albums", $bandHtml).prepend($albumsHtml);
            $feedResult.html($bandHtml);
            var $discography = $(".discography", $bandHtml);
            _this.$albumThumbnails = $(".small_album", $bandHtml).click(onThumbnailClick);
            if (_this.$albumThumbnails.length > 0) $(_this.$albumThumbnails[0]).click();

            function handleSliderSlide(e, ui) {
                var maxScroll = $discography.attr("scrollWidth") - $discography.width();
                $discography.attr({ scrollLeft: ui.value * (maxScroll / 100) });
            }

            $(".slider", $bandHtml).slider({
                animate: true,
                change: handleSliderSlide,
                slide: handleSliderSlide
            });
        };
        $.ajax({
            url: "/website/feeds/bandcamp/" + feedId,
            type: 'POST',
            success: responseHandler
        });
    },
    resetPlaylist: function () {
        if (this.$bigAlbumHtml) this.$bigAlbumHtml.remove();
        if (this.$albumThumbnails != null && this.$albumThumbnails.length > 0) $(this.$albumThumbnails[0]).click();
    }
};

function SoundcloudFeed() {
    this.bandTemplateId = null;
    this.trackAlbumTemplateId = null;
    this.$visits = null;
    this.data = null;
    this.$feedResult = null;
}
SoundcloudFeed.prototype = {
    initTemplate: function (bandTemplateId, trackAlbumTemplateId) {
        this.bandTemplateId = "#" + bandTemplateId;
        this.trackAlbumTemplateId = "#" + trackAlbumTemplateId;
    },
    initVisit: function ($visits) {
        this.$visits = $visits;
    },
    create: function (feedId, index, $feedResult) {
        this.$feedResult = $feedResult;
        feedHelpers.manager.feeds[index] = this;
        var _this = this;
        var responseHandler = function (data) {
            if (!data) {
                data = { BandName: "", BandUrl: "http://soundcloud.com", Tracks: [] };
            }
            _this.$visits.attr("href", data.BandUrl);
            _this.data = data;
            $.each(data.Tracks, function (i, v) { v.index = i; v.provider = "sound"; });
        };
        $.ajax({
            url: "/website/feeds/soundcloud/" + feedId,
            type: 'POST',
            success: responseHandler
        });
    },
    resetPlaylist: function () {
        var player = feedHelpers.manager.player;
        player.reset();
        if (this.data != null && this.data.Tracks != null) {
            var $tracksHtml = $(this.trackAlbumTemplateId).tmpl(this.data.Tracks);
            $($tracksHtml[$tracksHtml.length - 1]).css("borderBottom", "1px solid silver");
            var $bandHtml = $(this.bandTemplateId).tmpl(this.data);
            $("div.playlist", $bandHtml).html($tracksHtml);
            this.$feedResult.html($bandHtml).css("height", "auto");
            player.loadPlaylist(this.data.Tracks, $tracksHtml);
        }
    }
};
