﻿//EB UI utility functions

var amazonImageUrl = 'http://images.echobazaar.failbettergames.com.s3.amazonaws.com/icons/';

function alertVersion() {
    alert('3');
}

function hideMainContentLoadingImage() {
    $('#mainContentLoading').hide();
}


function changeCharacterDescription() {

    $('#characterDescriptionDisplay').hide();
    $('#characterDescriptionEdit').show();
}

function switchToCharacterDescriptionDisplay() {

    $('#characterDescriptionDisplay').show()
    $('#characterDescriptionEdit').hide()
}


function loadMainContent(url, tab,callback) {
    loadMainContentWithParams(url, { 'cb':1 }, tab,callback);
}
function loadMainContentWithParams(url,params, tab,callback) {
        $('#top_messages').html('');
        $('#mainContentViaAjax').html('');
        $('#mainContentLoading').show();

        var hashlink = null;
        var hashIndex = url.indexOf('#');
        var hashCallback = function () { };

        if (hashIndex >= 0) {
            hashlink = url.substring(hashIndex);
            hashCallback = function () { location.href = hashlink}
            //alert(hashlink);
        }

        if (callback != null) {
            callbackFunction = function () {
                callback();
                hideMainContentLoadingImage();
                hashCallback();
            };
        }
        else 
        {
            callbackFunction = function () {
                hideMainContentLoadingImage();
                hashCallback();
            };
        }
        
        $('#mainContentViaAjax').load(url, params, callbackFunction);
        clearTooltip();

        if (tab == null) {
            url = url.toLowerCase();
            if (url.indexOf('/storylet') > -1)
                tab = "storyTab";
           else if (url.indexOf('/fate') > -1)
                tab = "fateTab";
            else if (url.indexOf('/help') > -1)
                tab = "helpTab";
            else if(url.indexOf('/mystery') > -1)
                tab = "mysteryTab";
            else if (url.indexOf('/fight') > -1)
                tab = "fightTab";
            else if(url.indexOf('/bazaar') > -1)
                tab = "bazaarTab";
            else if (url.indexOf('/me/landing') > -1)
                tab = "homeTab";
            else if (url.indexOf('/me') > -1)
                tab = "meTab";
        }

        $('.selected').removeClass('selected');
        $('#' + tab).addClass('selected');
        return false;
    }


    function countDown(minutesSpanId, SecondsSpanId, reloadAreaId, reloadUrl) {
    
        var minutesSpan= $("#" +minutesSpanId);
        var secondsSpan= $("#" + SecondsSpanId);
        var minutes=parseInt(minutesSpan.text(),10);
        var seconds = parseInt(secondsSpan.text(), 10);
        var loopCallback = function () { countDown(minutesSpanId, SecondsSpanId, reloadAreaId, reloadUrl); };
        
        seconds--;

        if (minutes < 0 || (seconds <= 0 && minutes == 0)) {
            $("#" + reloadAreaId).load(reloadUrl, { cb: 1 });
        }
        else 
        {
            if (seconds <= -1) {
                seconds = 60 + seconds;
                minutes--;
            }

            minutesSpan.text(minutes);

            if (seconds < 10) {
                secondsSpan.text("0" + seconds.toString());
            }
            else
            {
                secondsSpan.text(seconds);
            }
        }

        setTimeout(loopCallback, 1000);
    }

    function showAttackDiv(here, defender) {


        var choice = $('.combatStrategyAttackChoice');

        var links = choice.find("a");

        links.each(function() {
            $(this).unbind('click');
            var strategy = $(this).attr("href");
            $(this).bind('click',
            function() {
                loadMainContentWithParams('/Fight/Attack',
           { 'defenderId': defender, 'strategy': strategy }); return false;

            });

        });
        
        
        choice.hide();
        $(here).parent().parent().after(choice);
        choice.slideDown("fast");
        $.scrollTo(choice);
        
       }

    function showDefenceChoiceDiv(here)
    {

        var choice = $('.combatStrategyDefenceChoice');
        choice.hide();
        $(".kc_player").after(choice);
        choice.slideDown("fast");
        $.scrollTo(choice);
    }
   
   //max length for textareas 
    function imposeMaxLength(Object, MaxLen)
{
    if (Object.value.length <= MaxLen)
        return true;
    else {
        Object.value = Object.value.substring(0, MaxLen)
        return false;
    }
}

