﻿"use strict";

var gallery = {

    autoplay_tmr: null,

    big: false,

    bigClick: function (e) {
        e.stopImmediatePropagation();
        var ww = $(window).width();
        var x = (e.originalEvent.touches ? e.originalEvent.touches[0].clientX : e.clientX);
        var d = gallery.offset.down;
        if (d) {
            var l = Math.abs(d.x - e.pageX) + Math.abs(d.y - e.pageY);
            if (l > 20) { return false; }
        }
        if (x < ww * 0.15) {
            gallery.prev();
        }
        else if(x > ww * 0.85) {
            gallery.next();
        }
    },

    bigClose: function () {
        $('.gallery-dialog').stop(true, false).animate({ opacity: 0 }, 500, function () { $(this).hide(); $('.gallery-dialog .bigimage').html(''); });
        window.clearTimeout(gallery.autoplay_tmr);
        base.scrollShow();
        gallery.offset.w = 0;
        gallery.big = false;
        if (base.videoPlaying) {
            base.videoPlaying = false;
            if ((base.audio) && (base.audioPlaying == true)) {
                base.audioVolSet(1);
            }
        }
    },

    bigDown: function (e) {
        gallery.offset.down = { x: e.pageX, y: e.pageY };
    },

    bigOpen: function () {
        var g = $('.gallery-dialog');
        if (g.length == 0) {
            g = $('<div class="gallery-dialog fsize popin-container" hd-fsize="3"><div class="popin-close ion-close-circled"></div><div class="container" style="margin: 1em;"><div class="ion-ios-arrow-left arrow-left"></div><div class="ion-ios-arrow-right arrow-right"></div><div class="bigimage"></div><div class="dialog-text"></div></div></div>').appendTo(document.body).bind(base.clickevent, gallery.bigClose).contextmenu(base.nope);
            $('.popin-close', g).bind(base.clickevent, gallery.bigClose);
            $('.container', g).bind('dragstart', base.nope).bind(base.clickevent, gallery.bigClick).mousedown(gallery.bigDown);
        }
        $(g).stop(true, false).css({ opacity: 0 }).show().animate({ opacity: 1 }, 300);
        base.scrollHide();
        base.resizeFonts();
        gallery.big = true;
    },

	bigSize: function () {
		var iw = $('.gallery-dialog .container').width();
		var ih = $('.gallery-dialog .container').height() - (gallery.vars.tover == '1' ? 0 : $('.gallery-dialog .dialog-text').outerHeight(true));
		$('.gallery-dialog .bigimage').css({ width: iw, height: ih });

		$('.gallery-dialog .picbox').addClass('loadnow');
		base.picbox($('.gallery-dialog')); //recalc to re-center if needed
		$('.gallery-dialog .picbox').removeClass('loadnow');
		//base.picbox_resize($('.gallery-dialog'));

		if ($('.gallery-dialog .bigimage-offset').length) {
			$('.gallery-dialog .bigimage-offset img').css({ height: $('.gallery-dialog .bigimage-inner').height() });

			if ((gallery.offset.i) != undefined) {
				gallery.offset.cw = $(gallery.offset.i).width();
				gallery.offset.ch = $(gallery.offset.i).height();
			}
			gallery.offset.w = $('.gallery-dialog .bigimage-offset').width();
			gallery.offset.h = $('.gallery-dialog .bigimage-offset').height();
			if ((gallery.offset.w * gallery.offset.m) < gallery.offset.cw) {
				$('.gallery-dialog .bigimage-offset').css({ left: (gallery.offset.w - gallery.offset.cw) * -0.5 });
			}
		}
    },

    index: -1,

    init: function () {
        gallery.initMedia();
        if (gallery.vars.ihover == '1') {
            $('.gallery .item-inner').each(function (i, o) { gallery.itemOver.apply(o); });
        }
        else {
            $('.gallery .item-inner').mouseover(gallery.itemOver).mouseout(gallery.itemOut);
        }
        $('.gallery .item-inner').click(gallery.itemClick).contextmenu(base.nope);
        base.subscribe('keydown', gallery.keydown);
        base.subscribe('resize', gallery.resize);
        gallery.resize();
        gallery.updateOffset();
    },

    initMedia: function () {
        gallery.media = [];
        $('.gallery .content .item').each(function (i, o) {
            var pb = $('.picbox', o);
            gallery.media.push({ i: $(o).attr('hd-mid'), t: $(o).attr('hd-mediatype'), u: $(o).attr('hd-mediaurl'), n: $(o).attr('hd-medianame'), d: $(o).attr('hd-mediadesc'), a: $(o).attr('hd-mediamute'), m: $(pb).attr('hd-media'), x: $(pb).attr('hd-mediaext') });
        });
    },

    itemClick: function () {
        gallery.bigOpen();
        gallery.setMedia($(this).closest('.item').index());
    },

    itemOver: function () {
        $(this).find('.scene-name').stop(true, false).animate({ opacity: 1 }, 150);
    },

    itemOut: function () {
        $(this).find('.scene-name').stop(true, false).animate({ opacity: 0 }, 300);
    },

    keydown: function (k) {
        if (gallery.big) {
            if (k == 27) { gallery.bigClose(); }
            if (k == 37) { gallery.prev(); }
            if (k == 39) { gallery.next(); }
        }
    },

    magazineLayout: function (l, c, video, tall) {
        var b = [], bb = [];
        if (l <= c) {
            for (var a = 0; a < l; a++) {
                b[a] = { i: a, w: 1, h: 1, x: 0, y: a };
            }
            gallery.vars.rows = 1;
            return b;
        }
        if (c == 1) {
            for (var a = 0; a < l; a++) {
                b[a] = { i: a, w: 1, h: 1, x: a, y: 0 };
            }
            gallery.vars.rows = l;
            return b
        }
        var w = true;
        while (w) {
            var s = 0;
            for (var a = 0; a < l; a++) {
                b[a] = { i: a, w: 1 + Math.floor(Math.random() * 1.333), h: 1 + Math.floor(Math.random() * 1.333) };
                s += (b[a].w * b[a].h);
            }
            var r = s / c;
            w = (r != Math.floor(r));
            if (!w) {
                var g = [];
                var f = 0;
                for (var a = 0; a < r; a++) { g[a] = []; }
                for (var a = 0; a < l; a++) {
                    var p = false;
                    for (var x = 0; x <= r - b[a].h; x++) {
                        var xx = x + (b[a].h - 1);
                        for (var y = 0; y <= c - b[a].w; y++) {
                            var yy = y + (b[a].w - 1);
                            if (!g[x][y] && !g[xx][y] && !g[x][yy] && !g[xx][yy]) {
                                p = { x: x, y: y, xx: xx, yy: yy };
                                break;
                            }
                        }
                        if (p) { break; }
                    }
                    if (p) {
                        g[p.x][p.y] = true;
                        g[p.xx][p.y] = true;
                        g[p.x][p.yy] = true;
                        g[p.xx][p.yy] = true;
                        b[a].x = p.x;
                        b[a].y = p.y;
                        f++;
                    }
                }
                gallery.vars.rows = r;
                w = (l != f);
                if (!w) {
                    var m = [];
                    for (var a = 0; a < l; a++) {
                        if (b[a].w == 2 && b[a].h == 2 && video.length) {
                            m[a] = video[0];
                            video.splice(0, 1);
                        }
                        else if (b[a].w == 1 && b[a].h == 2 && tall.length) {
                            m[a] = tall[0];
                            tall.splice(0, 1);
                        }
                    }
                    var i = 0;
                    while ($.inArray(i, m) > -1) { i++; }
                    for (var a = 0; a < l; a++) {
                        if (m[a] === undefined) {
                            m[a] = i++;
                            while ($.inArray(i, m) > -1) { i++; }
                        }
                    }
                    for (var a = 0; a < l; a++) {
                        bb[m[a]] = b[a];
                    }
                }
            }
        }
        return bb;
    },

    media: [],

    mousemove: function (e) {
        var co = $(gallery.offset.i).offset();
        var x = (e.pageX - co.left) / gallery.offset.cw;
        var y = (e.offsetY - co.top) / gallery.offset.ch;
        if (x < 0.3) {
            gallery.offset.x = Math.pow(1 - (x / 0.3), 3) * -42;
        }
        else if (x > 0.7) {
            gallery.offset.x = Math.pow(1 - ((1 - x) / 0.3), 3) * 42;
        }
        else {
            gallery.offset.x = 0;
        }
    },

    mouseout: function (e) {
        gallery.offset.x = Math.sign(gallery.offset.x);
    },

    next: function () {
        if (gallery.index >= (gallery.media.length - 1)) {
            gallery.bigClose();
        }
        else {
            gallery.setMedia(gallery.index + 1);
        }
    },

    offset: { w: 0, h: 0 },

    prev: function () {
        if (gallery.index == 0) {
            gallery.bigClose();
        }
        else {
            gallery.setMedia(gallery.index - 1);
        }
    },

    resize: function () {
        window.clearTimeout(gallery.resize_tmr);
        gallery.resize_tmr = window.setTimeout(gallery.resize_ex, 200);
    },

    resize_tmr: null,

	resize_ex: function () {
        var cw = $('.gallery .content').width() - 2;
        var items = $('.gallery .content .item');
        var cols = Math.min(Math.ceil(cw / gallery.vars.imaxwidth), items.length);
        var iw = Math.floor(cw / cols);
        var ih = Math.floor((cw / cols) * 0.65);
        if (gallery.vars.layout != '2') {
            $('.gallery .content .item').css({ fontSize: iw * 0.08, width: iw, height: ih });
            gallery.vars.rows = Math.ceil(items.length / cols);
            if (gallery.vars.baserows && (gallery.vars.baserows < gallery.vars.rows) && (!gallery.vars.more)) {
                $('.gallery .content .item').each(function (i, o) {
                    if (i >= (gallery.vars.baserows * cols)) { $(o).addClass('more-hidden').hide(); } else { $(o).show(); }
                });
            }
        }
        else {
            ih = Math.floor((cw / cols) * 0.7);
            if (gallery.vars.lastiw != iw) {
                gallery.vars.lastiw = iw;
                var l;
                if (gallery.vars.lastcols == cols) {
                    l = gallery.vars.magazine;
                }
                else {
                    gallery.vars.lastcols = cols;
                    var v = [], t = [];
                    items.each(function (i, o) {
                        if ($(o).attr('hd-mediatype') == 6) {
                            v.push(i);
                        }
                        else {
                            var s = $(o).find('.picbox').attr('hd-media').split(',')[0].split(':');
                            if (parseInt(s[1]) < parseInt(s[2])) { t.push(i); }
                        }
                    });
                    l = gallery.vars.magazine = gallery.magazineLayout(items.length, cols, v, t);
                }
                $('.gallery .content').css({ position: 'relative', height: ih * gallery.vars.rows });
                var h = (gallery.vars.baserows && (gallery.vars.baserows < gallery.vars.rows) && (!gallery.vars.more));
                items.each(function (i, o) {
                    var oo = $(o).css({ fontSize: iw * 0.08, position: 'absolute', left: l[i].y * iw, top: l[i].x * ih, width: iw * l[i].w, height: ih * l[i].h }).removeClass('more-overlap');
                    if (h) {
                        if (l[i].x >= gallery.vars.baserows) { oo.addClass('more-hidden').hide(); } else { oo.show(); }
                        if ((l[i].x == (gallery.vars.baserows - 1)) && (l[i].h > 1)) { oo.addClass('more-overlap').attr('hd-overlapheight', ih * l[i].h).height(ih); }
                    }
                });
            }
        }
        gallery.vars.contentheight = ih * gallery.vars.rows;
        if (gallery.vars.baserows && (gallery.vars.baserows < gallery.vars.rows) && (!gallery.vars.more)) {
            $('.gallery .content').css({ height: ih * gallery.vars.baserows });
            $('.gallery .more').show();
        }
        else {
            $('.gallery .content').css({ height: ih * gallery.vars.rows });
        }
        gallery.bigSize();
        base.picbox_resize($('.gallery .content'));
    },

    setMedia: function (i) {
        var m = gallery.media[i];
        gallery.index = i;
        $('.gallery-dialog .dialog-text').html('<h2>' + m.n + '</h2>' + m.d);
        gallery.bigSize();
        gallery.offset = { l: 0, cw: 0, ch: 0, w: 0, h: 0, m: 1, x: 1, y: 0, t: parseInt(m.t) };
        var bii;
        if (m.t == '1' || m.t == '5') {
            bii = $('.gallery-dialog .bigimage').html('<div class="bigimage-inner picbox" hd-media="' + m.m + '" hd-mediaext="' + m.x + '" hd-mediatype="' + m.t + '" hd-mediafit=""></div>');
        }
        else if (m.t == '6') {
            bii = $('.gallery-dialog .bigimage').html('<div class="bigimage-inner"><iframe src="' + m.u + '" frameborder="0" style="width: 100%; height: 100%;" /></div>');

            var funcEnded = function () {
                window.focus();
                gallery.next();
            };

            var funcPause = function () {
                window.setTimeout(function () {
                    base.videoPlaying = false;
                    if (!m.a) { base.audioVolSet(1); }
                }, 10);
            };

            if (m.u.toLowerCase().indexOf('videodelivery.net') > -1) {
                var player = Stream($('iframe', bii)[0]);
                player.addEventListener('play', function () {
                    base.videoPlaying = true;
                    if (m.a) {
                        player.volume = 0;
                    }
                    else {
                        base.audioVolSet(0);
                    }
                });
                player.addEventListener('ended', funcEnded);
                player.addEventListener('pause', funcPause);
            }
            if (m.u.toLowerCase().indexOf('vimeo.com') > -1) {
                var player = new Vimeo.Player($('iframe', bii)[0]);
                player.on('play', function () {
                    base.videoPlaying = true;
                    if (m.a) {
                        player.setVolume(0);
                    }
                    else {
                        base.audioVolSet(0);
                    }
                });
                player.on('ended', funcEnded);
                player.on('pause', funcPause);
            }
        }
        else {
            bii = $('.gallery-dialog .bigimage').html('<div class="bigimage-inner"><div class="bigimage-offset"><img />' + (m.t == 3 ? '<img />' : '') + '</div></div>');
            gallery.offset.i = $('.bigimage-inner', bii).mousemove(gallery.mousemove).mouseout(gallery.mouseout);
            gallery.offset.m = 0.5;
            var pw = $('.gallery-dialog .bigimage-inner').width();
            var ph = $('.gallery-dialog .bigimage-inner').height();
            var mm = base.getMediaUrl(m.m, pw, ph, m.x);
            $('.gallery-dialog .bigimage img').load(gallery.resize).attr('src', mm.u).css({ height: ph });
        }
        if (m.t != '6' && base.videoPlaying) {
            base.videoPlaying = false;
            if ((base.audio) && (base.audioPlaying == true)) {
                base.audioVolSet(1);
            }
        }
        if (parseFloat(gallery.vars.autoplay)) {
            window.clearTimeout(gallery.autoplay_tmr);
            gallery.autoplay_tmr = window.setTimeout(gallery.next, parseFloat(gallery.vars.autoplay) * 1000);
            var mp = gallery.media[i + 1];
            if (mp && mp.t != '6') {
                $('<div class="bigimage-inner picbox" hd-media="' + mp.m + '" hd-mediaext="' + mp.x + '" hd-mediatype="' + mp.t + '" hd-mediafit="" style="opacity: 0.01; z-index: -1;"></div>').appendTo(bii);

            }
        }
        base.picbox(bii);
        base.logHit(m.i);
    },

    showMore: function () {
        $('.gallery .more').hide();
        $('.gallery .content .more-hidden').removeClass('more-hidden').show();
        $('.gallery .content .more-overlap').each(function (i, o) { $(o).removeClass('more-overlap').height($(o).attr('hd-overlapheight')) });
        var gc = $('.gallery .content').animate({ height: gallery.vars.contentheight }, 500, 'easeInQuad');
        base.picbox_resize(gc);
        gallery.vars.more = true;
    },

    updateOffset: function () {
        if (gallery.offset.w) {
            var l = gallery.offset.l - gallery.offset.x;
            var mw = (gallery.offset.t == 2) ? (gallery.offset.w - gallery.offset.cw) : (gallery.offset.w * 0.5);
            if ((gallery.offset.w * gallery.offset.m) < gallery.offset.cw) {
                l = (gallery.offset.w - gallery.offset.cw) * -0.5;
            }
            else {
                if (gallery.offset.t == 2) {
                    if (l > 0) { l = 0; } else if (l < -mw) { l = -mw; }
                }
                else if (gallery.offset.t == 3) {
                    if (l > 0) { l -= mw; } else if (l < -mw) { l += mw; }
                }
            }
            $('.gallery-dialog .bigimage-offset').css({ left: l });
            gallery.offset.l = l;
        }
        window.setTimeout(gallery.updateOffset, 20);
    },

    vars: {}

};

$(gallery.init);
 