﻿//Some code to prompt the user to use his transportation if availble
$.expr[':'].linksToTravel = function (obj) {
    return (obj.href.indexOf("Travel.aspx") > -1);
};

$(function () {
    $("#" + BGIMG_CLIENTID).attr('style', '');
    var theWindow = $(window),
	            $bg = $("#" + BGIMG_CLIENTID),
	            aspectRatio = $bg.width() / $bg.height();

    function resizeBg() {

        if ((theWindow.width() / theWindow.height()) < aspectRatio) {
            $bg
		    	.removeClass()
		    	.addClass('bgheight')
		    	.addClass('uxBigBgImg')
                .css('left', parseInt((theWindow.width() - $bg.width()) / 2));
        } else {
            $bg
		    	.removeClass()
		    	.addClass('bgwidth')
		    	.addClass('uxBigBgImg');
        }
    }

    theWindow.resize(function () {
        resizeBg();
    }).trigger("resize");

    $('a:linksToTravel').unbind('click').click(function () { SuggestUsingTransportation(this.href.split("=")[1], $(this).html(), false); return false; });

});

function SuggestUsingTransportation(sid, streetName, confirmTravelAsWell) {
    var c = GlobalFindObjectWithCharacterIdInArray(CURRENT_CHARACTER_ID, LAST_PEOPLE)
    if (!c.IsInVehicle) {
        var v = null;
        var vehiclesString = "";
        for (var i = 0; i < LAST_VEHICLES.length; i++) {
            v = LAST_VEHICLES[i];
            if (v.ThisPlayerOwnsOrControlsThis) {
                vehiclesString += "<div class='a useVehicle' data-vid='" + v.ItemRealId + "'>Use my " + v.Title + "</div><br />"
            }
        }
        if (vehiclesString != "") {
            var msg = "You are not in a vehicle.<br/><br/>";
            msg += "If you use a vehicle your journey will be quicker.<br/><br/>";
            msg += "<div style='margin-left:20px;'>" + vehiclesString + "</div>";
            GlobalShowGenericDialog("Walk to " + streetName + "?", msg, { "No thanks, I'll walk": function () { window.location = 'Travel.aspx?sid=' + sid; } });
            $('.useVehicle').click(function () {
                VEHICLE_ID_OF_INTEREST = $(this).attr('data-vid');
                EnterVehicle(function () { window.location = 'Travel.aspx?sid=' + sid; }, false);
            });
            return;
        }
    } 
    if (confirmTravelAsWell) {
        GlobalConfirmTravelDialog(sid, streetName);
    } else {
        window.location = 'Travel.aspx?sid=' + sid;
    }
    
}


function GlobalAddEvent(onclickScript) {
    return function (evt) { var tmpFunc = new Function(onclickScript); tmpFunc(); }
}

function GlobalGetPageName() {
    var sPath = window.location.pathname;
    //var sPage = sPath.substring(sPath.lastIndexOf('\\') + 1);
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
    return sPage;
}

function GlobalKeyValuePair(key, value) {
    this.key = key;
    this.value = value;
    this.Key = key;
    this.Value = value;
}