function showinspectedCharacterBox() {
    $("#inspectedCharacterBox").dialog('open');
}
function closeInspectedCharacterBox() {
    $("#inspectedCharacterBox").html(' ');
    $("#inspectedCharacterBox").dialog('close');
}


function displayQualityAs(qualityId, newLevel, newXp) {
    $("#" + g.InfoBarQualityLevelIdBase + qualityId).text(newLevel);

    var widthFilled = (newXp / newLevel) * 120;

    $("#" + g.InfoBarQualityBarIdBase + qualityId)
    .animate({width: widthFilled},1000);

}

function setInfoBarEnhancement() {
}

function displayFateChange(change) {

    var newLevel = parseInt($("#" + g.InfoBarFateLevelId).text()) + change;
    $("#" + g.InfoBarFateLevelId).text(newLevel);
}

function decrementRemainingActions() {

    var newDailyLevel = parseInt($("#" + g.InfoBarDailyActionsId).text()) - 1;
    var newCurrentLevel = parseInt($("#" + g.InfoBarCurrentActionsId).text()) - 1;

    setActionsLevel(newCurrentLevel, newDailyLevel)
}

function useUpSecondChanceQuality(qualityId,imageName)
{
var boxId="#" + g.InfoBarAdvantageIdBase + qualityId;
    
    var newLevel = parseInt($(boxId).text(newLevel)) - 1;

    if (newLevel > 0)
        $(boxId).text(newLevel);
    else {
        $(boxId).text('');
        $("#" + g.infoBarQImage + qualityId).html('');
    }
    
}

function displayActionsRefilled() {
    
    var newCurrentLevel = 10;
    var newDailyLevel = parseInt($("#" + g.InfoBarDailyActionsId).text()) + 10;
    
    setActionsLevel(newCurrentLevel, newDailyLevel)
}
function setActionsLevel(newCurrentLevel,newDailyLevel) {

    $("#" + g.InfoBarDailyActionsId).text(newDailyLevel);
    $("#" + g.InfoBarCurrentActionsId).text(newCurrentLevel);

    if(newCurrentLevel == 9 || newCurrentLevel==10 || newCurrentLevel==20){
        $('.content_rhs').load('/Sidebar/GetForCurrentAreaWithWrapper');
    }

    if($("#actionsCandle").length>0)
    {
        if (newCurrentLevel < 10) 
        {
            $(".timer").show();
        }


            $("#actionsCandle").removeClass();
            $("#actionsCandle").addClass("widecandle");
            $("#actionsCandle").addClass("candle_" + newCurrentLevel);
    }


        if ($("#actionsCandle1").length > 0) {
            
            if (newCurrentLevel < 20)
            {
                $(".timer").show();
            }

//            if(newCurrentLevel == 19)
//            {
//                $('.content_rhs').load('/Sidebar/GetForCurrentAreaWithWrapper?justShared=false&inStoryletBox=false');
//            }

        var actionsInBank1 = Math.max(newCurrentLevel - 10,0);
        var actionsInBank2 = Math.min(newCurrentLevel, 10);
        
        $("#actionsCandle1").removeClass();
        $("#actionsCandle1").addClass("firstCandle");
        $("#actionsCandle1").addClass("candle_" + actionsInBank1);

        $("#actionsCandle2").removeClass();
        $("#actionsCandle2").addClass("secondCandle");
        $("#actionsCandle2").addClass("candle_" + actionsInBank2);
    }

}


