﻿var TwentyQuestions = {};
TwentyQuestions.Home = {};

var thoughtWatermark = "Think of someone or something...";
var categorytWatermark = "Give them a hint (example: famous politician from the 60s)";
var questionWatermark = "Ask a yes/no question, or guess the answer...";
var startTyping = "Type to find friends...";
var tags = [];


$(document).ready(function () {

    //    if ($.cookie("message")) {
    //        TwentyQuestions.Common.ShowMessageBar($.cookie("message"), 7000);
    //        $.cookie('message', "any_value", { expires: -10 })
    //    }


    //    var msg = TwentyQuestions.Common.GetQueryStringByName("msg");
    //    if (msg != "") {
    //        TwentyQuestions.Common.ShowMessageBar(msg, 7000);
    //        window.history.replaceState(null, '', root);
    //    }

    //    if(document.location.hash == '#new') {
    //        TwentyQuestions.Common.ShowMessageBar("Welcome to 20 Questions! We've just sent you an email to verify your account.", 7000);
    //        document.location.hash='';
    //    }

    if ($('#NewUser').length > 0) {
        TwentyQuestions.Common.ShowMessageBar("Welcome " + $('#NewUser').val() + "! Please check your email to verify your account.", 7000);
    }


    TwentyQuestions.Home.AddWatermarks();
    TwentyQuestions.Home.AddFocusBehavior($('#Thought'));
    TwentyQuestions.Home.AddFocusBehavior($('#Category'));
    TwentyQuestions.Home.AddFocusBehavior($('.question-textbox'));
    TwentyQuestions.Home.AddPrivacyBehavior();
    TwentyQuestions.Home.AddMoreLinkBehaviour();
    TwentyQuestions.Home.AddAddGameBehavior();
    TwentyQuestions.Home.AddToolTips();
    TwentyQuestions.Home.Poll();
    TwentyQuestions.Common.SetupTabs('.tabs-topplayers');
    TwentyQuestions.Common.SetupMenu();
    TwentyQuestions.Home.AddTokenizerInputBehavior();
    TwentyQuestions.Home.AddGameLikersBehavior();
    TwentyQuestions.Home.AddGameRecipientsBehavior();

    if ($('#Thought').length > 0) {
        TwentyQuestions.Home.AddTagBehavior();
    }


    $('#Search').keyup(function (e) {
        if (e.keyCode == 13) {
            $('#SearchButton').click();
            return true;
        }
    });

    $('.slide-out-div').tabSlideOut({
        tabHandle: '.handle',                              //class of the element that will be your tab
        pathToTabImage: root + '/Content/Images/feedback.gif', //path to the image for the tab *required*
        imageHeight: '122px',                               //height of tab image *required*
        imageWidth: '40px',                               //width of tab image *required*    
        tabLocation: 'left',                               //side of screen where tab lives, top, right, bottom, or left
        speed: 400,                                        //speed of animation
        action: 'click',                                   //options: 'click' or 'hover', action to trigger animation
        topPos: '200px',                                   //position from the top
        fixedPosition: false                               //options: true makes it stick(fixed position) on scroll
    })



    getStatus();
});

TwentyQuestions.Home.AddTokenizerInputBehavior = function () {
    var prePopulateItems = { id: 0, name: "Public" };
    var hintText = "<div class='privacy-suggestions'>" +
                        "<h4>Who do you want to play with?</h4>" +
                        "<h5>Start typing your friend's name, enter an email address, or select a list from below.</h5>" + 
                        "<ul>" +
                            "<li><a id='Followers' href='javascript://' onclick='javascript:TwentyQuestions.Common.AddToken(this, \"GameRecipients\", -1, \"Followers\");return false;' class='friend-list'>Followers</a></li>" +
                            "<li><a id='MutualFollowers' href='javascript://' onclick='javascript:TwentyQuestions.Common.AddToken(this, \"GameRecipients\", -2, \"Friends (Mutual Followers)\");return false;' class='friend-list'>Friends (Mutual Followers)</a></li>" +
                        "</ul>" +
                   "</div>";
    var resultsFormatter = function(item){ return "<li class='people-list-item'><div class='tag-avatar'><img src='" + item.icon + "'/></div><div class='person-text'><div class='tag-text-first-line'>" + item.name + "</div><div class='person-text-second-line'>" + item.desc + "</div></div></li>" };
    var tokenFormatter = function (item){ return "<li class='token-public'>" + item.name + "</li>" };
    TwentyQuestions.Common.AddTokenizerInput("GameRecipients", "/Home/TokenizedRecipients", prePopulateItems, hintText, resultsFormatter, tokenFormatter);
};