function GlobalGetRandom(min, max) {
    var randomNum = Math.random() * (max - min);
    return (Math.round(randomNum) + min);
}
function GlobalFakeAjax(d) {
    this.d = d;
}
function GlobalDicToString(dic) {
    var str = "";
    for (var i in dic) {
        str += dic[i].key;
        str += ":";
        str += dic[i].value;
        str += ";";
    }
    return str;
}
function GlobalToFloat(num) {
    num = num.toString().replace(/,/gi, "");
    num = num.toString().replace(/\$/gi, "");
    num = num.toString().replace(/£/gi, "");
    return parseFloat(num);
}
function GlobalToMoney(val) {
    return GlobalAddCommas(parseFloat(val).toFixed(2));
}
function GlobalUpdateCash(dbl) {
    $('#' + UxLoginCashClientId).html(GlobalAddCommas(parseFloat(dbl).toFixed(2)));
    /*
    var original = parseFloat($('#' + UxLoginCashClientId).html().replace(/,/gi, ""));
    var dif = dbl - original;
    var amount = 0;
    var increment = 100;
    var limit = 11;

    if (dif > 500 || dif < -500) {
    for (var i = 1; i < limit; i++) {
    amount = original + parseInt((dif / 100) * i);
    setTimeout("$('#" + UxLoginCashClientId + "').html('" + GlobalAddCommas(amount.toFixed(2)) + "');", i * increment);
    }
    }
    
    dbl = dbl + '';
    dbl = dbl.replace(/,/gi, "");
    dbl = parseFloat(dbl);
    if (dif > 500 || dif < -500) {
    setTimeout("$('#" + UxLoginCashClientId + "').html('" + GlobalAddCommas(dbl.toFixed(2)) + "');", limit * increment);
    } else {
    $('#' + UxLoginCashClientId).html(GlobalAddCommas(dbl.toFixed(2)));
    }*/
}
function GlobalGetCash() {
    return parseFloat($('#' + UxLoginCashClientId).html().replace(/,/gi, ""));
}
function GlobalUpdateBank(dbl) {
    dbl = dbl + '';
    dbl = dbl.replace(/,/gi, "");
    dbl = parseFloat(dbl);
    $('#' + UxLoginBankClientId + ',.myBank').html(GlobalAddCommas(dbl.toFixed(2)));
}
function GlobalGetBank() {
    return parseFloat($('#' + UxLoginBankClientId).html().replace(/,/gi, ""));
}
function GlobalAddCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
function GlobalToNumber(dbl) {
    return GlobalAddCommas(dbl.toFixed(2));
}
function GlobalConfirmTravelDialog(streetId, streetName) {
    //On login control.
    $('#mapAndPanoConfirmStreetName').html(streetName);
    $('#ConfirmTravelRequest').dialog({ modal: true,
        buttons: {
            No: function () {
                $(this).dialog('close');
            },
            Yes: function () {
                window.location = "Travel.aspx?sid=" + streetId;
            }
        }
    });
}
function GlobalFindObjectWithItemRealIdInArray(ItemRealId, arr) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].ItemRealId == ItemRealId) {
            return arr[i];
        }
    }
    return null;
}
function GlobalFindObjectWithStreetIdInArray(StreetId, arr) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].streetId == StreetId) {
            return arr[i];
        }
    }
    return null;
}
function GlobalFindObjectWithBuildingIdInArray(BuildingRealID, arr) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].BuildingRealId == BuildingRealID) {
            return arr[i];
        }
    }
    return null;
}
function GlobalFindObjectWithCharacterIdInArray(CharacterId, arr) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].CharacterId == CharacterId) {
            return arr[i];
        }
    }
    return null;
}
function GlobalAddSocial(friendId, GroupID) {
    $.ajax({ type: "POST", url: "WebService.asmx/AddSocial", contentType: "application/json; charset=utf-8", data: "{'targetCharacterID':" + friendId + ",'GroupID':" + GroupID + "}", dataType: "json", success: GlobalSocialAdditionAttempted, error: GlobalAjaxError });
}
function GlobalSocialAdditionAttempted(response) {
    alert(response.d);
}
function GlobalAjaxError(response) {
    debugger;
}
$(function () {
    $('.uxItemOfInterest').hover(
            function () {
                $(this).children('a').fadeIn();
                $(this).children('.fadeable').fadeIn();
            },
            function () {
                $(this).children('a').fadeOut();
                $(this).children('.fadeable').fadeOut();
            }
        );
});

function GlobalPad(str, prefix, finalLength) {
    while ((str + '').length < finalLength) {
        str = prefix + str;
    }
    return str;
}
function GlobalGetUrlVar(key) {
    var x = location.search.substr(1).split("&");
    for (var i = 0; i < x.length; i++) {
        var y = x[i].split("=");
        if (y[0] == key) { return y[1]; }
    }
    return "";
}


var ETA_SECONDS_LEFT = null;

