﻿function minimizePlayer() { player.minimize();return false; }
function maximizePlayer() { player.maximize();return false; }

function displayValidation(input, isValid, message) {
    var ctrl = $(input);
    var toAdd = 'valid-n';
    var toRemove = 'valid-y';
    if (isValid) {
        toAdd = 'valid-y';
        toRemove = 'valid-n';
    }
    ctrl.parent().addClass(toAdd);
    ctrl.parent().removeClass(toRemove);
    ctrl.parent().children('.message').text(message);
};
function validateHelper(input, type) {
    var ctrl = $(input);
    var doJSON = !(ctrl.attr('nojson') == 'True');
    var minLength = ctrl.attr('minlength');
    var curLength = ctrl.val().length;
    var isTooShort = false;
    if (minLength != null) {
        isTooShort = (curLength < minLength);
        displayValidation(ctrl, !isTooShort, isTooShort ? 'Too short.' : 'OK.');
    }
    if (doJSON && !isTooShort) {
        var url = 'validate-' + type + '/' + ctrl.val();
        $.getJSON(url, null, function(data) {
            displayValidation(ctrl, data.ok, data.message);
        });
    }
};
function validate(name, validateOnPageLoad) {
    var selector = "#" + name;
    $(selector).blur(function() { validateHelper($(this), name); });
    $(selector).keyup(function() { validateHelper($(this), name); });
    if (validateOnPageLoad) { validateHelper($(selector), name); }
}

var notifications = function() {
    return {
        ready: function() {
            alert('notifications object is ready');
        },
        display: function(msg, id) {
            var html = '<div class="band">';
            html += '<div class="message">' + msg + '</div>';
            html += '<div class="dismiss"><a onclick="notifications.dismiss(' + id + ')" title="dismiss this message">&#215;</a></div>';
            html += '</div>';
            $('#notifications').append(html);                   // Add the notification to the HTML DOM
            $('body').css('margin-top', '35px');               // Move the rest of the content down the page
            $('#notifications').fadeIn('slow')                  // Fade the notifications in
        },
        dismiss: function(i) {
            $.post('/my/notifications-dismiss', { id: i });
            $('#notifications').hide();                         // Hide the notifications area
            $('body').css('margin-top', '0px');                 // Restore the standard padding
        },
        fetch: function() {
            $.post(
                '/my/notifications-fetch',
                'ok=ok',
                function(data) {
                    if (data.id > 0) { notifications.display(data.msg, data.id); }
                },
                "json"
            );
        }
    }
} ();

var logger = function() {
    var cachebust = function() {
        return 'ts=' + new Date().getTime();
    };
    return {
        log: function(type) {
            $.post(
                '/log/' + type,
                cachebust(),
                function(data) {
                    if(!data.ok) alert(data.msg);
                },
                'json'
            );
        }
    }
}();

