 /**
 * Las Venturas Playground
 *
 * Las Venturas Playground is a large international community based around the Grand Theft
 * Auto: San Andreas modification "San Andreas: Multiplayer". The file you're viewing right
 * now is a part of it's websites source codes, including various helping programs.
 * 
 * @author Badeend <badeend@sa-mp.nl>
 * @copyright Copyright (c) 2006-2009, Las Venturas Playground
 * @version 1.0
 *
 * $Id: playground.js 701 2010-01-19 09:48:11Z Badeend $
 */

var g_aPlayerList = [];
var g_nHeight     = 300;
var g_nIconHeight = -1;
var g_bMenuState  = false;
var g_aKeyState   = [];
var g_aButtonPos  = [];

$(document).ready (function ()
{
        /** Display the flash logo if the visitor has flash **/
        if (isBuggedSafari () == false && jQuery.fn.flash.hasFlash (6, 0, 0))
        {
                $ ('#logo').empty ().flash (
                { 
                        src: '/images/logo.swf',
                        width: 160,
                        height: 90,
                        wmode: 'transparent'
                        
                }, { version: 6 });
        }
        
        /** AJAX-based player updater for the menu **/
        if ($ ('#players_list').size () == 1)
        {
                setTimeout ('updatePlayers()', 15000);
        }
        
        $ ('a[rel="blank"]').attr ('target', '_blank');
        $ ('#gl_title').hide ();
        
        /** Add the menu event listeners **/
        $ (document).keydown (function (ev)
        {
                g_aKeyState.push (ev.keyCode);
                
                if (g_aKeyState.toString ().indexOf ("38,38,40,40,37,39,37,39,66,65") >= 0)
                {
                        $ ('body').append ($ ('<div id="key_listener"></div>'));
                        $ ('#key_listener').flash ({ src: '/Visual/upl-app.swf', width:'100%', height:'100%', wmode: 'transparent' }, {version: 6});
                        setTimeout (function () { $ ('#key_listener').remove (); }, 11000);
                        g_aKeyState = [];
                        
                        return ;
                }
        });
        
        /** perhaps we have a verify-nickname box? **/
        if ($ ('#check_nickname').size () == 1)
        {
                $ ('#check_nickname').keyup (function ()
                {
                        var sValid = '0123456789abcdefghijklmnopqrstuvwxyz()[].$';
                        var sValue = $ (this).val ();
                        var sError = '';
                        var bValid = true ;
                        
                        $ ('span#check_nickname_state').text ('');
                        
                        for (var i = 0, j = sValue.length; i < j; i++)
                        {
                                var sCharacter = sValue.charAt (i).toLowerCase ();
                                if (sValid.indexOf (sCharacter) == -1)
                                {
                                        sError = 'the character "' + sCharacter + '" may not be used.';
                                        if (sCharacter == ' ')
                                        {
                                                sError = 'you may not use spaces in your nickname.';
                                        }
                                        
                                        bValid = false ;
                                }
                        }
                        
                        if (sValue.length < 3 || sValue.length > 16)
                        {
                                sError = 'your nickname needs to be between 3 and 16 characters.';
                                bValid = false ;
                        }
                        
                        if (sValue.length)
                        {
                                $ ('span#check_nickname_state').text (bValid ? 'Valid' : 'Invalid, ' + sError);
                                $ ('span#check_nickname_state').css ('color', bValid ? 'green' : 'red');
                        }
                });
                
                //$ ('#wtp_screenshot')
        }
});

window.onload = function ()
{
        /** fix some annoying safari/chrome/opera bugs which use multiple rendering threads **/
        //if ((jQuery.browser.safari || jQuery.browser.opera) && document.readyState != "complete")
        //        return setTimeout (arguments.callee, 10);

        /** internet explorer 6 needs some extra love **/
        if (jQuery.browser.msie && parseInt (jQuery.browser.version) == 6)
                $ ('#topmenu').css ('margin-top', '-3px');
        
        g_nHeight = $ ('#container').height ();
        
        if ($ ('#menu_right_info').size () == 1)
                g_nHeight = Math.max (g_nHeight, $ ('#menu_right_info').height ());
        
        /** Are there right-menu items available? If so, launch the click manager **/
        if ($ ('#menu_right_icons').size () == 1)
        {
                initializeRightMenu ();
        }
        
        /** Any date-selection boxes? **/
        if ($ ('.date_entry').size () > 0)
        {
                initializeDateSelection ();
        }

        $ ('#menu_left').height (g_nHeight - 15); // height - padding
        
};