function UpdateTravelCountdown() {
    if ($('.UxEtaSecondsLeft').length == 0) {
        clearInterval(TRAVEL_TIMER);
    }
    if (ETA_SECONDS_LEFT == null) {
        ETA_SECONDS_LEFT = parseInt($($('.UxEtaSecondsLeft')[0]).text());
    }

    if (ETA_SECONDS_LEFT < 1) {
        window.location = 'Street.aspx';
        clearInterval(TRAVEL_TIMER);
    } else {
        ETA_SECONDS_LEFT--;
        var hr = '';
        var min = '';
        var sec = '';

        hr = ETA_SECONDS_LEFT / 3600;
        min = (ETA_SECONDS_LEFT % 3600) / 60;
        sec = ((ETA_SECONDS_LEFT % 3600) % 60);

        hr = GlobalPad(parseInt(hr), '0', 2);
        min = GlobalPad(parseInt(min), '0', 2);
        sec = GlobalPad(parseInt(sec), '0', 2);

        $('.UxEtaSecondsLeft').text(hr + ':' + min + ':' + sec);
    }
}

var TRAVEL_TIMER = setInterval("UpdateTravelCountdown();", 1000);

function GlobalToHtml(str) {
    return str.replace(/&lt;/ig, "<").replace(/&gt;/ig, ">").replace(/&#39;/ig, "'");
}

function GlobalShowGenericDialog(Title, Message, Buttons) {
    $('#UxGenericModal').attr('title', Title);
    $('#ui-dialog-title-UxGenericModal').html(Title);
    $('#UxGenericModal').html(Message);
    $('#UxConfirmPayment').dialog('close');
    if (typeof Buttons === "undefined") {
        $('#UxGenericModal').dialog({ close: function () { $('#UxGenericModal').attr('title', ''); $('#UxGenericModal').html(''); }, modal: true, width: 400, buttons: { Ok: function () { $(this).dialog('close'); } }
        });
    } else {
        $('#UxGenericModal').dialog({ close: function () { $('#UxGenericModal').attr('title', ''); $('#UxGenericModal').html(''); }, modal: true, width: 400, buttons: Buttons });
    }
}

function GlobalBlockUi() {
    $('#UxUiBlocker').height($(window).height()).width($(window).width()).show().css({ 'background': 'black', 'top': '0', 'left': '0', 'position': 'fixed', 'opacity': '.50', 'filter': 'Alpha(Opacity=50)' });
}
function GlobalUnblockUi() {
    $('#UxUiBlocker').height(1).width(1).hide();
}



function GlobalCollectBuildingIncome(brid) {
    $.ajax({ type: "POST", url: "WebService.asmx/GlobalCollectBuildingIncome", contentType: "application/json; charset=utf-8", data: "{'brid':" + brid + "}", dataType: "json", success: function (result) { GlobalBuildingIncomeCollected(result, brid); }, error: GlobalAjaxError });
}
function GlobalBuildingIncomeCollected(r,brid) {
    var parts = r.d.split('|');
    GlobalShowGenericDialog(parts[0], parts[1]);
    SlideItUp();
    UpdateViewstate(function () { ShowBuildingDetail(brid) });
}
function GlobalSellBuilding(brid) {
    var b = GlobalFindObjectWithBuildingIdInArray(brid, LAST_BUILDINGS);
    if (b != null && b.OwnedByCurrentCharacter==true) {
        GlobalShowGenericDialog(
            "Sell Building?",
            "Do you want to sell this building for<br /><br /><h2 style='color:#0D0;text-align:center;'>+$" + GlobalAddCommas(b.SalePrice) + "</h2>",
            { no: function () { $(this).dialog('close'); }, yes: function () { SellBuilding(brid); $(this).dialog('close'); } }
            );
    }
}
function SellBuilding(brid) {
    $.ajax({ type: "POST", url: "WebService.asmx/SellBuilding", contentType: "application/json; charset=utf-8", data: "{'brid':" + brid + "}", dataType: "json",
        success: function (result) {
            SlideItUp();
            UpdateViewstate(function () { ShowBuildingDetail(brid) });
        }, error: GlobalAjaxError
    });
}