var player = function() {
    var cachebust = function() {
        return 'ts=' + new Date().getTime();
    };
    var a = function(uri, answer) {
        $.post(uri, 'answer=' + answer, function(data) {
            $(messageId).replaceWith(data);
            $(frameId).addClass('withMsg');
            $(messageId).show('drop', { direction: 'up' }, 2000);
        }, 'html');
    };
    var startId = '';
    var questionId = '';
    var formId = '';
    var timerId = '';
    var frameId = '';
    var messageId = '';
    var scoreId = '';
    var voiceId = '';
    var optsId = '';
    var optsToggleId = '';
    var shuffleButtonId = '';
    var width = 0;
    var sidebarOpen = false;
    var isShuffleDisabled = false;
    return {
        ready: function() {
            if (startId === '') { alert('startId is empty'); return false; }
            if (questionId === '') { alert('questionId is empty'); return false; }
            if (formId === '') { alert('formId is empty'); return false; }
            if (timerId === '') { alert('timerId is empty'); return false; }
            if (frameId === '') { alert('frameId is empty'); return false; }
            if (messageId === '') { alert('messageId is empty'); return false; }
            if (scoreId === '') { alert('scoreId is empty'); return false; }
            if (voiceId === '') { alert('voiceId is empty'); return false; }
            if (optsId === '') { alert('optsId is empty'); return false; }
            if (optsToggleId === '') { alert('optsToggleId is empty'); return false; }
            if (shuffleButtonId === '') { alert('shuffleButtonId is empty'); return false; }
            alert('player object is ready');
            return true;
        },
        debug: function(prop) {
            alert(eval(prop));
        },
        wireup: function(start, question, form, timer, frame, message, score, voice, opts, optsToggle, shuffleButton) {
            startId = start;
            questionId = question;
            formId = form;
            timerId = timer;
            frameId = frame;
            messageId = message;
            scoreId = score;
            voiceId = voice;
            optsId = opts;
            optsToggleId = optsToggle;
            shuffleButtonId = shuffleButton;
            width = $('body').width();
            $(formId).submit(function() { player.guess(); return false; });
            $(startId).click(function() { player.start(); });
            $(optsToggleId).click(function() { player.toggleOptions(); });
            $(optsId + ' ul.guides li').click(function() { player.toggleOptionsGuide(this); return false; });
            $(optsId + ' ul.genres li').click(function() { player.toggleOptionsGenre(this); return false; });
            $(shuffleButtonId).click(function() { player.shuffle(); });
        },
        getQueryString: function() {
            var qs = '';
            var guides = $(optsId + ' ul.guides li.selected');
            var genres = $(optsId + ' ul.genres li.selected');
            if (guides.length > 0 || genres.length > 0) qs += '?opts=on';
            if (guides.length > 0) {
                qs += '&guide=';
                $.each(guides, function() {
                    var guide = $(this).attr('data-guide');
                    qs += guide + ',';
                });
                qs = qs.substring(0, qs.length - 1);
            };
            if (genres.length > 0) {
                qs += '&genre=';
                $.each(genres, function() {
                    var genre = $(this).attr('data-genre');
                    qs += genre + ',';
                });
                qs = qs.substring(0, qs.length - 1);
            };
            return qs;
        },
        shuffle: function() {
            window.location = '/cards/shuffle' + this.getQueryString();
        },
        prepTimer: function() {
            $(timerId).countdown({ until: +stopwatch, compact: true, format: 'MS', onExpiry: player.timeout, onTick: player.tick });
            $(timerId).countdown('pause');
        },
        iframe: function(src) {
            $(frameId).attr('src', src);
            window.location.hash = src;
        },
        readAnswer: function() {
            $(formId + ' input').attr('disabled', 'true'); // disable the form
            var answer = $(formId + ' input[type=text]').val(); // read its value
            $(timerId).countdown('pause'); // pause timer
            return answer;
        },
        showQuestion: function(question) {
            var css = (question.length > 35) ? 'l2' : 'l1';
            $(questionId).html(question).removeClass().addClass(css);
        },
        showMessage: function(isCorrect, line1, line2, line3, stats) {
            var l1 = $(messageId + ' h1');
            var l2 = $(messageId + ' h2');
            var l3 = $(messageId + ' p');
            if (isCorrect) { l1.addClass('y'); l1.removeClass('n'); } else { l1.addClass('n'); l1.removeClass('y'); }
            l1.text(line1);
            l2.text(line2);
            l3.text(line3);
            $(frameId).addClass('withMsg');
            $(messageId).show('drop', { direction: 'up' }, 2000);

            $.each(stats, function(i) { // for each stat, update the display
                //var id = messageId + 'dl dd.stat' + i;
                //$(id).text(this);
            });
        },
        played: function(css) {
            $(messageId).show();
            $(frameId).addClass('withMsg');
            $(messageId + ' h1').addClass(css);
        },
        hideMessage: function() {
            $(frameId).removeClass('withMsg');
            $('body').removeClass();
            $(messageId).hide();
        },
        awardBadges: function() {
            $.post(
                '/my/award-badges',
                cachebust(),
                function(data) {
                    if (!data.ok) alert('There is a problem with the badges. We are working on the problem.');
                },
                'json'
            );
        },
        rate: function(rating) {
            $.post(
                '/cards/rate/' + rating,
                cachebust(),
                function(data) {
                    if (!data.ok) alert(data.message);
                    else {
                        $('a.thumbs').hide();
                        $('a.thumbs.' + rating).show().addClass('selected');
                    }
                },
                'json'
            );
        },
        start: function() {
            $.post(
                '/cards/start',
                cachebust(),
                function(data) {
                    player.iframe(data.url); // load the website
                    player.showQuestion(data.question); // fill the challenge
                    player.disableShuffleButton(false); // enabled the shuffle button if disabled
                    setTimeout(function() { player.reveal(); }, 250); // reveal the challenge
                    $(timerId).effect('pulsate', {}, 500); // courtesy time
                    setTimeout(function() { $(timerId).countdown('resume'); }, 3000); // start timer
                },
                'json'
            );
        },
        resume: function(url, question) {
            player.restore(url, question);
            $(timerId).countdown('resume');
        },
        restore: function(url, question) {
            player.iframe(url);
            player.showQuestion(question);
            player.reveal();
        },
        restoreWithAnswer: function(url, question, answer) {
            player.restore(url, question);
            $(formId + ' input[type=text]').val(answer); // fill in the answer
            $(formId + ' input').attr('disabled', 'true'); // disable the form
        },
        timeout: function() {
            var answer = player.readAnswer();
            a('/cards/timeout', answer);
        },
        guess: function() {
            var answer = player.readAnswer();
            a('/cards/answer', answer);
        },
        rightOrWrong: function(isCorrect, newCoins, m1, m2, m3, stats) {
            if (isCorrect) {
                $(scoreId).html(newCoins).effect('highlight', {}, 1000);
            }
            player.showMessage(isCorrect, m1, m2, m3, stats);
        },
        tick: function(periods) {
            if (periods[5] == 0 && periods[6] == 30) {
                $(timerId).addClass("warn1");
            };
            if (periods[5] == 0 && periods[6] == 10) {
                $(timerId).addClass("warn2");
            };
            if (periods[5] == 0 && periods[6] <= 10) {
                $(timerId).effect('highlight', { color: '#990000' }, 250);
            }
        },
        reveal: function() {
            $(voiceId).prev().click(function() {
                $(formId).parent().toggle();
                $(voiceId).toggle();
                $(questionId).toggle();
            });
            $(formId).parent().show();
            $(voiceId).hide('slide');
            $(startId).parent().hide('slow');
        },
        unreveal: function() {
            $(formId).parent().hide();
            $(voiceId).show('slide');
            $(startId).parent().show();
        },
        toggleOptions: function() {
            $(optsId).slideToggle('fast');
            $(optsToggleId).toggleClass('on');
        },
        toggleOptionsGuide: function(elem) {
            var li = $(elem);
            var guide = li.attr('guide');
            li.toggleClass('selected');
            var isSelected = li.hasClass('selected');
        },
        toggleOptionsGenre: function(elem) {
            var li = $(elem);
            var genre = li.attr('class');
            li.toggleClass('selected');
        },
        openSidebar: function(uri) {
            sidebarOpen = true;
            var sidebarId = '#stfb-sidebar';
            var opened = ($(sidebarId).length > 0);
            if (!opened) {
                var html = '<iframe id="stfb-sidebar" frameborder="0" noresize="0" name="sidebar" src="" style="display:none" ></iframe>';
                $('body').append(html);
            };
            $(sidebarId).attr('src', uri);
            $(sidebarId).show();
        },
        closeSidebar: function() {
            sidebarOpen = false;
            $('#stfb-sidebar').hide();
            $(frameId).attr('style', 'width:' + (width) + 'px');
            actions.sidebarClosed();
        },
        toggleSidebar: function(uri, icon) {
            if (sidebarOpen) {
                $(icon).removeClass('checked');
                player.closeSidebar();
            } else {
                $(icon).addClass('checked');
                player.openSidebar(uri);
            }
        },
        disableShuffleButton: function(bool) {
            isShuffleDisabled = bool;
            if (bool) {
                $('#stfb-shuffle-btn').hide();
                $('#stfb-shuffle-disabled').show();
            } else {
                $('#stfb-shuffle-btn').show();
                $('#stfb-shuffle-disabled').hide();
            };
        },
        minimize: function() {
            $('#stfb').animate({ top: "5px" }, 300).animate({ top: "-70px" }, 600);
            $('#frame').animate({ paddingTop: "24px" }, 900);
            $('html.ie #stfb-shuffle').hide();
        },
        maximize: function() {
            $('html.ie #stfb-shuffle').show();
            $('#frame').animate({ paddingTop: "70px" }, 900);
            $('#stfb').animate({ top: "5px" }, 600).animate({ top: "0px" }, 300);
        }
    }
} ();

