﻿$(function () {

    var options = window.cbOptions = {
        initialWidth: '320px',
        initialHeight: '190px',
        innerWidth: '640px',
        innerHeight: '380px',
        onCleanup: function () {
            killVideos();
        },
        onClosed: function () {
            $('#scoreboard-container').load('/scoreboard', function () {
                if (typeof (DD_belatedPNG) == 'object') {
                    setTimeout(function () { DD_belatedPNG.fix('div'); }, 100);
                }
            });
        },
        onComplete: function () {
            initInputMasks();
            initTabs();
            initTwitter();
            initVideos();
            initPNGs();
            playAudio();
        },
        rel: 'nofollow'
    };

    var getMetaProperty = function (name) {
        return $('meta[property = "og:' + name + '"]').attr('content');
    };

    var initColorboxForms = function () {
        $('#create-entry-form').live('submit', function () {
            _gaq.push(['_trackEvent', 'Entries', 'Submitted entry form']);
        });

        $('#cboxLoadedContent form').live('submit', function (e) {
            var form = $(this);

            $.post(form.attr('action'), form.serialize(), function (data) {
                $.colorbox($.extend({}, options, { html: data, transition: 'none' }));
            });

            return false;
        });
    };

    var initColorboxLinks = function () {
        $('#cboxLoadedContent a').live('click', function (e) {
            var link = $(this);
            switch (link.attr('rel')) {
                case 'facebook':
                case 'tab':
                    break;
                case 'index':
                    $.colorbox.close();
                    break;
                default:
                    $.colorbox($.extend({}, options, { href: link.attr('href'), transition: 'none' }));
                    break;
            }

            return false;
        });
    };

    var initExternalLinks = function () {
        var regex = new RegExp('^' + window.location.protocol + '//' + window.location.hostname);

        $('a[href ^= "http"]').live('click', function () {
            if ((regex.test(this.href) || this.rel) == false) {
                window.open(this.href);
                return false;
            }
        });
    };

    var initFacebook = function () {
        $('a[rel = "facebook"]').live('click', function (e) {
            var hrefMatch = /&redirect_uri=([^&]+)/i.exec(this.href);
            var href = hrefMatch ? unescape(hrefMatch[1]) : null;

            FB.getLoginStatus(function (response) {
                if (response.session) {
                    showFeedDialog(href);
                }
                else {
                    FB.login(function (response) {
                        if (response.session) {
                            showFeedDialog(href);
                        }
                    }, { perms: 'publish_stream' });
                }
            });

            return false;
        });
    };

    var initInputMasks = function () {
        $('input:text[id $= "Phone"]').mask('(999) 999-9999');
        $('input:text[id $= "PostalCode"]').mask('a9a 9a9');
    };

    var initPNGs = function () {
        if (typeof DD_belatedPNG != "undefined") {
            DD_belatedPNG.fix('a, div, h1, h2, h3, img, label');
        }
    };


    var initTwitter = function () {
        if (window.twttr && window.twttr.anywhere) {
            window.twttr.anywhere(function (T) {
                $('.tweet-box').empty();
                T('.tweet-box').tweetBox({
                    width: $('#tweet').width(),
                    height: 100,
                    defaultContent: 'Visit http://youth.safemanitoba.com for an online prize auction that includes a MacBook & 48” Panasonic TV #safemanitoba #talesfromthecreep',
                    onTweet: function () {
                        var form = $('.tweet-box').parents('form:first');
                        form.find('#Method').val('twitter');
                        form.submit();
                    }
                });
            });
        }
    };

    var initTabs = function () {
        var cookieName, $tabs, stickyTab;
        cookieName = 'stickyTab';
        $tabs = $('#inviteTabs');

        $tabs.tabs();
        $tabs.bind("tabsshow", function (event, ui) {
            initTwitter();
        });
        $tabs.bind("tabsselect", function (event, ui) {
            $.cookie(cookieName, ui.index + 1);
        });

        stickyTab = $.cookie(cookieName);

        if (!isNaN(stickyTab)) {
            $tabs.tabs('select', stickyTab);
        }
    }

    var initVideos = function () {
        $('video').each(function () {
            var file = $(this).find('source').attr('src') || $(this).next('source').attr('src');
            var next = $(this).parents('.episode-video').find('a[rel = "next"]');
            var id = this.id;

            if (next.parents("#cboxLoadedContent").length == 0) {
                next.click(function () {
                    window.location.href = next.attr('href');
                });
            }

            jwplayer(id).setup({
                autostart: true,
                events: {
                    onComplete: function () {
                        killVideos();
                        next.click();
                    }
                },
                modes: [
                    { type: 'flash', src: flashBasePath + '/content/media/player.swf?' + Math.abs(Math.random()), config: { file: file} },
                    { type: 'html5' },
                    { type: 'download' }
                ]
            });
        });
    };


    var killVideos = function () {
        $('object').each(function () {
            jwplayer($(this).attr('id')).setFullscreen(false).stop().remove();
        });
    };

    var playAudio = function () {
        if ($('.episode-quiz .field-validation-error').length > 0) {
            $('#try-again').each(function () {
                this.play();
            });
        }
    };

    var showFeedDialog = function (href) {
        FB.ui({
            method: 'feed',
            link: getMetaProperty('url'),
            picture: getMetaProperty('image'),
            name: getMetaProperty('site_name'),
            description: getMetaProperty('description')
        }, function (response) {
            if (href && response) {
                $.colorbox($.extend({}, options, { href: href }));
            }
        });
    };

    var imageCache = [];
    // Arguments are image paths relative to the current page.
    var preLoadImages = function () {
        var args_len = arguments.length;
        for (var i = args_len; i--; ) {
            var cacheImage = document.createElement('img');
            cacheImage.src = arguments[i];
            imageCache.push(cacheImage);
        }
    };

    preLoadImages("/content/images/video_find_your_voice.gif", "/content/images/video_fright_shift.gif", "/content/images/video_fry_day.gif", "/content/images/video_reach_bleach.gif");



    initColorboxForms();
    initColorboxLinks();
    initExternalLinks();
    initFacebook();
    initInputMasks();
    initPNGs();
    initTabs();
    initTwitter();
    initVideos();

    // start colorbox
    $('a[rel = "popup"]').colorbox(options);

    $('body').ajaxComplete(function (e, xhr, settings) {
        if (window._gaq) {
            window._gaq.push(['_trackPageview', settings.url]);
        }
    });

    $('div.episode-quiz label').live('click', function () {
        $(this).find('input:radio').attr('checked', true).closest('form').submit();
    });
});