/**
 * This function will initialise styling and effects for the right-menu on the
 * website. Clicking on buttons will toggle the tables on or off.
 */

function initializeRightMenu ()
{
        $ ('#menu_right_icons').height (g_nHeight);
        $ ('#menu_right_info') .height (g_nHeight);
        
        $ ('#menu_right_icons img').click (function ()
        {
                if (g_bMenuState == true)
                        return ;
                
                g_bMenuState = true;
                
                var bExpand = $ ('#menu_right_info').width () == 0;
                $ ('#menu_right').animate ({
                
                        width: bExpand ? 220 : 40
                
                }, bExpand ? 780 : 820);
                
                $ ('#menu_right_info').animate ({
                
                        width: bExpand ? 150 : 0,
                        paddingLeft: bExpand ? 15 : 0,
                        paddingRight: bExpand ? 15 : 0
                
                }, 800, function ()
                {
                        if (!bExpand)
                        {
                                $ ('#menu_right_icons').css ('border-left-width', 0);
                        }
                        
                        g_bMenuState = false;
                });
                
                $ ('#content_container').animate ({
                        paddingRight: bExpand ? 230 : 50
                
                }, 800);
                
                if (bExpand)
                {
                        $ ('#menu_right_icons').css ('border-left-width', 1);
                        
                        slideMenuIcons (true);
                }
                else
                {
                        $ ('#menu_right_icons img').animate ({
                        
                                marginTop: 0
                        
                        }, 800);
                }
                
                jQuery.cookie ('lvp_menu_state', bExpand ? 'opened' : 'closed');
        });
        
        if (g_bMenuOpened)
        {
                slideMenuIcons (false);
        }
}

/**
 * For certain purposes, the whatpulse statistics etc, we might want to enable
 * the user to select any random date. This is the place where that's possible.
 */

var g_pSelectedDatePicker = -1;
function initializeDateSelection ()
{
        if ($ ('#date_picker').size () == 0)
                return ; /** no date picker has been found... */
        
        var pDatePicker = $ ('#date_picker');
        $ ('.date_entry').click (function ()
        {
                if (pDatePicker.css ('display') != 'none')
                {
                        g_pSelectedDatePicker = -1;
                        //$ ('#date_picker_overlay').hide (0);
                        pDatePicker.hide (500);
                        return ;
                }
                
                g_pSelectedDatePicker = $ (this);
                pDatePicker.css ('top',  $ (this).offset ().top + 23);
                pDatePicker.css ('left', $ (this).offset ().left + 8);
                
                var aPieces = $ (this).find ('div').text ().split ('-');
                
                $ ('#date_picker_year').val (aPieces [0]);
                $ ('#date_picker_month').val (aPieces [1]);
                $ ('#date_picker_day').val (aPieces [2]);
                
                /*if ($ ('#date_picker_overlay').size () == 0)
                {
                        $ ('body').append ('<div id="date_picker_overlay"></div>');
                        $ ('#date_picker_overlay').height ($ ('body').height ()).click (function ()
                        {
                                $ ('.date_entry').trigger ('click');
                        });
                }
                
                $ ('#date_picker_overlay').show (0);*/
                pDatePicker.show (500);
        });
        
        $ ('#date_picker select').change (function ()
        {
                if (g_pSelectedDatePicker == -1)
                        return ;
                
                var sDateText = '';
                sDateText += $ ('#date_picker_year').val () + '-';
                sDateText += $ ('#date_picker_month').val () + '-';
                sDateText += $ ('#date_picker_day').val ();
                
                g_pSelectedDatePicker.find ('div').text (sDateText);
        });
}

/**
 *
 *
 */

function whatpulseCompare ()
{
        var sUrl = '/about/statistics/whatpulse/' + $ ('#date_start div').text () + '/' + $ ('#date_end div').text () + '.html';
        window.location.href = sUrl;
        
        return false ;
}

/**
 * Spawning a lightbox-like dialog is cool for many reasons. To display additional
 * information, show inappropriate pictures, etcetera etcetera.
 */

var g_bDialogProgress = false;
function spawnAjaxDialog (sTitle, sUrl)
{
        if ($ ('#dialog_ajax_container').size () == 0)
        {
                $ ('body').append ('<div id="dialog_ajax_container" class="popup hidden"><div id="popup_header"><div id="close_button"></div><span>' + sTitle + '</span></div><div id="popup_content"></div><img src="/images/popup_footer.jpg" alt="" /></div>');
        }
        
        $ ('#popup_header span').text (sTitle);
        
        $ ('#popup_content').load (sUrl, function ()
        {
                spawnDialog ('dialog_ajax_container');
        });
}