var actions = function() {
    var a = '';
    var playfirst = function() {
        alert('You need to start playing the card before you can do that.');
    };
    var pending = function() {
        alert("Coming soon! (This is why we're in alpha...)");
    };
    var state = '';
    return {
        ready: function() {
            alert('actions object is ready');
            alert('state = ' + state);
        },
        wireup: function(x) {
            a = x;
            state = $('body').attr('class');
            var fav = $(a + ' a[rel=favorite]').attr('id');
            favorites.wireupPlay(fav);
            $(a + ' a').click(function() {
                var el = $('#' + $(this).attr('id'));
                var action = $(this).attr('rel');
                switch (action) {
                    case 'favorite':
                        favorites.starPlay();
                        break;
                    case 'share':
                        player.toggleSidebar('/cards/share', el);
                        break;
                    case 'report':
                        player.toggleSidebar('/cards/report', el);
                        break;
                    case 'discuss':
                        player.toggleSidebar('/cards/discuss', el);
                        break;
                    default:
                        pending();
                        break;
                };
            });
        },
        sidebarClosed: function() {
            $(a + ' a').each(function() {
                var action = $(this).attr('rel');
                if (action != 'favorite') {
                    $(this).removeClass('checked');
                };
            });
        }
    }
} ();


var fbconnect = function() {
    var oldButtonText = '';
    var button = null;
    var cachebust = function() {
        return 'ts=' + new Date().getTime();
    };
    var connected = function() {
        var uri = '/account/fbconnected?url=' + window.location;
        window.location = uri;
    };
    var disableButton = function(id) {
        oldButtonText = $(id).html();
        $(id).html('Please wait...').attr('disabled', 'disabled').addClass('disabled');
        button = $(id);
    };
    var enableButton = function() {
        $(button).html(oldButtonText).removeAttr('disabled').removeClass('disabled');
    };
    return {
        login: function() { window.location = '/account/login-fbconnect'; },
        join: function() { window.location = '/account/join-fbconnect'; },
        connect: function() { connected(); },
        grant: function() {
            FB.ensureInit(function() {
                FB.Connect.showPermissionDialog("offline_access,publish_stream", connected);
            });
        },
        pubcallback: function(post_id, exception) {
            enableButton();
        },
        publishRecruit: function(uri, playtime, cards, coins) {
            var attachment = {
                name: 'Join Shuffletime, the online game that lets you play the internet',
                href: uri,
                description: 'Here are a few of my stats:',
                properties: { 
                    'Playtime': playtime,
                    'Cards played': cards,
                    'Coins earned': coins
                },
                media: [{
                    type: 'image',
                    src: 'http://cdn.shuffletime.com/content/logo_facebook.png',
                    href: uri
                }]
            };
            var actions = [{
                text: 'Play Now!',
                href: uri
            }];
            var message = ' cannot stop playing the new online game Shuffletime. You should try it.';
            FB.Connect.streamPublish(message, attachment, actions, null, 'Enter your personal message here:', null, false);
        },
        publishInvite: function(btn, code, max, used) {
            disableButton(btn);
            var uri = 'http://shuffletime.com/invitation-code/enter/' + code
            var attachment = {
                name: 'Join Shuffletime, the online game that lets you play the internet',
                href: uri,
                description: 'You\'ll need this invite code to get into the website.',
                properties: { 'Invite Code': code },
                media: [{
                    type: 'image',
                    src: 'http://cdn.shuffletime.com/content/logo_facebook.png',
                    href: uri
                }]
            };
            var actions = [{
                text: 'Play Now!',
                href: uri
            }];
            var message = 'I\'m beta-testing the new, invite-only online game Shuffletime, and I have ' + (max - used) + ' invitations to give out.';
            FB.Connect.streamPublish(message, attachment, actions, null, 'Write whatever you want here:', fbconnect.pubcallback, false);
        },
        publishCard: function(btn, title, guide, genre, username, link, thumbnail, time, earnedCoins, totalCoins) {
            if(btn != null) { disableButton(btn); }
            var description = ((genre == 'Image') ? 'an' : 'a') + ' ' + genre + ' from ' + guide;
            var attachment = {
                name: title,
                href: link,
                caption: description,
                description: 'Found on Shuffletime.com, while playing the Internet.',
                properties: { 'I completed in': time, 'I earned': earnedCoins + ' coins', 'I now have': totalCoins + ' coins' },
                media: [{
                    type: 'image',
                    src: thumbnail,
                    href: link
                }]
            };
            var actions = [{
                text: 'Play Now!',
                href: link
            }];
            var message = 'just saw this awesome ' + genre.toLowerCase() + ' on Shuffletime. Check it out.';
            FB.Connect.streamPublish(message, attachment, actions, null, 'Add a comment:', fbconnect.pubcallback, false);
        },
        publishCard2: function(title, guide, genre, username, link, thumbnail, timer, coins) {
            var description = ((genre == 'Image') ? 'an' : 'a') + ' ' + genre + ' from ' + guide;
            var attachment = {
                name: title,
                href: link,
                caption: description,
                description: 'Found on Shuffletime.com, while playing the Internet.',
                properties: { 'Timer': timer, 'Coins': coins },
                media: [{
                    type: 'image',
                    src: thumbnail,
                    href: link
                }]
            };
            var actions = [{
                text: 'Play Now!',
                href: link
            }];
            var message = 'just saw this awesome ' + genre.toLowerCase() + ' on Shuffletime. Check it out.';
            FB.Connect.streamPublish(message, attachment, actions, null, 'Add a comment:', null, false);
        }        
    }
} ();


