﻿var _isLobbyPage = false;

var CONFIG = {
        PATHS: {
            WEB: '/',
            WEB_SECURE: '/',
            IMG: _IMG,
            IMG_SECURE: _IMGSECURE,
            IMG_AVATAR: _IMGAVATAR,
            LANDING_IMG: _IMG + 'l/',
            WEBSYNC: _CLP
        },
        ERROR_MESSAGES: {
            // 100+: generic/undetailed errors        
            100: 'An error has occurred.',
            101: 'An error has occurred.',
            102: 'An error has occurred.',
            103: 'Some options are missing.',
            104: 'Some options are invalid.',
            105: 'Sorry, an error has occurred.  Please click the LEAVE button again to leave this league.',
            
            // 200+: access/authorization errors
            200: 'You have to be logged in.',
            201: 'You are not authorized to access this league.',  // invalid game or game inaccessible to calling user
            202: 'Your user was not found in our system',
            203: 'Incorrect username/password.<br><br>Reminder: Username is your email address.',

            // 300+: draft/game errors
            300: 'Please wait your turn to perform a pick.',
            301: 'Invalid player.',
            302: 'This player has already been drafted; please select another.',
            303: 'That position limit has been reached; please select another player position.',
            304: 'You have reached your salary cap limit',
            305: 'The draft is not active.',
            307: 'Your turn has expired.',
            310: 'Sorry, this league has already filled up.  Please select another league to join from the lobby.',
            311: 'You have already registered for this league',
            312: 'You are not registered to the league.',
            313: 'You have reached the free league limit (2 per day; 5 per week).',
            314: 'The password that you entered is incorrect.',
            315: 'You cannot leave a league that you created.',
            316: 'You do not have any vouchers available for this entry fee.',
            317: 'You were unable to join this league as users are only allowed to play in one freeroll per night.',
            318: 'You cannot leave freeroll leagues.',
            320: 'You are over the salary cap.',
            321: 'You have one or more empty roster spots.',
            322: 'Sorry, you are not allowed to select all players from the same sports team.  Please select another player.',
            323: 'Your current roster cannot be the same as another roster that you have already registered to this League.',
            325: 'We\'re sorry, but you have reached the limit of 20 leagues for this entry-fee. You can still join leagues of a different entry-fee.',
            326: 'We are currently running overnight updates.  Snake leagues will be available to join by 4am EST',
            330: 'Sorry, this league name currently exists in our lobby.  Please choose a different league name.',
            331: 'Sorry, this league abbreviation currently exists in our lobby.  Please choose a different league abbreviation.',

            // 400+: financials errors
            400: 'Sorry, you do not currently have enough funds in your account to join this league.<BR><BR>Please deposit more funds or select a league with a lower entry fee.',
            401: 'Incorrect password.',

            // 500+: promo errors
            500: 'The promo code you have entered is not valid.',
            501: 'The promo code you have entered has expired.',
            502: 'The promo code you have entered can only be used once.',
            503: 'The promo code you have entered can only be used on your first deposit.',
            
            // 600+: registration errors
            601: 'First name is required.',
            602: 'Last name is required.',
            610: 'Username is required.',
            611: 'The username and/or email already exists.',
            612: 'Your username did not pass the word filter.',
            613: 'The username you have provided is too long.',
            614: 'The email address is invalid.',
            620: 'Date of birth is required.',
            621: 'Date of birth is invalid.',
            630: 'Password is required.',
            640: 'The recruit code you have provided is not valid.'

        }
    };

var ENUMS = {
        GAME_STATUS: {
            PRE_REG:        1,
            REG_OPEN:       2,
            REG_CLOSED:     3,
            DRAFT_READY:    4,
            DRAFT_ACTIVE:   5,
            DRAFT_COMPLETE: 6,
            SCORED:         7,
            CANCELLED:      8
        },
        DRAFT_METHOD: {
            SNAKE:      1,
            SALARY_CAP: 2
        },
        SCORING_METHOD: {
            STANDARD : 1,
            HRDERBY : 2,
            ROTO: 3
        },
        MONEY_TYPE: {
            MONEY:          1,
            STREET_CREDS:   2,
            BONUS_MONEY:    3,
            FEDEX_PAYMENTS: 4
        },
        SPORT: {
            MLB:            1,
            NBA:            2,
            NFL:            3,
            NHL:            4,
            PGA:            5,
            CFB:            6,
            CBB:            7
        },
        SCORING_PERIOD: {
            DAILY: 1,
            PLAYOFF: 2,
            WEEKLY: 9
        }
    };

