﻿function setTimeZoneCookie() {
    var offset = new Date().getTimezoneOffset();
    createCookie('tzos', offset, 1);
}

function createCookie(c_name, value, days) {
    var expires = "";

    if (days && days > 0) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    document.cookie = c_name + "=" + value + expires + "; path=/";
}

function delCookie(c_name) {
    createCookie(c_name, "", -1);
}

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

function setGrowlDefaults(imgName) {
    $.blockUI.defaults.growlCSS = {
        width: '350px',
        top: '50%',
        left: '50%',
        right: '',
        border: 'none',
        padding: '5px',
        opacity: 0.6,
        cursor: 'default',
        color: '#fff',
        '-webkit-border-radius': '10px',
        '-moz-border-radius': '10px',
        'border-radius': '10px',
        'height': '100px',
        'margin-top': '-50px',
        'margin-left': '-175px',
        'background': '#000 url(' + imgPath + imgName + ')  no-repeat 10px 10px'
    };
}

function growlAlert(msgType, mainMessage, subMessage) {
    var img;
    var timeOut = 4000;

    switch (msgType.toLowerCase()) {
        case "success":
            img = 'Symbols-Tips-icon.png';
            break;
        case "failed":
            img = 'Symbols-Error-icon.png';
            break;
        case "notice":
            img = 'Symbols-Critical-icon.png';
            break;
    }

    setGrowlDefaults(img);
    $.growlUI(mainMessage, subMessage, timeOut);
}

function printSelection(node) {
    var content = document.getElementById(node).innerHTML;
    var pwin = window.open('', 'print_content', 'width=100,height=100');

    pwin.document.open();
    pwin.document.write('<html><body onload="window.print();">' + content + '</body></html>');
    pwin.document.close();

    setTimeout(function () { pwin.close(); }, 1000);
}

function initCustomerDialog() {
    $("#cAccount").dialog({
        autoOpen: false,
        height: 520,
        width: 900,
        zIndex: 9999,
        modal: true,
        open: function (type, data) {
            $(this).parent().appendTo(jQuery("form:first"));
        },
        buttons: {
            "Update": function () {
                $("#btnUpdateAccount").click();
            },
            "Change Password": function () {
                location.href = 'UpdatePassword.aspx';
            },
            Cancel: function () {
                window.location = window.location;
            }
        },
        close: function () { }
    });

    $("#tabs").tabs({
        event: "click"
    });

    $("#platforms").tabs({
        event: "click"
    });
}

function reloadPage() {
    setTimeout(function () { window.location = window.location; }, 4000);
}

function selTeam(tid) {
    try {
        if (confirm('Are you sure?')) {

            $("#hfTeamId").val(tid);
            $("#btnSubmit").click();

            return true;
        }
    }
    catch (Error) { }

    return false;
}

function selectMessage(messageID) {
    document.getElementById('hfMessageID').value = messageID;
}

function detailsSelection(listItem) {
    var items = new Array('Details', 'Players');

    hideAllListItems(items);
    selectItem(listItem);
}

function detailsTeamSelection(listItem) {
    var items = new Array('Details', 'Players');

    hideAllListItems(items);
    selectItem(listItem);
}

function detailsPlayerSelection(listItem) {
    var items = new Array('Details', 'Games', 'Medals', 'Teams');

    hideAllListItems(items);
    selectItem(listItem);
}

function profileViewSelect(listItem) {
    var items = new Array('Wall', 'Challenges', 'PlayedChallenges');

    hideAllListItems(items);
    selectItem(listItem);
}

//function messageMenuSelect(item) {
//    switch (item) {
//        case "Inbox":
//            document.getElementById('linkInbox').className = 'selected';
//            document.getElementById('linkSentItems').className = '';
//            break;
//        case "SentItems":
//            document.getElementById('linkInbox').className = '';
//            document.getElementById('linkSentItems').className = 'selected';
//            break;
//    }
//}

function menuTeamManageSelection(listItem) {
    var items = new Array('MyTeams', 'CreateTeam', 'TeamPlayers', 'AllPlayers');

    hideAllListItems(items);
    selectItem(listItem);
}

function hideAllListItems(arr) {
    try {
        for (var i = 0; i < arr.length; i++) {

            if (document.getElementById('ph' + arr[i]))
                document.getElementById('ph' + arr[i]).style.display = 'none';

            if (document.getElementById('tab' + arr[i]))
                document.getElementById('tab' + arr[i]).className = '';
        }
    }
    catch (Error) { alert(Error); }
}

