$(document).ready(function () {
    
    var AGE_GATE_VALUE = {
        pass: '1',
        fail: '0',
        unknown: undefined
    };

    var $this = $(this);
    var currentWidth = $(window).width();

    var $agegate = [],
        videoPlayer;

    var ageGatePassed;

    if (currentWidth <= 650) {
        $this.css("margin-top", "610em");
    }
    function current() {
        return $('#carousel').triggerHandler('currentPage');
    }

    var currentTimer = function() {
        return $('#pager a .bottom').eq(current()).find('span');
    };

    function prevTimers() {
        return $('#pager a .bottom').slice(0, current()).find('span');
    }

    function allTimers() {
        return $('#pager a .bottom span');
    }

    function initVideoItems() {
    // $('#pager .playvid')
        $('#pager .pagerThumb')
        .attr('rel', 'gallery').fancybox({
            openEffect: 'none',
            closeEffect: 'none',
            nextEffect: 'none',
            prevEffect: 'none',
            titleShow: true,
            padding: 0,
            helpers: {
                title: {
                    type: 'inside'
                }
            },
            margin: 50,
            beforeShow: function (event) {
                // Find the iframe ID
                $('body').append($('.fancybox-wrap'));
                $('html, body').animate({
                    scrollTop: $("#logo").offset().top
                }, 500);
                var $fancyboxIframe = $.fancybox.inner.find('iframe');
                var id = $fancyboxIframe.attr('id');
                var $div = $('<div></div>').attr('id', id).addClass('fancybox-iframe');
                $fancyboxIframe.after($div);
                $fancyboxIframe.remove();

                $agegate = $('.fancybox-inner .age-gate');
                
                if (!$agegate.length) {
                    $agegate = $('<div class="content-container"> \
                                    <div class="age-gate"> \
                                        <div class="content"> \
                                            <h3>' + window.twoK.localization['Please Enter Your Date of Birth'] + '</h3> \
                                            <div class="date-selector"> \
                                                <div class="dropdownWrapper month"> \
											                            <select></select> \
                                                </div> \
                                                <div class="dropdownWrapper day"> \
											                            <select></select> \
                                                </div> \
                                                <div class="dropdownWrapper year"> \
											                            <select></select> \
                                                </div> \
                                            </div> \
                                            <div class="buttons"> \
                                                <a class="cancel">' + window.twoK.localization['Cancel'] + '</a> \
                                                <a class="submit">' + window.twoK.localization['Submit'] + '</a> \
                                            </div> \
                                        </div> \
                                        <div class="fail"> \
                                            <h3>' + window.twoK.localization['Sorry!'] + '<br/>' + window.twoK.localization['You may not access this content'] + '</h3> \
                                            <a class="ok">' + window.twoK.localization['OK'] + '</a> \
                                        </div> \
                                        <div class="overlay"></div> \
                                    </div> \
                                </div>');
                    $div.before($agegate);
                }

                initAgeGate();

                $('#carousel').triggerHandler('stop');

                setTimeout(function() {
                    var $current = $('#carousel .slide').eq(0);
                    var currentvid = $current.data('videoid'),
                        isAgegated = !!$current.data('agegate'),
                        fancyInner = $('.fancybox-inner'),
                        title = $current.find('h1').html();

                    videoPlayer =  new YT.Player(id, {
                        videoId: currentvid,
                        events: {
                            'onReady': function () {
                                fancyInner.prepend("<h1>" + title + "</h1>");
                                fancyInner.append('<div id="comments"></div>');
                                buildComments(currentvid, title);
                                var video = {
                                    videoId: currentvid,
                                    ageGate: isAgegated,
                                    largeimage: 'https://i1.ytimg.com/vi/' + currentvid + '/sddefault.jpg'
                                };
                                checkAgeGate(video);
                            }
                        },
                        playerVars: { rel: 0 }
                    });
                    
                }, 650);
            },
            afterClose: function () {
                //restart carousel
                $('#carousel').triggerHandler('play', true);
            },
            beforeClose: function () {
                $('body').append($('#moot'));
            },
            afterShow: function() {
                //fix close X handlers for mobile
                function handler(e){
                    e.preventDefault();
                    $.fancybox.close();
                }

                $("a.fancybox-close").off('click').one({'click':handler,'touchstart':handler});
            }
        });

        //force title into view
        $(window).resize();
    }

    function buildComments(videoId, title) {
      var url = '/homeCarousel/' + videoId;
        window.makeCommentForm('#comments', url, title);
    }
    
    function initAgeGate() {
        $('a.cancel', $agegate).on('click', closeModal);

        $('a.submit', $agegate).on('click', function () {
            var month = $('.dropdownWrapper.month input').val();
            var day = $('.dropdownWrapper.day input').val();
            var year = $('.dropdownWrapper.year input').val();

            var birthdate = new Date(month + ' ' + day + ' ' + year);

            if (!!birthdate.getYear()) {
                if (isMinimumAge(birthdate, 17)) {
                    $.cookie('agegate', AGE_GATE_VALUE.pass);
                    ageGatePassed = AGE_GATE_VALUE.pass;
                    $agegate.hide();

                    //track with analytics
                    var $fancy = $('.fancybox-wrap').eq(0);
                    Analytics.trackEvent('Video Age Gate', 'Pass', 'Modal: ' + $fancy.attr('data-moduletitle') + ' : ' + $fancy.attr('data-videoid'));

                } else {
                    $.cookie('agegate', AGE_GATE_VALUE.fail);
                    ageGatePassed = AGE_GATE_VALUE.fail;
                    $('.age-gate .fail .ok').on('click', closeModal);
                    $('.age-gate .content').hide();
                    $('.age-gate .fail').show();

                    //track with analytics
                    var $fancy = $('.fancybox-wrap').eq(0);
                    Analytics.trackEvent('Video Age Gate', 'Fail', 'Modal: ' + $fancy.attr('data-moduletitle') + ' : ' + $fancy.attr('data-videoid'));
                }
            } else {
                alert(window.twoK.localization['Invalid date']);
            }

            function isMinimumAge(birthdate, minimumAge) {
                var today = new Date();
                var before = new Date(today.getFullYear() - minimumAge, today.getMonth(), today.getDate());
                return before.getTime() - birthdate.getTime() >= 0;
            }
        });

        //bind data to dropdown lists
        var months = [
                    window.twoK.localization['Month'].toUpperCase(),
                    window.twoK.localization['January'],
                    window.twoK.localization['February'],
                    window.twoK.localization['March'],
                    window.twoK.localization['April'],
                    window.twoK.localization['May'],
                    window.twoK.localization['June'],
                    window.twoK.localization['July'],
                    window.twoK.localization['August'],
                    window.twoK.localization['September'],
                    window.twoK.localization['October'],
                    window.twoK.localization['November'],
                    window.twoK.localization['December']
        ];
        bindStyledSelect($('.dropdownWrapper.month'), months);
        var days = [window.twoK.localization['Day'].toUpperCase()];
        for (var d = 1; d <= 31; d++) days.push(d);
        bindStyledSelect($('.dropdownWrapper.day'), days);
        var years = [window.twoK.localization['Year'].toUpperCase()];
        for (var y = new Date().getFullYear() ; y >= 1900 ; y--) years.push(y);
        bindStyledSelect($('.dropdownWrapper.year'), years);

        function bindStyledSelect($dropdownWrapper, options) {
            var $styledSelect = $('select', $dropdownWrapper);
            var optionHtml = '';
            for (var i = 0; i < options.length; ++i) {
                optionHtml += '<option value="' + options[i] + '">' + options[i] + '</option>';
            }
            $styledSelect.html(optionHtml).styledSelect();
        }
    }
    
    function checkAgeGate(video) {
        if (video.ageGate) {
            switch ($.cookie('agegate')) {
                case AGE_GATE_VALUE.pass:
                    videoPlayer.cueVideoById(video.videoId, 0, 'large');
                    break;
                case AGE_GATE_VALUE.fail:
                    $('.content', $agegate).hide();
                    $('.fail', $agegate).show();
                    $('.age-gate .fail .ok').on('click', closeModal);
                    showAgeGate(video);
                    break;
                case AGE_GATE_VALUE.unknown:
                    showAgeGate(video);
                    break;
            }
        } else {
            videoPlayer.cueVideoById(video.videoId, 0, 'large');
        }
    }

    function showAgeGate(video) {
        $('.age-gate').css({ 'height': '385px', 'background-image': 'url(' + video.largeimage + ')' }).show();
    }
    
    function closeModal() {
        $('.fancybox-close').trigger('click');
    }

    function updatePagers(data) {
        allTimers().stop().width(0);
        prevTimers().width('0%');
        var $activeSlide = data.items['new'].eq(0);
        var bgImage;
        if (currentWidth <= 650) {
            if ($activeSlide.data('mobile').length) bgImage = $activeSlide.data('mobile');
            else bgImage = $activeSlide.data('background');
        } else {
            bgImage = $activeSlide.data('background');
        }

        window.changeBackground(bgImage);

        var index = $activeSlide.attr('id').slice(-1); //$activeSlide.attr('id').substr(-1)-1;
        $('#overhang a').removeClass('selected').eq(index - 1).addClass('selected');
    }

    function initCarousel() {
        var yt_url = "//www.youtube.com/embed/";
        $("#carousel").carouFredSel({
            responsive: true,
            width: "100%",
            items: {
                visible: 1,
                height: "20%"
            },
            scroll: {
                duration: 500,
                pauseOnHover: true,
                fx: "slide",
                easing: "linear",
                onBefore: updatePagers
            },
            onCreate: function () {
                $('#carousel').triggerHandler('play');
            },
            auto: {
                play: true,
                timeoutDuration: 5000,
                pauseOnResize: true,

                onTimeoutStart: function (percentage, duration) {
                    currentTimer().stop().animate({
                        width: '100%'
                    }, {
                        duration: duration,
                        easing: 'linear'
                    });
                },
                onTimeoutPause: function (percentage, duration) {
                    currentTimer().stop().css('width', 0 + '%');
                } //,
                //onBefore: updatePagers
            },
        pagination: {
                container: "#pager",
                anchorBuilder: function(nr) {
                    var videoLink = "#";
                    var videoClass = "pagerThumb";
                    if ($(this).data('videoid') != undefined) {
                        videoLink = yt_url + $(this).data('videoid');
                    } else {
                        videoClass = "";
                    }
                    return '<a href="' + videoLink + '" class="fancybox.iframe">'+
                        '<img src="'+$(this).data('thumb')+'" />'+
                        '<div class="top"></div>'+
                        '<div class="bottom"><p>' + $(this).find('h1').text() + '</p>' +
                        '<span></span></div>'+
                         ($(this).data('videoid') ?
                             '<div class="' + videoClass + ' playvid fancybox.iframe" href="' + yt_url + $(this).data('videoid') + '"><img src="//downloads.2kgames.com/2k/img/playbutton.png"/></div>'
                             : '') +
                        '</a>';
                }
            }
        });

        window.changeBackground($('#carousel .slide').eq(0).data('background'));

        initVideoItems();

    }

    initCarousel();

    $(window).on('resize', function () {
        var baseSize = $(window).width() > 650 ? 65 : 100;
        $('#carousel_wrapper h1').each(function () {
            var $h1 = $(this);
            var fontSize = baseSize;
            
            $h1.css({
                'height': 'auto',
                'font-size': baseSize + 'em',
                'white-space': 'nowrap'
            });
            
            var targetHeight = $h1.height();
            
            $h1.css('white-space', 'normal');

            while ($h1.height() > targetHeight) {
                $h1.css('font-size', --fontSize + 'em');
            }

            var marginTop = $h1.siblings('.actions').height() - $h1.height() * .02;
            $h1.css('margin-top', marginTop);
        });
    }).trigger('resize');
});
(function($) {

    $(document).one('gridster.done', function() {
        var curr_width, $module, origSize, mobileBreakPoint = 650;
        $module = $('#connect_with_us');
        origSize = parseInt($module.parent().attr('data-sizey'),10);

        function triggerResize() {
            $(document).trigger('grid.updateHeight');
        }
        function moduleResize() {
            curr_width = $(window).width();

            if (curr_width > mobileBreakPoint) {
                $module.parent().attr('data-sizey', origSize);
                triggerResize();
            } else {
                $module.parent().attr('data-sizey', '-1');
                triggerResize();
            }

            last_width = curr_width;
        }
        moduleResize();
        $(window).on('resize', moduleResize);
        
        getAccessToken(function(accessToken){    
            
            $module.find('.fb-page').each(function(){
                var $this = $(this);
                var username = $this.data('username');
                $this.find('a').attr('href', 'https://facebook.com/' + username);
                $this.find('iframe').attr('src', '//www.facebook.com/plugins/like.php?href=https%3A%2F%2Fwww.facebook.com%2F' + username + '&send=false&layout=button_count&width=450&show_faces=true&font&colorscheme=light&action=like&height=21');
                $this.find('img').attr('src', '//graph.facebook.com/' + username + '/picture')
                getLatestFeed(username, accessToken, getLatestFeedComplete);         
            
                function getLatestFeedComplete(response){
                    var message;
                    if(response.data.length > 0){
                        
                        var streamItem = response.data[0];
                        message = streamItem.message;
                        var date = formatDateFromUnixTimeStamp(streamItem.created_time);
                        $this.find('.date').html(date);
                    } else {
                        message = "latest status not available: " + JSON.stringify(response);
                    }
                    
                    var $message = $this.find('p').html(message);
                    //truncate long titles with elipses
                    var maxHeight = $message.height();
                    $message.css('height', 'auto');
                    while($message.height() > maxHeight){
                        message = message.replace(/ [^ ]*$/, '...');
                        $message.html(message);
                    }
                    message = message.replace(/(https?:\/\/\S*)/g,'<a target="_blank" href="$1">$1</a>')
                    $message.html(message);
                    $message.css('height', '');
                };       
            }); 
        });
    });   
                  
    
    function getAccessToken(callback){
         $.ajax({
            type: 'GET',
            contentType: 'application/json; charset=utf-8',
            url: twokApiUrl + '/facebook/get-access-token',
            dataType: 'jsonp',
            success: callback
        });
    }

    function getLatestFeed(username, accessToken, callback){

        var url = "https://graph.facebook.com/fql?" + accessToken + "&q=select message, created_time from stream where source_id in (select page_id from page where username = '" + username + "') and actor_id in (select page_id from page where username = '" + username + "') and message != '' limit 1"; 
        $.ajax({
            type: 'GET',
            contentType: 'application/json; charset=utf-8',
            url: url,
            dataType: 'jsonp',
            success: callback
        });
    }

    function formatDateFromUnixTimeStamp(unixTime){
        var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
        var date = new Date(unixTime * 1000);
        var hour = date.getHours() % 12;
        if(hour == 0){
            hour = 12;
        }
        var minute = date.getMinutes();
        if(minute < 10){
            minute = '0' + minute;
        }
        var ampm = (date.getHours() < 12) ? 'am' : 'pm';
        return months[date.getMonth()] + ' ' + date.getDate() + ' at ' +  hour + ':' + minute +  ampm;
    }
    
})(jQuery);