TwentyQuestions.Home.AddWatermarks = function () {
    $('#Thought').watermark(thoughtWatermark);
    $('#Category').watermark(categorytWatermark);
    $('.question-textbox').watermark(questionWatermark);
    $('#GameRecipients').watermark('Notify your friends/circles...');
};


TwentyQuestions.Home.AddFocusBehavior = function (textbox) {
    textbox.focus(function () {
        if (textbox.attr('id') == 'Thought' || textbox.attr('id') == 'Category') {
            $('#Category').show();
            $('#Play').show();
            $('#SetPrivacy').show();

            if ($('#fb-login').is(':visible')) {
                $('#GamePostOptions').hide();
            } else {
                $('#GamePostOptions').show();
            }
        }

        if ($(this).hasClass('question-textbox')) {
            $(this).siblings().css('display', 'inline-block');

            if ($('#fb-login').is(':visible')) {
                $('.question-post-options').hide();
            } 
        }
    });

    textbox.blur(function () {
        if (($('#Thought').val() == "" || $('#Thought').val() == thoughtWatermark) &&
            ($('#Category').val() == "" || $('#Category').val() == categorytWatermark)) {
            $('#Category').hide();
            $('#Play').hide();
            $('#SetPrivacy').hide();
            $('#GamePostOptions').hide();
        }

        if ($(this).hasClass('question-textbox') && ($(this).val() == "" || $(this).val() == questionWatermark)) {
            $(this).siblings().hide();

            var $questionsBlock = $(this).parent().parent().parent();
            if ($questionsBlock.hasClass('hidden')) {
                $questionsBlock.hide();
            }
        }
    });
};

TwentyQuestions.Home.AddPrivacyBehavior = function () {
    $('#Privacy').click(function (e) {
        e.stopPropagation();
        //Other code if you want to execute anything on panel click.
    });
   

    $('body').click(function (e) {
        if ($(e.target).attr('id') == 'SetPrivacy') {
            $('#Privacy').show();

            $(function () {
                //$("input:radio,input:checkbox").uniform();
            });
        } else {
            if($('.privacy-suggestions').length == 0){
                $('#Privacy').hide();
            }
        }
    });
};

TwentyQuestions.Home.Poll = function () {
    window.setInterval(function () {
        $.ajax({
            type: "GET",
            url: root + "/Home/Poll",
            data: { 'sinceTime': $('#LastUpdatedTime').val() },
            dataType: "json",
            success: function (response) {
                if (response.AnyUpdates) {
                    $('#updatesLink').text(response.Message).css('display', 'inline-block');
                } else {
                    $('#updatesLink').hide();
                }
            },
            error: function (xhr, status, error) {
                //TwentyQuestions.Common.ShowMessageBar(xhr.statusText);
            }
        });
    }, 5000);
};

TwentyQuestions.Home.LoadUpdates = function () {
    $('#updatesLink').html($('#updatesLink').html() + " <img src=\'" + root + "/Content/Images/ajax-loader.gif' border='0' />");
    $.ajax({
        type: "GET",
        url: root + "/Home/Updates",
        data: { 'sinceTime': $('#LastUpdatedTime').val() },
        dataType: "html",
        success: function (response) {
            //remove items on the page that are going to be updated to avoid duplicates
            $.each($(response).find('.game-list-item'), function (index) {
                var id = $(this).attr('id');
                $('#' + id).remove();
            });

            $('#games #game-list').prepend($(response).find('#game-list').html());
            $('#games #updatesLink').hide();
            $('#games #LastUpdatedTime').val($(response).find('#LastUpdatedTime').val());
            TwentyQuestions.Common.SetupMenu();
            $('.question-textbox').watermark(questionWatermark);
            TwentyQuestions.Home.AddFocusBehavior($('.question-textbox'));
            TwentyQuestions.Home.AddGameRecipientsBehavior();
        },
        error: function (xhr, status, error) {
            TwentyQuestions.Common.ShowMessageBar(error);
        }
    });
};