var share = function() {
    var title = '';
    var guide = '';
    var genre = '';
    var username = '';
    var shareToken = '';
    var cardGuid = '';
    var time = '';
    var earnedCoins = '';
    var totalCoins = '';
    var summary = '';
    var link = '';
    var thumb = '';
    function pop(uri, name, options) {
        if (!window.open(uri, name, options)) {
            window.location.href = uri;
        };
    };
    return {
        wireup: function(p1, p2, p3, p4, p5, p6, p7, p8, p9) {
            title = p1;
            guide = p2;
            genre = p3;
            username = p4;
            shareToken = p5;
            cardGuid = p6;
            time = p7;
            earnedCoins = p8;
            totalCoins = p9;
            summary = ((genre == 'Image' || genre == 'Article') ? 'an' : 'a') + ' ' + genre + ' from ' + guide;
            link = 'http://shfltm.com/' + username + '/' + shareToken;
            thumb = 'http://cdn.shuffletime.com/images/cards/__' + cardGuid + '.img';
        },
        twitter: function() {
            var status = '"' + title + '", ' + summary + ': ' + link + ' #shuffletime';
            var url = 'http://twitter.com/home?status=' + escape(status) + '&source=Shuffletime';
            if (!window.open(url, 'sharetwitter', 'toolbar=1,status=1,resizable=1,scrollbars=1,width=800,height=526')) {
                window.location.href = url;
            };
        },
        twitterWithParams: function(pTitle, pGenre, pGuide, pUsername, pShareToken) {
            var pSummary = ((pGenre == 'Image' || pGenre == 'Article') ? 'an' : 'a') + ' ' + pGenre + ' from ' + pGuide;
            var pLink = 'http://shfltm.com/' + pUsername + '/' + pShareToken;
            var status = '"' + pTitle + '", ' + pSummary + ': ' + pLink + ' #shuffletime';
            var url = 'http://twitter.com/home?status=' + escape(status) + '&source=Shuffletime';
            pop(url, 'sharetwitter', 'toolbar=1,status=1,resizable=1,scrollbars=1,width=800,height=526');
        },
        facebook: function() {
            var status = 'Found this ' + genre + ' from ' + guide + ' on Shuffletime: "' + title + '".';
            var url = 'http://www.facebook.com/sharer.php?u=' + encodeURIComponent(link) + '&t=' + encodeURIComponent(status);
            if (!window.open(url, 'sharefacebook', 'toolbar=1,status=1,resizable=1,scrollbars=1,width=626,height=436')) {
                window.location.href = url;
            };
        },
        email: function() {
            var url = '/cards/email';
            pop(url, 'sharemail', 'toolbar=1,status=1,resizable=0,scrollbars=0,width=500,height=500');
        },
        emailWithParams: function(pShareToken) {
            var url = '/cards/email/' + pShareToken;
            pop(url, 'sharemail', 'toolbar=1,status=1,resizable=0,scrollbars=0,width=500,height=500');
        },
        facebookconnect: function(btn) {
            fbconnect.publishCard(btn, title, guide, genre, username, link, thumb, time, earnedCoins, totalCoins);
        },
        facebookConnectPop: function() {
            pop(window.location.href + '?t=fb', 'sharefacebook', 'toolbar=1,status=1,resizable=0,scrollbars=0,width=626,height=500');
        },
        emailPop: function() {
            pop(window.location.href + '?t=email', 'sharemail', 'toolbar=0,status=0,resizable=1,scrollbars=0,width=500,height=500');
        },
        debug: function() {
            alert(summary + link + thumb);
        }
    }

} ();