function selectItem(item) {
    try {
        if (document.getElementById('ph' + item))
            document.getElementById('ph' + item).style.display = '';
        if (document.getElementById('tab' + item))
            document.getElementById('tab' + item).className = 'selected';
    }
    catch (Error) { alert(Error); }
}

function Rollover(ctrl) {
    try {
        ctrl.src = ctrl.src.replace('_off', '_on');
    }
    catch (Error) { }
}

function Rollout(ctrl) {
    try {
        ctrl.src = ctrl.src.replace('_on', '_off');
    }
    catch (Error) { }
}

//function createChallenge(cid, returnMsg, inviteOnly, platform) {
//    switch (parseInt(cid)) {
//        case 0:
//            growlAlert('failed', 'Sorry', returnMsg);
//            break;
//        default:
//            var msg = 'Your challenge was successfully created.';
//            if (inviteOnly.toLowerCase() != "false")
//                msg += '\nA message has been sent to you opponent.';

//            growlAlert('success', 'Thank you', msg);
//            setTimeout(function () { window.location = 'ChallengeOverview.aspx?platform=' + platform; }, 4000);
//            break;
//    }
//}

function updateGamerTag(returnMsg) {
    switch (returnMsg.toLowerCase()) {
        case "ok":
            growlAlert('success', 'Thank you', 'Your GamerTag was successfully updated.');
            break;
        default:
            growlAlert('failed', 'Sorry', returnMsg);
            break;
    }
}

function addWallComment(returnMsg, wallType) {
    switch (returnMsg.toLowerCase()) {
        case "ok":
            growlAlert('success', 'Thank you', 'Your comment was successfully added.');
            break;
        default:
            growlAlert('failed', 'Sorry', returnMsg);
            break;
    }
}

function deleteWallComment(returnMsg) {
    switch (returnMsg.toLowerCase()) {
        case "ok":
            growlAlert('success', 'Thank you', 'Wall comment was successfully deleted.');
            break;
        default:
            growlAlert('failed', 'Sorry', returnMsg);
            break;
    }
}

//function toggleRightCol() {
//    try {
//        var ct = document.getElementById('profileContent_ddlChallengeType').options[document.getElementById('profileContent_ddlChallengeType').selectedIndex].value;
//        var g = document.getElementById('profileContent_ddlGames').options[document.getElementById('profileContent_ddlGames').selectedIndex].value;
//        var f = document.getElementById('profileContent_ddlFormats').options[document.getElementById('profileContent_ddlFormats').selectedIndex].value;

//        var p = document.getElementById('phChallengePlayer');
//        var t = document.getElementById('phChallengeTeam');

//        p.style.display = 'none';
//        t.style.display = 'none';

//        if (ct == 2) {
//            if (g > 0 && f > 0) {
//                if (f == 1)
//                    p.style.display = '';
//                else
//                    t.style.display = '';
//            }
//        }
//    }
//    catch (Error) { }
//}

function togglePlatform(PlatformID) {
    var divWindows = document.getElementById('divWindows');
    var divXbox360 = document.getElementById('divXbox360');
    var divPS3 = document.getElementById('divPS3');
    var divArcade = document.getElementById('divArcade');

    try {
        divWindows.className = 'platform windows';
        divXbox360.className = 'platform xbox360';

        divPS3.className = 'platform ps3';
        divArcade.className = 'platform arcade';
        switch (PlatformID) {
            case 1:
                divWindows.className = 'platform platform_hover windows';
                break;
            case 2:
                divXbox360.className = 'platform platform_hover xbox360';
                break;
            case 3:
                divPS3.className = 'platform platform_hover ps3';
                break;
            case 5:
                divArcade.className = 'platform platform_hover arcade';
        }
    }
    catch (Error) { }
}

function ShowProfile(val) {
    try {
        var challengerID = $("#hfChallengerID").val();
        var challengerName = $("#txtChallenger").val();
        var opponentType = $("#hfOpponentType").val();
        var opponentID = $("#hfOpponentID").val();
        var opponentName = $("#txtOpponentAccountID").val();
        var url;

        if (opponentType.length > 0) {
            if (val == 1) {
                switch (opponentType) {
                    case "player":
                        url = 'PlayerProfile/' + challengerName;
                        break;
                    case "team":
                        url = 'TeamProfile/' + challengerName;
                        break;
                }
            }
            else if (val == 2 && opponentID.length > 0) {
                switch (opponentType) {
                    case "player":
                        url = 'PlayerProfile/' + opponentName;
                        break;
                    case "team":
                        url = 'TeamProfile/' + opponentName;
                        break;
                }
            }

            location.href = url;
        }
    }
    catch (Error) { }
}