function beginEvent(eventId) {
        loadMainContentWithParams('/Storylet/Begin', { 'eventid': eventId });

    }


    function canGoToArea(areaId) {

        var bcanGoToArea = false;
        $.ajax({
            type: 'POST',
            url: '/Map/CanGoToArea',
            data: { areaId: areaId },
            success: function (data) {
                bcanGoToArea = data.CanGoToArea;
            },
            error: function () {
                alert('error');
            },
            dataType: 'json',
            async: false

        });

        return bcanGoToArea;
    }

    function travel(areaId, areaImageName, areaFriendlyName) {
        if (canGoToArea(areaId)) {
            displayCurrentArea(areaId, areaImageName, areaFriendlyName);
            loadMainContent('/Map/Move?areaid=' + areaId);
        }
        else {
            alert('Regrettably, only Exceptional Friends may enter ' + areaFriendlyName + '. Visit the Fate page to become an Exceptional Friend!')
        }
    }

    function updatePageAfterStoryletChoice(areaId,areaImageName, areaFriendlyName) {
    displayCurrentArea(areaId,areaImageName, areaFriendlyName);
    }

    function displayCurrentArea(areaId, areaImageName, areaFriendlyName) {
        g.CurrentAreaId = areaId;
    
        $(".area_hdr").css("background-image", "url('" + g.GlobalImageHostingUrl + "headers/" + areaImageName + ".jpg')");
        
        $("#area_hdr_name").text(areaFriendlyName);

   


}

function loadPostcard(areaId) {
$('#postcardWrapper').load('/Content/Postcard?areaid=' + areaId).show();
}
    

function reloadInfoArea() {
    $("#lhs_col").load('/User/InfoSummary', { cb: 1 });

}

function adoptThing(qualityId, showExpanded)
{
    $('#inventory').load('/Me/AdoptThing', {id:qualityId, showExpanded:showExpanded}, reloadInfoArea);
}

function unadoptThing(qualityId, showExpanded)
{
    $('#inventory').load('/Me/UnadoptThing', {id:qualityId, showExpanded:showExpanded}, reloadInfoArea);
}

function loadInventory(expanded){
    if(expanded)
    {
        $('#inventory').load('/Me/InventoryExpanded');
    }
    else
    {
        $('#inventory').load('/Me/InventoryStandard');
    }
}

function reloadInfoAreaNowAndLater() {
    reloadInfoArea();
    setTimeout("reloadInfoAreaNowAndLater()", 120000);
}

function reloadSidebarArea() {
    $(".content_rhs").load('/Sidebar/GetForCurrentAreaWithWrapper', { cb: 1 });

}

function displayActionsRefilledAndReloadSidebarArea() {
    //alert('displayActionsRefilledAndReloadSidebarArea');
    displayActionsRefilled();
    reloadSidebarArea();
}


function fadeMessages() {
    setTimeout(function() {
        $(".fadeable_message").fadeOut('slow');
    }, 3000);
}

function showFateChanged(fateCost) {
    $("#fateUseResponse").slideUp();
    $("#fateUseResponse").slideDown();
    var currentFate = parseInt($("#fateReadoutPoints").text());
    var newFate = currentFate - fateCost;
    if(newFate>0)
        $(".currentfatepoints").text(newFate);
        //if it's not>0, then we won't actually have charged it
    
}

function showMap() {
    if ($("#topMap").is(':visible')) {
        $(".unlockedMapLocation").hide(1);
        $("#topMap").slideUp();
    }
    else {
        
        $('#topMap').load('/Map/Display', {}, function(){
            $("#topMap").slideDown();
            });
    }
}

function bazaarTransactionDone(currentDosh) {
    fadeMessages();
    $(".currentEchoes").text((currentDosh/100).toFixed(2));
    $(".shop_btn").attr("disabled", false);
}
function disableBuySellButtons() {
    $(".shop_btn").attr("disabled", true);
}
function disableChooseBranchBtn() {
    $("#chooseBranchBtn").hide();
    $("#greyedChooseBranchBtn").show();
}