var recruit = function() {
    var url = '';
    var playtime = '';
    var cards = '';
    var coins = '';
    function pop(uri, name, options) {
        if (!window.open(uri, name, options)) {
            window.location.href = uri;
        };
    };
    return {
        wireup: function(recruitingUrl, myPlaytime, myCards, myCoins) {
            url = recruitingUrl;
            playtime = myPlaytime;
            cards = myCards;
            coins = myCoins;
        },
        twitter: function() {
            var status = 'You need to try #shuffletime. Best. Game. Ever. ' + url;
            var uri = 'http://twitter.com/home?status=' + escape(status) + '&source=Shuffletime';
            pop(uri, 'recruittwitter', 'toolbar=1,status=1,resizable=1,scrollbars=1,width=800,height=526');
        },
        email: function() {
            var uri = '/my/recruit-by-email';
            pop(uri, 'recruitemail', 'toolbar=1,status=1,resizable=0,scrollbars=0,width=500,height=500');
        },
        facebook: function() {
            var status = 'I cannot stop playing Shuffletime. Have you tried?';
            var uri = 'http://www.facebook.com/sharer.php?u=' + encodeURIComponent(url) + '&t=' + encodeURIComponent(status);
            pop(uri, 'recruitfacebook', 'toolbar=1,status=1,resizable=1,scrollbars=1,width=626,height=436');
        },
        facebookConnect: function() {
            fbconnect.publishRecruit(url, playtime, cards, coins);
        }
    }
} ();