TwentyQuestions.Home.AddTagBehavior = function () {
    $.get(root + "/Home/Tags", function (response) {
        if (response.AnyTags) {
            tags = response.Tags;
        }
    });

    $("#Category").bind("keydown", function (event) {
        if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
            event.preventDefault();
        }
    }).autocomplete({
        minLength: 0,
        source: function (request, response) {
            var term = request.term,
                results = [];
            if (term.indexOf("@") >= 0) {
                term = extractLast(request.term);
                if (term.length > 0) {
                    results = $.ui.autocomplete.filter(tags, term);
                } else {
                    results = [startTyping];
                }
            }
            response(results);
        },
        focus: function () {
            return false;
        },
        select: function (event, ui) {
            if (ui.item.value !== startTyping) {
                var terms = this.value.split(' ');
                terms.pop();
                terms.push("@" + ui.item.value);
                this.value = terms.join(" ");
            }
            return false;
        }
    }).data("autocomplete")._renderItem = function (ul, item) {
        if (item.label != startTyping) {
            return $("<li class='people-list-item'></li>")
				.data("item.autocomplete", item)
				.append("<a><div class='tag-avatar'><img src='" + item.icon + "'/></div><div class='person-text'><div class='tag-text-first-line'>" + item.label + "</div><div class='person-text-second-line'>" + item.desc + "</div></div></a>")
				.appendTo(ul);
        } else {
            return $("<li></li>")
				.data("item.autocomplete", item)
				.append("<a>" + item.label + "</a>")
				.appendTo(ul);
        }
    };
};

TwentyQuestions.Home.OnAskOrGuessClick = function (sender) {
    var $questionsBlock = $(sender).parent().parent().parent().parent().find('.questions-block').show();
    $questionsBlock.find('#QuestionText').focus();
    $.scrollTo({ top: '+=100px', left: '+=0px' }, 400);
};

TwentyQuestions.Home.ShowAllQuestions = function (sender, gameId) {
    $(sender).next().show().html("<img src=\'" + root + "/Content/Images/ajax-loader.gif' border='0' />");
    $.ajax({
        type: "POST",
        url: root + "/Home/GetQuestions",
        data: { 'gameId': gameId },
        dataType: "html",
        success: function (result) {
            var $questionsList = $(sender).parent().next();
            $questionsList.html(result);
            $questionsList.show();
            $(sender).parent().hide();
        },
        error: function (xhr, status, error) {
            TwentyQuestions.Common.ShowMessageBar(error);
        }
    });
};


TwentyQuestions.Home.AddMoreLinkBehaviour = function () {
    $('#moreLink').live("click", function () {
        $(this).html("<img src=\'" + root + "/Content/Images/ajax-loader.gif' border='0' />");
        $.get($(this).attr("href"), function (response) {
            $('#games #game-list').append($(response).find('#game-list').html());
            $('#games #moreLink').replaceWith($("#moreLink", response));
            $('.question-textbox').watermark(questionWatermark);
            TwentyQuestions.Home.AddFocusBehavior($('.question-textbox'));
            TwentyQuestions.Common.SetupMenu();
            TwentyQuestions.Home.AddGameLikersBehavior();
            TwentyQuestions.Home.AddGameRecipientsBehavior();
        });
        return false;
    });
};

TwentyQuestions.Home.LikeGame = function (sender, gameId) {

    $.ajax({
        type: "POST",
        url: root + "/Home/LikeGame",
        data: { 'gameId': gameId },
        dataType: "html",
        success: function (response) {
            $(sender).parent()
            if ($(sender).parent().parent().parent().next().attr("class") == "questions-block") {
                $(sender).parent().parent().parent().next().html($(response).html());
            } else {
                if ($(sender).parent().parent().parent().next().hasClass("questions-block")) {
                    $(sender).parent().parent().parent().next().remove();
                }
                $(sender).parent().parent().parent().after(response);
            }

            $('.question-textbox').watermark(questionWatermark);
            TwentyQuestions.Home.AddFocusBehavior($('.question-textbox'));
            TwentyQuestions.Home.AddGameLikersBehavior();

            $(sender).text("Unlike");
            $(sender).removeAttr("onclick");
            $(sender).unbind('click');
            $(sender).bind('click', function () {
                TwentyQuestions.Home.UnlikeGame(sender, gameId);
                return false; 
            });

            //var postid = postToWall("A new game was started on 20questions.com", "Guess what", "http://20questions.com");
            like(1);
        },
        error: function (xhr, status, error) {
            TwentyQuestions.Common.ShowMessageBar(error);
        }
    });
};