//for char creation and avatar choice pages
function selectAvatarImage(imageName) {
    $(".avatarchoice").removeClass('selectedavatarchoice');
    $("#" + imageName).addClass('selectedavatarchoice');
    $("#avatarchosen").val(imageName);
}

//for char creation and avatar choice pages
function checkAvatarChosen() {
    if ($("#avatarchosen").val() == "") {
        alert('Please click on one of the cameos above.');
        return false;
    }
}



function prepMapLocations() {

    $('input.unlockedMapLocation').die('mouseover').die('mouseout').die('click').live('mouseover', function(event) {

    $("<div id='tooltip'>ss</div>").appendTo(this)
  .css({
  position: "absolute",
      top: event.pageY + 12,
      left: event.pageX + 12
  })

  .show();


}).live('mouseout', function(event) {
$('#tooltip').remove()
    })
    .live('click', function(event) {

    $('#tooltip').remove()

    })
    ;

}

/*quality chooser for mantelpiece/scrapbook*/

function displayQualitiesForSelection(target, action, nature, title) {

    var chooserDialog = $('#quality-chooser');

    $.ajax({
        type: 'POST',
        url: '/Me/GetQualities?nature=' + nature,
        data: {},
        success: function (data) {
            var qualityList = $('<ul class="qualities"></ul>');
            chooserDialog.append($('<h3>' + title + '</h3>')).append(qualityList);

            for (var iQualityIndex = 0; iQualityIndex < data.length; iQualityIndex++) {
                var icon = $('<li>' + data[iQualityIndex].Html + '</li>');
                icon.find('a').attr('href', '/Me/' + action + '?qualityId=' + data[iQualityIndex].Id + '&target=' + target);

                qualityList.append(icon);
            }

            function closeDialog() {
                setTimeout(
                    function () {
                        if (chooserDialog.dialog("isOpen")) {
                            chooserDialog.dialog('close');
                        }
                        chooserDialog.empty();
                        $('#tooltip').hide();
                    },
                    0
                )
            }

            qualityList.find('li a').click(function () {

                $.ajax({
                    type: 'POST',
                    url: $(this).attr('href'),
                    data: {},
                    dataType: 'json',
                    success: function (data) {
                        if (data.Html) {
                            var targetIcon = $('#' + target + ' a');
                            targetIcon.replaceWith(data.Html)
                            //for profile page:

                            var figure = $('#' + target).find('figure');
                            figure.find('h1').text(data.Quality.Name);
                            figure.find('p').text(data.Quality.Description);
                            if (data.Quality.Level > 1) {
                                figure.find('div.slotLevel').text(data.Quality.Level).show();
                            }
                            else {
                                figure.find('div.slotLevel').hide();
                            }

                        }
                        closeDialog();
                    },
                    error: function () {
                        closeDialog();
                    }
                }
                    )
                return false;
            });
            chooserDialog.dialog('open');
            chooserDialog.bind('dialogclose', closeDialog);
        },
        error: function () { alert('error') },
        dataType: 'json'
    });
}

/*external associate UI code*/

var AssociateSource = {
    Twitter: 0,
    Facebook: 1,
    getSource: function (sourceInt) {
        switch (sourceInt) {
            case this.Twitter:
                return 'Twitter';
                break;
            case this.Facebook:
                return 'Facebook';
                break;
        }
    },
    getSourceChar: function (sourceInt) {
        switch (sourceInt) {
            case this.Twitter:
                return 'T';
                break;
            case this.Facebook:
                return 'F';
                break;
        }
    }
};