var favorites = function() {
    var playStarId = '';
    var cachebust = function() {
        return 'ts=' + new Date().getTime();
    };
    var clicked = false;
    return {
        ready: function() {
            alert('favorites object is ready');
        },
        wireupPlay: function(x) {
            playStarId = '#' + x;
            //$(playStarId).click(function() { favorites.starPlay(); });
        },
        starPlay: function() {
            if (!clicked) {
                $.post(
                    '/cards/star',
                    cachebust(),
                    function(data) {
                        if (data.ok) {
                            $(playStarId).addClass('checked');
                            clicked = true;
                        } else {
                            alert('Your favorites are not responding. Please try again later.');
                        }
                    },
                    'json'
                );
            }
        }
    }
} ();


var infobox = function() {
    var cookieName = '__hidden';
    return {
        hide: function(elem) {
            var id = '#' + $(elem).parent().attr('id');
            var hidden = $.cookie(cookieName);
            $.cookie(cookieName, hidden + ',' + id);
            $(elem).parent().hide('slow');
        },
        restoreSettings: function(elem) {
            var hidden = $.cookie(cookieName);
            if (hidden != null && hidden.length > 0) {
                var id = '#' + $(elem).attr('id');
                if (hidden.indexOf(id) > 0) $(elem).hide();
            };
        }
    }
} ();