var __STATES = 
    [
        'AK', 'AL', 'AR', 'AZ', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'GA', 'HI', 'IA', 'ID', 'IL', 'IN', 'KS', 
        'KY', 'LA', 'MA', 'MD', 'ME', 'MI', 'MN', 'MO', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM', 'NV', 
        'NY', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VA', 'VT', 'WA', 'WI', 'WV', 'WY',
        'AB', 'BC', 'MB', 'NB', 'NL', 'NT', 'NS', 'NU', 'PE', 'SK', 'ON', 'QC', 'YT' 
    ];

function populateStates(selector) {
    var html = '<option value=""></option>';
    for (var i = 0; i < __STATES.length; i++)
        html += '<option value="' + __STATES[i] + '">' + __STATES[i] + '</option>';
    
    $(selector).html(html);
}





/* -- WCF SERVICE -- */
function normalizeResult(result) {
    // this normalizes the result from a WCF call, converting to an object from JSON
    // -> if the returned content-type is application/json, the .NET result functions treat it as JSON (expected), so this returns it as is
    // -> if the content-type is text/html, it's treated as text, so this creates an object from JSON
    if (typeof result == 'object')
        return result;
    else
        return eval('(' + result + ')').d;
}





/* -- DIALOGS -- */
function basicDialog(title, html, addCloseButton, allowEscape, width, closeCallback) {
    $.modal.close();
    $('#basic-dialog').remove();
    
    $('body').append('<div id="basic-dialog" style="display: none;"></div>');
    
    $('#basic-dialog')
        .dsdialog(
            {
                tabTitle: title,
                imgPath: _IMG + 'dsdialog/',
                useClose: (addCloseButton === 'undefined' ? false : addCloseButton),
                width: (width === 'undefined' ? 400 : width)
            }
        );
            
    $('#basic-dialog .dsdialog-body-content .html')
        .html(html);
    
    $('#basic-dialog')
        .modal({
            opacity: 75,
            overlayCss: { backgroundColor: '#000000' },
            close: (allowEscape === 'undefined' ? true : allowEscape),
            onClose: closeCallback
        });
}





/* -- DATE FUNCTIONS -- */
Date.fromUtc = function(dateString) 
{
    // generates and returns a date from an UTC-formatted string
    // -> yyyy-MM-dd HH:mm:ss (time is optional)
    
    var x = /(\d{4})-(\d{2})-(\d{2})(?: )(\d{1,2})?(?::)?(\d{2})?(?::)?(\d{2})?/;
    var tokens = x.exec(dateString);

    if (tokens == null)
        return null;
    else
        return new Date(tokens[1], tokens[2] - 1, tokens[3],
            tokens[4] == null ? 0 : tokens[4], 
            tokens[5] == null ? 0 : tokens[5], 
            tokens[6] == null ? 0 : tokens[6]);
}

Date.dayNames = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ];
    
Date.monthNames = [ 
    'January', 'February', 'March', 
    'April', 'May', 'June', 
    'July', 'August', 'September', 
    'October', 'November', 'December'
    ];
    
Date.prototype.toUtcTimeString = function() {
    return this.getFullYear() + '-' + pad(this.getMonth() + 1, 2) + '-' + pad(this.getDate(), 2)
        + ' ' + pad(this.getHours(), 2) + ':' + pad(this.getMinutes(), 2) + ':' + pad(this.getSeconds(), 2);
};

Date.prototype.toUtcDateString = function() {
    return this.getFullYear() + '-' + pad(this.getMonth() + 1, 2) + '-' + pad(this.getDate(), 2);
};

Date.prototype.getMonthName = function() {
    return Date.monthNames[this.getMonth()];
};