TwentyQuestions.Home.UnlikeGame = function (sender, gameId) {
    $(sender).text("Like");
    $(sender).removeAttr("onclick");
    $(sender).unbind('click');
    $(sender).bind('click', function () {
        TwentyQuestions.Home.LikeGame(sender, gameId);
        return false; // don't follow the link!
    });

    $.ajax({
        type: "POST",
        url: root + "/Home/UnlikeGame",
        data: { 'gameId': gameId },
        dataType: "html",
        success: function (response) {
            $(sender).parent()
            if ($(sender).parent().parent().parent().next().attr("class") == "questions-block") {
                $(sender).parent().parent().parent().next().replaceWith(response); //using replacewWith incase we need to hide the entire questions-block 
            } else {
                if ($(sender).parent().parent().parent().next().hasClass("questions-block")) {
                    $(sender).parent().parent().parent().next().remove();
                }
                $(sender).parent().parent().parent().after(response);
            }

            $('.question-textbox').watermark(questionWatermark);
            TwentyQuestions.Home.AddFocusBehavior($('.question-textbox'));
            TwentyQuestions.Home.AddGameLikersBehavior();
        },
        error: function (xhr, status, error) {
            TwentyQuestions.Common.ShowMessageBar(error);
        }
    });
};

TwentyQuestions.Home.AddAddGameBehavior = function () {
    var form = $("#AddGame");
    form.submit(function (e) {
        if (form.find("#GameRecipients").val().length == 0) {
            TwentyQuestions.Common.ShowMessageBar('You need to select at least one person to play with!');
        } else {
            var data = form.serialize();

            $.ajax({
                type: "POST",
                url: root + "/Home/AddGame",
                data: data,
                dataType: "json",
                success: function (response) {
                    if (response.Success) {
                        var $html = "<li class='game-list-item'>" + response.Html + "</li>";
                        $('#games #game-list').prepend($html).find(':first');
                        $('#games #LastUpdatedTime').val($(response.Html).find('.time').attr('time'));
                        TwentyQuestions.Common.SetupMenu();
                        TwentyQuestions.Home.AddGameRecipientsBehavior();

                        if (response.PostToFacebook) {
                            postToWall(response.Message, response.Name, response.Link);
                        }
                    } else {
                        TwentyQuestions.Common.ShowMessageBar(response.Message);
                    }
                },
                error: function (xhr, status, error) {
                    TwentyQuestions.Common.ShowMessageBar(error);
                }
            });
            $("#Thought").val("").blur();
            $("#Category").val("").blur();
        }
        return false;
    });
};

TwentyQuestions.Home.DeleteGame = function (sender, gameId) {
    $.ajax({
        type: "POST",
        url: root + "/Home/DeleteGame",
        data: { 'gameId': gameId },
        dataType: "html",
        success: function (response) {
            $(sender).parent().parent().parent().parent().fadeOut("slow");
        },
        error: function (xhr, status, error) {
            TwentyQuestions.Common.ShowMessageBar(error);
        }
    });

    return false;
};

TwentyQuestions.Home.AddQuestion = function (sender, isGuess) {
    var form = $(sender).parent();
    var data = form.serialize();

    if (isGuess) {
        data = data + "&IsGuess=true";
    }

    $(sender).addClass("disabled");
    $(sender).attr("disabled", "disabled");

    var url = form.attr('action');
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: "json",
        success: function (response) {
            if (response.Success) {
                var $html = "<li class='question-list-item'>" + response.Html + "</li>";
                form.parent().parent().find("ul").append($html); //add to question list
                form.parent().parent().find("ul").next().hide(); //hide ask/guess div
                form.parent().parent().parent().find(".game-text-second-line").find("ul li:first").hide(); //hide ask/guess link 
                //$('#LastUpdatedTime').val(GetTimeNow());  
                $('#games #LastUpdatedTime').val($(response.Html).find('.time').attr('time'));

                if (response.PostToFacebook) {
                    postToWall(response.Message, response.Name, response.Link);
                }

            } else {
                TwentyQuestions.Common.ShowMessageBar(response.Message);
            }

            $(sender).removeAttr('disabled');
            $(sender).removeClass("disabled");

            //remove timing out icon
            $(sender).parent().parent().parent().parent().find('.timing-out').fadeOut("slow");
        },
        error: function (xhr, status, error) {
            TwentyQuestions.Common.ShowMessageBar(error);
            $(sender).removeAttr('disabled');
            $(sender).removeClass("disabled");
        }
    });
    return false;
};