function validateInputNumeric(ctrl) {
    var num = parseFloat(ctrl.value);

    ctrl.value = num > 0 ? num : '';
}

function setprizePoolAmount(ctrl) {
    var challengeAmount = parseFloat(ctrl.value);
    var prizePoolAmount = 0;
    var m = 0.9;

    if (challengeAmount != NaN && challengeAmount > 0)
        prizePoolAmount = (challengeAmount * 2) * m;

    ctrl.value = challengeAmount > 0 ? challengeAmount : '';
    document.getElementById('txtPrizePool').value = prizePoolAmount > 0 ? prizePoolAmount.toFixed(2) : '0.00';
}

function submitMsg(status, url) {
    switch (status.toLowerCase()) {
        case "ok":
            growlAlert('success', '', 'Your message was successfully sent');
            setTimeout(function () { location.href = url; }, 4000);
            break;
        default:
            growlAlert('failed', 'Sorry', status);
            break;
    }
}

function deleteMsg(status) {
    switch (status.toLowerCase()) {
        case "ok":
            growlAlert('success', '', 'Message was deleted successfully');
            setTimeout(function () { location.href = 'Messages.aspx'; }, 4000);
            break;
        default:
            growlAlert('failed', 'Sorry', status);
            break;
    }
}

function joinChallenge(challengeID, status) {
    switch (status.toLowerCase()) {
        case "ok":
            growlAlert('success', '', 'You have successfully joined the challenge.\nPlease click \'Connect\' to connect to the game server.');
            break;
        default:
            growlAlert('failed', 'Sorry', status);
            break;
    }
}

function cancelChallenge(challengeID, status) {
    switch (status.toLowerCase()) {
        case "ok":
            growlAlert('success', '', 'You have successfully cancelled challenge #' + challengeID + '.\nYour buy-In was refunded to your account.');
            reloadPage();
            break;
        default:
            growlAlert('failed', 'Sorry', status);
            break;
    }
}

function createTeam(status, tid) {
    switch (status.toLowerCase()) {
        case "ok":
            growlAlert('success', 'Thank you', 'Your team was successfully created.\You will be redirected to the Team Management Page');
            setTimeout(function () { window.location = window.location.toString().split('#')[0] + '?tid=' + tid; }, 4000);
            break;
        default:
            growlAlert('failed', 'Sorry', status);
            break;
    }
}

function updateTeam(status) {
    switch (status.toLowerCase()) {
        case "ok":
            growlAlert('success', 'Thank you', 'Your team was successfully updated.');
            reloadPage();
            break;
        default:
            growlAlert('failed', 'Sorry', status);
            break;
    }
}

function uploadMsg(filename, status) {
    switch (status.toLowerCase()) {
        case "ok":
            growlAlert('success', 'Thank you', 'Your team logo was successfully uploaded.');
            document.getElementById('txtLogo').value = filename;
            document.getElementById('phUploadLogo').style.display = 'none';
            document.getElementById('phLogoFileName').style.display = '';
            break;
        default:
            growlAlert('failed', 'Sorry', status);
            break;
    }
}

function uploadFile(fileType, filename, status) {
    switch (status.toLowerCase()) {
        case "ok":
            var type, msg;
            switch (fileType.toLowerCase()) {
                case "avatar": type = "Avatar was"; break;
                case "photoid": type = "Photo ID was "; break;
                case "addressverify": type = "Address Verification Details were"; break;
            }

            msg = 'Your ' + type + ' successfully uploaded.';

            growlAlert('success', 'Thank you', msg);
            reloadPage();
            break;
        default:
            growlAlert('failed', 'Sorry', status);
            break;
    }
}

function uploadFeaturedPicMsg(filename, status) {
    switch (status.toLowerCase()) {
        case "ok":
            growlAlert('success', 'Thank you', 'Your Game Face was successfully uploaded.');
            reloadPage();
            break;
        default:
            growlAlert('failed', 'Sorry', status);
            break;
    }
}

function challengeConfirmResult(approvalType, approvalResult, filename, uploadStatus) {
    var msg = '';

    if (filename.length > 0) {
        if (uploadStatus.toLowerCase() == "ok")
            msg = 'Your screenshot was uploaded successfully.';
        else
            msg = uploadStatus;
    }

    switch (approvalResult.toLowerCase()) {
        case "ok":
            growlAlert('success', 'Thank you', approvalResult + '<br/>' + msg);
            reloadPage();
            break;
        default:
            growlAlert('failed', 'Sorry', approvalResult + '<br/>' + msg);
            break;
    }
}