Date.prototype.getShortMonthName = function() {
    return this.getMonthName(this.getMonth()).substr(0, 3);
}

Date.prototype.getDayName = function() {
    return Date.dayNames[this.getDay()];
};

Date.prototype.getHours12 = function() {
    var h = this.getHours();
    return (h == 0 || h == 12) ? 12 : (h % 12);
};

Date.prototype.getPeriod12 = function() {
    return (this.getHours() < 12) ? 'AM' : 'PM';
};

Date.prototype.addDays = function(days) {
    // should be 86400000 for 24 hours; adding 25 hours to prevent st/dst problems
    return new Date(this.getTime() + days * 90000000);
};

Date.prototype.stripTime = function() {
    return new Date(this.getFullYear(), this.getMonth(), this.getDate());//
}

Date.prototype.formatTime = function() {
    var hh = (this.getHours() == 12) ? 12 : format00(this.getHours() % 12);
    var mm = format00(this.getMinutes());
    var tt = this.getHours() < 12 ? 'AM' : 'PM';
    return hh + ':' + mm + ' ' + tt;
}

function format00(num) {
    if (num < 10)
        return '0' + num;
    else
        return num;
}



/* -- TEXT/FORMATTING -- */
function truncate(text, length) {
    return (text.length < length) ? text : (text.substr(0, length - 3) + '&#0133;');
}

function pad(number, length) {
    var len = number.toString().length;
    var ret = number.toString();
    for (var i = 0; i < length - len; i++)
        ret = '0' + ret;
    return ret;
}

function getOrdinalSuffix(num) {
    // adapted from http://www.highdots.com/forums/javascript/ordinal-st-nd-rd-th-41109-2.html
    var n = num % 100;
    var suff = ["th", "st", "nd", "rd", "th"]; // suff for suffix
    var ord= n<21?(n<4 ? suff[n]:suff[0]): (n%10>4 ? suff[0] : suff[n%10]);
    return ord;
}


function addCommas(nStr)
{
    // source: http://www.mredkj.com/javascript/nfbasic.html (2010-04-29)
    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;
}





/* -- SPORT GAME FUNCTIONS -- */
function getSportId(sportName)
{
    if (sportName == 'MLB') //mlb
        return 1;
    else if (sportName == 'NFL') // nfl
        return 3;
    else if (sportName == 'NBA') // nba
        return 2;
    else if (sportName == 'NHL') // nba
        return 4;
    else if (sportName == 'PGA') // pga
        return 5;
    else if (sportName == 'CFB')
        return 6;
    else if (sportName == 'CBB')
        return 7;
    else // mlb as default
        return 1;
}





/* -- VALIDATION -- */
function IsDecimal(strString) //  check for valid numeric strings	
{
    if(!/\D/.test(strString)) return true;//IF NUMBER
    else if(/^\d+\.\d+$/.test(strString)) return true;//IF A DECIMAL NUMBER HAVING AN INTEGER ON EITHER SIDE OF THE DOT(.)
    else return false;
}

function IsNumeric(strString) //  check for valid numeric strings	
{
    if(!/\D/.test(strString)) return true;//IF NUMBER
    else return false;
}

function IsEmail(strString) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(strString)){
        return (true)
    }
    return (false)
}





/* -- AJAX/PROCESS LOADER -- */
function showLoader(elemId, zIndex) {
    var $elem = $('#' + elemId);
    var w = $elem.width(),
        h = $elem.height(),
        o = $elem.offset(),
        left = o.left,
        top = o.top;
    
    if (zIndex == undefined)
        zIndex = 900;
    
    var html = $('<div class="loader" style="z-index: ' + zIndex + ' !important" rel="' + elemId + '"><img src="' + CONFIG.PATHS.IMG_SECURE + 'loading.gif" style="width: 32px; height: 32px;" alt="Please wait..."/></div>')
        .css('position', 'absolute')
        .css('background-image', 'url("' + CONFIG.PATHS.IMG_SECURE + 'loader-bg.png")')
        .css('background-repeat', 'repeat')
        .css('text-align', 'center')
        
        .css('width', w)
        .css('height', h)
        .css('left', left)
        .css('top', top)
        .css('visibility', 'visible');
        
    html.find('img')
        .css('margin-top', Math.round((h / 2) - 16));
        
    $('body').append(html);
}