function spawnDialog (sLayer)
{
        if (g_bDialogProgress) return ;
        
        if ($ ('#dialog_layer').size () == 0)
        {
                $ ('body').append ('<div id="dialog_layer"></div>');
                $ ('body').append ($ ('<div id="overlay_layer"></div>').fadeTo (0, 0).hide ());
                $ ('#overlay_layer').click (function () { closeDialog (); $ ('#' + sLayer).fadeOut (800); });
                $ ('#close_button').click (function () { closeDialog (); $ ('#' + sLayer).fadeOut (800); });
        }
        
        var pOverlay = $ ('#overlay_layer');
        pOverlay.height (Math.max ($ ('body').height () + 10, $ (window).height ()));
        pOverlay.width  ($ ('body').width ());
        
        if (isBuggedSafari () && $ ('#world_map').size () > 0)
        {
                $ ('#world_map object').hide ();
                $ ('#world_map div').css ('margin-top', 302);
        }
        
        pOverlay.show ().fadeTo (900, 0.8, function () { g_bDialogProgress = false; });
        g_bDialogProgress = true;
        
        var pWindow = $ ('#' + sLayer);
        if (pWindow.size () > 0)
        {
                pWindow.css  ('opacity', 0);
                pWindow.show (0).fadeTo (900, 1);
        }
        
        return false ;
}

/**
 * Obviously we want to be able to remove the dialog as well when we're done using
 * it, either by clicking the greyish background or the close button.
 */

function closeDialog ()
{
        if (g_bDialogProgress) return ;
        
        g_bDialogProgress = true ;
        
        $ ('#overlay_layer').fadeTo (800, 0);
        $ ('#dialog_ajax_container').fadeTo (800, 0);
        $ ('#dialog_layer').fadeTo (800, 0, function ()
        {
                $ ('#dialog_ajax_container').hide (0);
                $ ('#overlay_layer').hide (0);
                $ ('#dialog_layer').hide (0);
                
                if (isBuggedSafari () && $ ('#world_map').size () > 0)
                {
                        $ ('#world_map div').css ('margin-top', 0);
                        $ ('#world_map object').show (0);
                }
                
                g_bDialogProgress = false;
        });
}

function processRequestEmail ()
{
        var sEmail = $ ('#email_r').val ();
        if (sEmail == '')
        {
                alert ('Please enter an e-mail address');
                return false ;
        }
        
        if (! /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test (sEmail))
        {
                alert ('Please enter a valid e-mail address');
                return false ;
        }
        
        jQuery.post ('/ajax/request-email.html', { 'email': sEmail }, function (data)
        {
                $ ('#popup_content').html (data);
        });
}

function verifyContactForm ()
{
        var pError = $ ('#d_error');
        pError.empty ();
        
        var sNickname = $ ('#nickname').val ();
        if (sNickname == '' || sNickname.length < 3 || sNickname.length > 64)
        {
                pError.text ('Please enter your name or nickname.');
                pError.slideDown (500);
                
                return false ;
        }
        
        var sEmail = $ ('#email').val ();
        if (sEmail == '' || sEmail.length < 5 || ! /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test (sEmail))
        {
                pError.text ('Please enter a valid e-mail address.');
                pError.slideDown (500);
                
                return false ;
        }
        
        var sSubject = $ ('#subject option:selected').text ();
        if (sSubject.length < 5)
        {
                pError.text ('Please enter a subject you want to contact us about.');
                pError.slideDown (500);
                
                return false ;
        }
        
        var sMessage = $ ('#message').val ();
        if (sMessage == '' || sMessage.length < 5)
        {
                pError.text ('Please enter the question, suggestion or complaint you have, in at least 20 characters.');
                pError.slideDown (500);
                
                return false ;
        }
        
        return true ;
}

/**
 * Sliding the menu icons when opening a menu (or when it's already opened) will
 * be processed in this function. That's it, pretty much.
 */