function acceptOpenChallenge(status) {
    switch (status.toLowerCase()) {
        case "ok":
            growlAlert('success', 'Thank you', 'You have successfully accepted the challenge.');
            reloadPage();
            break;
        default:
            growlAlert('failed', 'Sorry', status);
            break;
    }
}

function updFriend(status) {
    switch (status.toLowerCase()) {
        case "ok":
            growlAlert('success', 'Thank you', 'You have successfully removed the selected player from your friends-list.');
            reloadPage();
            break;
        default:
            growlAlert('failed', 'Sorry', status);
            break;
    }
}

function updateChallengeStart(status, msg) {
    switch (status) {
        case "None":
            if (msg.length == 0)
                msg = 'An error occurred. Please try again.';
            growlAlert('failed', 'Sorry', msg);
            break;
        case "ChallengerApproved":
        case "OpponentApproved":
            growlAlert('success', 'Thank you', 'Your suggested Match Start has been submitted.<br/>Please wait for your opponent to approve the suggested time.');
            reloadPage();
            break;
        default:
            growlAlert('success', 'Thank you', 'Challenge has been accepted.<br/>Both sides have agreed the Match Start');
            reloadPage();
            break;
    }
}

function isNumeric(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

function fundTeam(amountCtrl, teamName) {

    var amount = document.getElementById(amountCtrl).value;

    if (isNumeric(amount) && amount > 0)
        return confirm('You are about to transfer €' + amount + ' to "' + teamName + '" do you wish to proceed?');

    alert('Amount is not valid!\nPlease try again.');
    return false;
}

function fundTeamMsg(returnMsg) {
    switch (returnMsg.toLowerCase()) {
        case 'ok':
            growlAlert('success', 'Thank you', 'Your transfer was successful');
            reloadPage();
            break;
        default:
            growlAlert('failed', 'Sorry', returnMsg);
            break;
    }
}

function updateCustomerDetails(returnMsg) {
    switch (returnMsg.toLowerCase()) {
        case 'ok':
            growlAlert('success', 'Thank you', 'Your details were successfully updated.');
            reloadPage();
            break;
        default:
            growlAlert('failed', 'Sorry', returnMsg);
            break;
    }
}

function joinTourney(returnMsg) {
    switch (returnMsg.toLowerCase()) {
        case "ok":
            growlAlert('success', 'Thank you', 'You have successfully joined the tournament.');
            reloadPage();
            break;
        default:
            growlAlert('failed', 'Sorry', returnMsg);
            break;
    }
}

function kickedFromTeam(returnMsg) {
    switch (returnMsg.toLowerCase()) {
        case "ok":
            growlAlert('success', 'Thank you', 'Player was successfully kicked from your team.');
            reloadPage();
            break;
        default:
            growlAlert('failed', 'Sorry', returnMsg);
            break;
    }
}

function addAsFriend(returnMsg, accountId) {
    switch (returnMsg.toLowerCase()) {
        case "ok":
            growlAlert('success', 'Thank you', accountId + ' has been notified of your friend-request.');
            reloadPage();
            break;
        default:
            growlAlert('failed', 'Sorry', returnMsg);
            break;
    }
}

function setGamesArr(arr) {
    myGamesArr = arr.split(';;');
    myGamesArr.sort();
    showMyGames();
}

function addMyGames(platform, game, pid, gid) {
    try {
        var currItem = platform + '||' + game + '||' + pid + '||' + gid;

        if ($.inArray(currItem, myGamesArr) == -1)
            myGamesArr.push(currItem);

        myGamesArr.sort();

        showMyGames();
    }
    catch (Error) { alert(Error); }
}

function removeMyGames(item) {
    try {
        var itemIndex = $.inArray(item, myGamesArr);

        if (itemIndex > -1)
            myGamesArr.splice(itemIndex, 1);

        myGamesArr.sort();

        showMyGames();
    }
    catch (Error) { alert(Error); }
}

function showMyGames() {
    try {
        var txtMyGames = document.getElementById('txtMyGames');
        var hfMyGames = document.getElementById('hfMyGames');
        var platform, game, pid, gid;

        if (txtMyGames != null && hfMyGames != null) {
            txtMyGames.innerHTML = '';
            hfMyGames.value = '';

            for (var i = 0; i < myGamesArr.length; i++) {
                var arr = myGamesArr[i].split('||');

                if (arr.length == 4) {
                    platform = arr[0];
                    game = arr[1];
                    pid = arr[2];
                    gid = arr[3];

                    addCtrl(txtMyGames, myGamesArr[i], platform, game);
                    hfMyGames.value += pid + ',' + gid + ';';
                }
            }
        }
    }
    catch (Error) { alert(Error); }
}

function addCtrl(ctrl, item, platform, game) {
    var pElem = document.createElement("a");
    pElem.setAttribute("href", "javascript:removeMyGames('" + item + "');");
    pElem.setAttribute("class", "bt2");
    pElem.setAttribute("title", "remove this game");

    var cElem = document.createElement("span");
    cElem.setAttribute("style", "font-size:0.8em;");
    cElem.innerHTML = platform + ' ' + game
    pElem.appendChild(cElem);
    ctrl.appendChild(pElem);
}

function setJcoverFlip(ctrl, numgames) {
    $(ctrl).jcoverflip({
        current: Math.floor(numgames / 2),
        beforeCss: function (el, container, offset) {
            return [
              $.jcoverflip.animationElement(el, { left: (container.width() / 2 - 126 - 66 * offset + 20 * offset) + 'px', bottom: '20px' }, {}),
              $.jcoverflip.animationElement(el.find('img'), { width: Math.max(10, 60 - 20 * offset * offset) + 'px' }, {})
            ];
        },
        afterCss: function (el, container, offset) {
            return [
              $.jcoverflip.animationElement(el, { left: (container.width() / 2 + 66 + 66 * offset) + 'px', bottom: '20px' }, {}),
              $.jcoverflip.animationElement(el.find('img'), { width: Math.max(10, 60 - 20 * offset * offset) + 'px' }, {})
            ];
        },
        currentCss: function (el, container) {
            return [
              $.jcoverflip.animationElement(el, { left: (container.width() / 2 - 60) + 'px', bottom: 0 }, {}),
              $.jcoverflip.animationElement(el.find('img'), { width: '120px' }, {})
            ];
        },
        change: function (event, ui) {
            jQuery(ctrl + '_scrollbar').slider('value', ui.to * (100 / (numgames - 1)));
        }
    });

    jQuery(ctrl + '_scrollbar').slider({
        value: 50,
        stop: function (event, ui) {
            if (event.originalEvent) {
                var newVal = Math.round(ui.value / (100 / numgames));
                jQuery(ctrl).jcoverflip('current', newVal);
                jQuery(ctrl + '_scrollbar').slider('value', newVal * (100 / (numgames - 1)));
            }
        }
    });
}

function fbShare(name, link, picture, caption, description) {
    FB.ui({
        method: 'feed',
        name: name,
        link: link,
        picture: picture,
        caption: caption,
        description: description,
        message: document.title
    },
    function (response) {
        if (response && response.post_id)
            growlAlert('success', 'Thank you', 'Your post was successfully published.');
        //        else
        //            growlAlert('failed', 'Sorry', 'An error occurred. Please try again later.');
    });
}

function getPaymentsMatrix(players) {
    switch (players) {
        case 0: return new Array(0, 0);
        case 1: return new Array(100, 0);
        case 2: return new Array(60, 40);
        case 3: return new Array(55, 35, 10);
        case 4: return new Array(50, 30, 14, 6);
        case 5: return new Array(48, 28, 12, 8, 4);
        case 6: return new Array(46, 25, 11, 7, 6, 5);
        case 7: return new Array(46, 25, 11, 7, 5, 4, 2);
        case 8: return new Array(40, 22, 12, 8, 6, 5, 4, 3);
        case 9: return new Array(35, 20, 11, 10, 8, 6, 5, 3, 2);
        case 10: return new Array(34, 19, 11, 10, 8, 6, 5, 3, 2, 2);
        case 11: return new Array(33, 18, 11, 10, 8, 6, 5, 3, 2, 2, 2);
        case 12: return new Array(32, 18, 11, 10, 7, 6, 5, 3, 2, 2, 2, 2);
        case 13: return new Array(31, 16, 10, 9, 8, 6, 5, 4, 3, 2.5, 2, 2, 1.5);
        case 14: return new Array(30, 18, 10, 9, 8, 6, 5, 3, 2, 2, 2, 2, 1.5, 1.5);
        case 15: return new Array(30, 18, 12, 9, 6, 5, 4, 3, 2, 2, 2, 2, 2, 2, 1);
        default: return new Array(30, 18, 12, 9, 6, 5, 4, 3, 2, 2, 2, 2, 1.5, 1.5, 1, 1);
    }
}

function checkGame(msg, link) {
    if (confirm(msg))
        location.href = link;
}

$.fn.preload = function () {
    this.each(function () {
        $('<img/>')[0].src = this;
    });
}

function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
function guid() {
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}