function hideLoader(elemId) {
    $('.loader[rel="' + elemId + '"]').remove();
}

function showFullBodyLoader() {
    // loading anim            
    $('<div id="full-body-loader"><img src="' + CONFIG.PATHS.IMG + 'loading.gif" style="width: 32px; height: 32px;" alt="Wait..."></div>')
        .modal({
            opacity: 75,
            overlayCss: { backgroundColor: '#000000' },
            close: false
        });
}




/* -- DRAFT ROOMS -- */
function openCapDraftroom(sportId, gameId, gameRegId) {
    var cap_room_height = 691;
    if (sportId == 5)
        cap_room_height = 565;
        
    var x = (screen.width - 760) / 2, y = (screen.height - cap_room_height) / 2;
    var page_url = 'salary-cap.aspx?game_id=';
    
    page_url = getSportName(sportId) + '/' + page_url;

    var cap_win = window.open(CONFIG.PATHS.WEB + page_url + gameId + '&game_reg_id=' + gameRegId,
        'cap_win_' + gameRegId, 'width=776,height=' + cap_room_height + ',left=' + x + ',top=' + y + ',toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1');
    cap_win.focus();
}

function openCapDraftroomNewReg(sportId, gameId, gameRegId) {
    var cap_room_height = 691;
    if (sportId == 5)
        cap_room_height = 565;
        
    var x = (screen.width - 760) / 2, y = (screen.height - cap_room_height) / 2;
    var page_url = 'salary-cap.aspx?n=1&game_id=';
    
    page_url = getSportName(sportId) + '/' + page_url;

    var cap_win = window.open(CONFIG.PATHS.WEB + page_url + gameId + '&game_reg_id=' + gameRegId,
        'cap_win_' + gameRegId, 'width=776,height=' + cap_room_height + ',left=' + x + ',top=' + y + ',toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1');
    cap_win.focus();
}

function openHrDerbyDraftroom(sportId, gameId, gameRegId) {
    var x = (screen.width - 760) / 2, y = (screen.height - 675) / 2;
    var page_url = 'hr-derby.aspx?game_id=';
    page_url = getSportName(sportId) + '/' + page_url;

    window.open(CONFIG.PATHS.WEB + page_url + gameId + '&game_reg_id=' + gameRegId,
        '', 'width=776,height=691,left=' + x + ',top=' + y + ',toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1');
}

function openHrDerbyDraftroomNewReg(sportId, gameId, gameRegId) {
    var x = (screen.width - 760) / 2, y = (screen.height - 675) / 2;
    var page_url = 'hr-derby.aspx?n=1&game_id=';
    page_url = getSportName(sportId) + '/' + page_url;

    window.open(CONFIG.PATHS.WEB + page_url + gameId + '&game_reg_id=' + gameRegId,
        '', 'width=776,height=691,left=' + x + ',top=' + y + ',toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1');
}

function openSnakeDraftroom(sportId, gameId) {
    var x = (screen.width - 973) / 2, y = 0;
    var page_url = 'snake-draft.aspx?game_id=';

    page_url = getSportName(sportId) + '/' + page_url;
    
    window.open(CONFIG.PATHS.WEB + page_url + gameId, 
        '', 'width=989,height=726,left=' + x + ',top=' + y + ',toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1');
}

function openScoreboard(sport, gameId) {
    window.open(CONFIG.PATHS.WEB + sport + '/scoreboard.aspx?game_id=' + gameId);
}



/* -- SPORTS -- */
function getSportName(sportId) {
    try {
        return ["mlb", "nba", "nfl", "nhl", "pga", "cfb", "cbb"][sportId - 1];
    }
    catch (err) {
        return "mlb";
    }
}