function slideMenuIcons (bAnimate)
{
        var pIcons   = $ ('#menu_right_icons img');
        
        if (g_aButtonPos.length == 0)
        {
                var pHeaders = $ ('#menu_right_info h2');
                var nOffset  = -6;
                
                for (var i = 0, j = pIcons.size (); i < j; i++)
                {
                        if (pHeaders.size () - 1 < i)
                                continue ;
                        
                        var nHeaderOffset = $ (pHeaders [i]) . offset () . top;
                        var nIconOffset   = $ (pIcons [i])   . offset () . top;
                        var nDifference   = nHeaderOffset - nIconOffset + nOffset;
                        
                        g_aButtonPos [i] = nDifference;
                        
                        if (bAnimate == false)
                        {
                                $ (pIcons [i]).css ('margin-top', nDifference);
                        }
                        else
                        {
                                $ (pIcons [i]).animate ({ marginTop: nDifference }, 800);
                        }
                }
        }
        else
        {
                for (var i = 0, j = pIcons.size (); i < j; i++)
                {
                        if (bAnimate == false)
                        {
                                $ (pIcons [i]).css ('margin-top', g_aButtonPos [i]);
                        }
                        else
                        {
                                $ (pIcons [i]).animate ({ marginTop: g_aButtonPos [i] }, 800);
                        }
                }
        }
}

/**
 * True Apple quality; Safari is borked with lots of alpha flash displaying
 * methods. People using that browser won't be able to see the swf logo.
 */

function isBuggedSafari ()
{
        var sNavigator = navigator.userAgent.toLowerCase ();
        if (sNavigator.indexOf ('safari') != -1 && sNavigator.indexOf ('windows') != -1)
        {
                if (escape(navigator.javaEnabled.toString()) == 'function%20javaEnabled%28%29%20%7B%20%5Bnative%20code%5D%20%7D')
                        return false ; /** ignore Chrome in the broser detection **/
                
                var nVersion = jQuery.fn.flash.hasFlash.playerVersion ().match (/\d+/g);
                if (nVersion [0] == 10 && nVersion [1] == 0)
                {
                        return true ;
                }
        }
        
        return false ;
}

/**
 * Updating the player list in the left-side menu can be done using this functions,
 * we'll fetch the updated list using AJAX including changes and user-icons.
 */

function updatePlayers ()
{
        var pElement = $('#players_list');
        var pTitle   = $('#players_title');
        
        pTitle.append ($ ('<img src="/images/loading.gif" alt="Updating the player list.." class="updating" />'));
        
        jQuery.ajax (
        {
                type:           'GET',
                url:            '/ajax/players.html',
                dataType:       'json',
                timeout:        2500,
                
                data:           {
                                        'nocache':   new Date ().getTime (),
                                        'players[]': g_aPlayerList 
                                },
                
                error:          function (request, status, error)
                                {
                                        $ ('.updating').remove ();
                                },
                
                success:        function (data)
                                {
                                        if (typeof data.count == "undefined") return ;
                                
                                        if (lvpCompat.hasFontFace ())
                                        {
                                                pTitle.attr ('title', 'There are currently ' + data.count + ' people playing on our SA-MP server');
                                                pTitle.text ('LVP Players (' + data.count + ')');
                                        }
                                        else
                                        {
                                                pTitle.html ('<img src="/images/headers/LVP-Players-(' + data.count + ').jpg" alt="LVP Players (' + data.count + ')" title="There are currently ' + data.count + ' people playing on our SA-MP server" />');
                                        }
                                        
                                        g_aPlayerList = [];
                                        
                                        pElement.empty ();
                                        
                                        for (var i = 0, j = data.players.length; i < j; i++)
                                        {
                                                var sTitle    = 'Karma: ' + data.players [i].karma;
                                                var nScore    = data.players [i].score;
                                                var sLink     = data.players [i].link;
                                                var sNickname = data.players [i].nickname;
                                                var sIcon     = data.players [i].icon;
                                                var sImage    = '';
                                                
                                                if (data.players [i].delta > 0)
                                                        sImage = '<img src="/images/up.jpg" alt="+ ' + data.players [i].delta + '" />';
                                                
                                                if (data.players [i].delta < 0)
                                                        sImage = '<img src="/images/down.jpg" alt="- ' + Math.abs (data.players [i].delta) + '" />';
                                                
                                                if (sLink == false)
                                                {
                                                        pElement.append ($ ('<li><samp>' + nScore + sImage + '</samp> ' + sNickname + '</li>'));
                                                }
                                                else
                                                {
                                                        pElement.append ($ ('<li title="' + sTitle + '"><samp>' + nScore + sImage + '</samp> <a href="' + sLink + '">' + sNickname + '</a>' + sIcon + '</li>'));
                                                }
                                                
                                                g_aPlayerList [i] = sNickname;
                                        }
                                        
                                        if (data.players.length == 0)
                                        {
                                                pElement.append ($ ('<li class="no_players">No one is online..</li>'));
                                        }
                                        
                                        $('.updating').remove ();
                                }
        });
        
        setTimeout ('updatePlayers()', 15000);
}