TwentyQuestions.Home.AnswerQuestion = function (sender) {
    var url = sender.href;
    $.ajax({
        type: "GET",
        url: url,
        dataType: "json",
        success: function (response) {
            if (response.Success) {
                //remove time remaining icon
                $(sender).parent().parent().parent().parent().parent().parent().find('.timing-out').fadeOut("slow"); 

                var $html = "<li class='question-list-item'>" + response.Html + "</li>";
                $(sender).parent().parent().parent().replaceWith($html); //replace question with answered question
                $('#games #LastUpdatedTime').val($(response.Html).find('.time').attr('time'));                
            } else {
                TwentyQuestions.Common.ShowMessageBar(response.Message);
            }
        },
        error: function (xhr, status, error) {
            TwentyQuestions.Common.ShowMessageBar(error);
        }
    });
    return false;
};

TwentyQuestions.Home.ExtendGame = function (sender) {
    var url = sender.href;
    $.ajax({
        type: "GET",
        url: url,
        dataType: "json",
        success: function (response) {
            TwentyQuestions.Common.ShowMessageBar(response);
            $(sender).parent().hide();

            //remove timing out icon
            $(sender).parent().parent().parent().find('.timing-out').fadeOut("slow");
        },
        error: function (xhr, status, error) {
            TwentyQuestions.Common.ShowMessageBar(error);
        }
    });
    return false;
};

TwentyQuestions.Home.EndGame = function (sender) {
    var url = sender.href;
    $.ajax({
        type: "GET",
        url: url,
        dataType: "json",
        success: function (response) {
            TwentyQuestions.Common.ShowMessageBar(response);
            $(sender).parent().hide();

            //remove timing out icon
            $(sender).parent().parent().parent().find('.timing-out').fadeOut("slow");
        },
        error: function (xhr, status, error) {
            TwentyQuestions.Common.ShowMessageBar(error);
        }
    });
    return false;
};


TwentyQuestions.Home.AddToolTips = function () {
    $('#Thought').tipTip({ activation: "focus", defaultPosition: "left" });
    $('#Category').tipTip({ activation: "focus", defaultPosition: "left" });

    $('#SetPrivacy').tipTip({ defaultPosition: "top" });
    $('.link-gamerules-frontpage').tipTip({ activation: "hover", defaultPosition: "top" });
};


TwentyQuestions.Home.ShareByEmail = function () {
    var form = $("#ShareByEmail");
    form.submit(function (e) {
        var data = form.serialize();
        $.ajax({
            type: "POST",
            url: root + "/Home/ShareByEmail",
            data: data,
            dataType: "json",
            success: function (response) {
                TwentyQuestions.Common.ShowMessageBar(response);
            },
            error: function (xhr, status, error) {
                TwentyQuestions.Common.ShowMessageBar(error);
            }
        });

        $.fancybox.close()
        return false;
    });
};

TwentyQuestions.Home.AddGameLikersBehavior = function () {
    $(".game-likers").fancybox({
        'hideOnContentClick': false,
        'autoDimensions': true,
        'titleShow': false
    });

    $(".share-email").fancybox({
        'hideOnContentClick': false,
        'autoDimensions': true,
        'titleShow': false,
        'onComplete': function () {
            $('#RecipientEmailAddress').watermark("Recipient's email address");
            $('#RecipientEmailAddress').tipTip({ activation: "focus", defaultPosition: "right" });
            $('#Subject').tipTip({ activation: "focus", defaultPosition: "right" });
        }
    });
};

TwentyQuestions.Home.AddGameRecipientsBehavior = function () {
    $(".game-recipients").fancybox({
        'hideOnContentClick': false,
        'autoDimensions': true,
        'titleShow': false,
        'onComplete': function () {
            TwentyQuestions.Common.SetupTabs('.modal-people-column');
        }
    });   
};



//helper functions
function split(val) {
    return val.split(/@\s*/);
}

function extractLast(term) {
    return split(term).pop();
}