function getQueryStringValue(queryParam)
{
    // no url params, return empty string
    if(window.location.search.length <= 1)
        return "";

    var params = window.location.search.substring(1).split("&");
    
    for(i=0;i<params.length;i++)
    {
        var param = params[i].split("=");
        
        if(param.length == 2 && param[0].toLowerCase() == queryParam.toLowerCase()) // if the param matches, return it
            return param[1];
    }
    
    // param not found, return empty
    return "";
}



/* -- GLOBAL -- */
function chatGameClick(gameId) {
    try {
        _selectedGameId = gameId;
        _joinFeatured = false;
        _uiService.GetSingleLobbyGame(_selectedGameId, 0, GetSingleLobbyGame_Complete_ExternalLink, GetSingleLobbyGame_Failed);
    } catch (ex) {}
}



/* -- SESSION MANAGEMENT & BASIC LOGIN DIALOG -- */
var _sessionValInterval;
function initSessionPersistence() {
    _sessionValInterval = setInterval(persistSession, 15000);
}

function persistSession() {
    _uiService.ValidateSession(ValidateSession_Complete, ValidateSession_Failed);
}

function ValidateSession_Complete(result) {
    result = normalizeResult(result);
        
    if (!result.success) {

        $.modal.close();
        buildBasicLogin();

        $('#basic-login')
            .modal({
                opacity: 75,
                overlayCss: { backgroundColor: '#000000' },
                close: true,
                onClose: function() {
                    $.modal.close();
                    window.location.reload();
                }
            });
            
        $('#basic-login .failed').toggle(false);

        clearInterval(_sessionValInterval);
    }
}

function ValidateSession_Failed(result) {
    // ignore
}

var _basicLoginBuilt = false;
function buildBasicLogin() {
    if (_basicLoginBuilt)
        return;
        
    var html =
        '<div id="basic-login" style="display: none;">' +
        '   <div>' +
        '       <div style="float: left;">' +
        '           <div style="padding: 8px 0px;">Your session has expired.  Please log in below.</div>' +
        '       </div>' +
        '       <div class="r" style="float: right">' +
        '           <a href="#" class="close"><img src="' + CONFIG.PATHS.IMG + 'basic-dialog-close.png" style="width: 16px; height: 16px;" /></a>' +
        '       </div>' +
        '       <div class="clear"></div>' +
        '       <div class="failed">Login failed.  Please try again.</div>' +
        '       <table>' +
        '           <tr>' +
        '               <td class="r" style="width: 100px; padding-right: 8px;">Email:</td>' +
        '               <td style="width: 160px;"><input type="text" class="email" maxlength="320" /></td>' +
        '           </tr>' +
        '           <tr>' +
        '               <td class="r" style="padding-right: 8px;">Password:</td>' +
        '               <td><input type="password" class="password" /></td>' +
        '           </tr>' +
        '           <tr>' +
        '               <td></td>' +
        '               <td class="c" style="padding-top: 4px;"><a href="#" class="log-in"><img src="' + CONFIG.PATHS.IMG + 'sign-in.png" style="width: 117px; height: 37px;" alt="Sign in" /></a></td>' +
        '           </tr>' +
        '       </table>' +
        '   </div>' +
        '</div>';
        
    $('body').prepend(html);
        
    $('#basic-login')
        .dsdialog({
            tabTitle: 'Log in',
            imgPath: _IMG + 'dsdialog/',
            useClose: false,
            width: '360px'
        });
        
    $('#basic-login .close')
        .click(function() {
            $.modal.close();
            return false;
        });

    $('#basic-login .log-in')
        .click(function() {
            _userService.LogIn(
                $('#basic-login .email').val(), $('#basic-login .password').val(),
                BasicLogin_LogIn_Complete, BasicLogin_LogIn_Failed);
                
            showLoader('basic-login', 2001);
            return false;
        });

   _basicLoginBuilt = true;
}

function BasicLogin_LogIn_Complete(result) {
    result = normalizeResult(result);
    
    if (!result.success)
        return BasicLogin_LogIn_Failed(result);
        
    window.location.reload();
}

function BasicLogin_LogIn_Failed(result) {
    $('#basic-login .failed').show();
    hideLoader('basic-login');
}