var setExternalAssociate = function (a, screenName, associateSource) {
    var associate;

    if (screenName) {
        associate = { ScreenName: screenName, Source: associateSource, Name: screenName, ExternalId: screenName };
    }
    else {
        var option = $('#externalTargetId').find('option:selected');

        if (option.length == 0) {
            $('#invitation-text').hide();
            return;
        }

        associate = option[0].associate;
    }


    var thisvipurl = vipurl; //(global variable)

    $('#invitation-text input').attr('checked', true);
    $('.screenname').text(associate.ScreenName);

    thisvipurl = thisvipurl.replace('{0}', AssociateSource.getSourceChar(associate.Source)).replace('{1}', associate.ExternalId);

    $('.vip-url').empty().append($('<a/>').text(thisvipurl).attr('href', thisvipurl));

    switch (associate.Source) {
        case AssociateSource.Twitter:
            $('#throughFacebook').hide();
            $('#throughTwitter').show();
            $('#throughFacebook input').attr('checked', false);
            $('#invitation-text').show();
            break;
        case AssociateSource.Facebook:
            $('#throughFacebook').show();
            $('#throughTwitter').hide();
            $('#throughTwitter input').attr('checked', false);
            $('#invitation-text').show();
            break;
    }

    $('#targetSource').val(AssociateSource.getSource(associate.Source));
    $('#inviteeUsername').text(associate.Name);
};


function initExternalAssociates(theAssociates) {

    for (var iAssociateCount = 0; iAssociateCount < theAssociates.Content.length; iAssociateCount++) {
        var associate = theAssociates.Content[iAssociateCount];
        var source = AssociateSource.getSource(associate.Source);
        var option = $('<option value="' + associate.ExternalId + '">' + associate.Name + '\t \t (through ' + source + ')</option>');
        option[0].associate = associate;

        $('#externalTargetId').append(option);
    }

    $('#invitation-text input').click(
                function () {
                    $(this).parent('span.associate-message').css('opacity', $(this).attr('checked') ? 1 : .5);
                }
            );

    setExternalAssociate();
    $('#externalTargetId').change(setExternalAssociate);

    var submitHandler = function () {
        $('#externalTargetId option').each(function () {
            $(this)[0].associate = null;
        });

        var theData;

        if ($(this).attr('id') == 'inviteTwitter') {
            theData = $($(this).attr('form')).serialize();
            theData += '&inviteTwitter=true'
        }
        else {
            theData = $(this).serialize();
         }
        loadMainContentWithParams('/Storylet/ChooseBranchAndTargetExternal', theData);
        return false;
    };

    $('#externalTargetForm').submit(submitHandler);
    $('#inviteTwitter').click(submitHandler)

}

function closeGeneralDialog() {
    $('#general-dialog').dialog("close");
    $('#general-dialog').empty();
}


function tryOpenTwitterRequestForm() {


    var loadingImg = $('<div style="width:100%;margin:30px auto;display:block;text-align:center">'
                        + '<img src="http://images.echobazaar.failbettergames.com.s3.amazonaws.com/functionalicons/loading_large.gif" alt="Loading..." id="mainContentLoading" style="width:80px;margin:0px auto;display:block;"/>' 
                        + '<p style="margin-top:20px;">If you\'re <em>very</em> popular this may take a little while...</p>'
                    + '</div>'
        
        );

    $('#general-dialog').html(loadingImg);
    $('#general-dialog').dialog('open');
    $('#general-dialog').load('/Friend/TwitterModalInvite');
}

$(".shareBtn").live('click',
        function () {
            var theForm = $(this).attr('form');
            if (theForm) {
                $('#general-dialog').load(
                theForm.action,
                function () {
                    $('#general-dialog').dialog('open');
                }
            );
            }

            return false;
        }
    );

    function shareContent(message, contentClass, contentKey) {
        $('#general-dialog').load(
            '/Content/ShareContent?message=' +  encodeURIComponent(message) + '&contentClass=' + contentClass + '&contentKey=' + contentKey,
            function () {
                $('#general-dialog').dialog('open');
            }
        );
     }

$.ui.dialog.defaults.bgiframe = true; //jquery ui dialog fix for IE
