/**
 * index.js
 *
 * @copyright (c) 2010 Frosmo Ltd
 * @version $Rev: 18017 $
 *
 * $LastChangedDate: 2010-05-27 11:49:50 +0300 (Thu, 27 May 2010) $
 * $LastChangedBy: joni $
 * $HeadURL: svn://musti_witos/e-arena/branches/rel_streamlined_20100528/ui_frosmo/assets/scripts/index.js $
 */

function setCookie( name, value, expires, path, domain, secure ) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );
    
    /*
    if the expires variable is set, make the correct 
    expires time, the current script below will set 
    it for x number of days, to make it for hours, 
    delete * 24, for minutes, delete * 60 * 24
    */
    if ( expires )
    {
    expires = expires * 1000 * 60 * 60 ;
    }
    var expires_date = new Date( today.getTime() + (expires) );
    
    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
    ( ( path ) ? ";path=" + path : "" ) + 
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

function getCookie(check_name) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f
    
    for ( i = 0; i < a_all_cookies.length; i++ ) {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split( '=' );
        
        
        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
    
        // if the extracted name matches passed check_name
        if ( cookie_name == check_name ) {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if ( a_temp_cookie.length > 1 ) {
                cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}        

// this deletes the cookie when called
function deleteCookie( name, path, domain ) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? ";path=" + path : "") +
            ((domain) ? ";domain=" + domain : "" ) +
            ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }
}

function getIEVersion() {
    // Returns the version of Internet Explorer or a -1
    // (indicating the use of another browser).
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer')
    {
        var ua = navigator.userAgent;
        var match = ua.match(/MSIE ([0-9]{1,}[\.0-9]{0,})/);
        if (match) {
            rv = parseFloat(match[1]);
        }
    }
    return rv;
}

function handleGiveUpGame(request) {       
    window.location = "game_index.php";
}

function getFlashVersion(desc) {
    var matches = desc.match(/[\d]+/g);
    matches.length = 3; // To standardize IE vs FF
    return matches.join('.');
}

function checkFlashVersion() {    
    var flashinstalled = -1;
    var flashversion = 0;
    // This doesn't work on IE
    if (navigator.plugins && navigator.plugins.length) {
        var flashPlugin = navigator.plugins["Shockwave Flash"];
        if (flashPlugin) {
            flashinstalled = 1;
            if (flashPlugin.description) {
                desc = flashPlugin.description; // "Shockwave Flash <v>.<subv> r<release>"
                v = desc.match(/[\d]+/g);
                flashversion = getFlashVersion(flashPlugin.description);
            } else {
                flashversion = 1;
            }
        } else {
            flashinstalled = 0;
            if (navigator.plugins["Shockwave Flash 2.0"]) {
                flashinstalled = 1;
                flashversion = 2;
            }
        }
    } else if (navigator.mimeTypes && navigator.mimeTypes.length) {
        var mimeFlash = navigator.mimeTypes['application/x-shockwave-flash'];
        if (mimeFlash && mimeFlash.enabledPlugin) {
            flashinstalled = 1;
            flashversion = getFlashVersion(mimeType.enabledPlugin.description);
        } else {
            flashinstalled = 0;
        }
    } else {
        // IE flash detection.
        try {
            var ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
            flashinstalled = 1;
            flashversion = getFlashVersion(ax.GetVariable('$version'));
        } catch(flashSevenException) {
            for (var i=12; i>7; i--) {
                try {
                    ActiveXObject("ShockwaveFlash.ShockwaveFlash." + i);
                    flashinstalled = 1;
                    flashversion = i;
                    break;
                } catch(flashException) {}
            }
            if (flashinstalled === 0) {
                try {
                    ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
                    flashinstalled = 1;
                    flashversion = '6.0.21';  // First public version of Flash 6
                } catch (flashSixException) {
                    try {
                        // Try the default activeX
                        var defaultAx = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
                        flashinstalled = 1;
                        flashversion = getFlashVersion(defaultAx.GetVariable('$version'));
                    } catch (defaultFlashException) {
                        // No Flash installed
                    }
                }
            }
        }
        
    }
    return flashversion;
}

function addLoadEvent(func) { 
    var oldonload = window.onload; 
    if (typeof window.onload != 'function') { 
        window.onload = func; 
    } else { 
        window.onload = function() { 
            if (oldonload) { 
                oldonload(); 
            }
            func(); 
        };
    }
} 

function createdimension(width,height){
    this.width=width;
    this.height=height;
}

function getWindowViewPortSize() {
    
    var myWidth = 0, myHeight = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
      myHeight = window.innerHeight;
      
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
      //IE 6+ in 'standards compliant mode'
      myWidth = document.documentElement.clientWidth;
      myHeight = document.documentElement.clientHeight;
      
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
      //IE 4 compatible
      myWidth = document.body.clientWidth;
      myHeight = document.body.clientHeight;
     
    }
    
    var dimension = new createdimension(myWidth,myHeight);
    
    return dimension;
}

function inviteHide() {
    $(".inviteHolder").hide();
}

function initInviteBox(frameUrl,holderId,frameId) {
    
    var holder = document.getElementById( holderId );
    
    var frame = document.getElementById( frameId );
    
    if (holder.style.visibility == "visible") {
        inviteHide(holderId);
        return;
    }
    
    frame.src = frameUrl;

    //for some reason document.getElementById("holder").style.width did no work
    windowWidth = $("#"+holderId).css("width");
    windowHeight = $("#"+holderId).css("height");
    
    divWidth = windowWidth.substring(0,windowWidth.length-2);
    divHeight = windowHeight.substring(0,windowHeight.length-2);
    
    
    windowDimension = new getWindowViewPortSize();
    
    var centerWidth = (windowDimension.width - divWidth) / 2;
    var centerHeight = (windowDimension.height - divHeight) / 2;

    holder.style.position = "absolute";
    holder.style.display = "inline";
    holder.style.top = centerHeight + "px";
    holder.style.left =  centerWidth + "px";    
    //holder.style.height = "480px";
    //holder.style.width = "auto";

    holder.style.visibility = "visible";
}

function inviteShow() {
    initInviteBox("invite.php", "inviteHolder", "inviteFrame");
}

function inviteMsnShow(holderId, frameId) {
    initInviteBox("inviteMsn.php",holderId, frameId);
}

function redirectToWelcome() {
     window.location = 'index.php';
} 

(function($) {   
    
    $.fn.isScrolledIntoView = function() {
        
        var docViewTop = $(window).scrollTop();
        var docViewBottom = docViewTop + $(window).height();

        var elemTop = $(this).offset().top;
        var elemBottom = elemTop + $(this).height();

        return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
    };

    /* USED ON GAMES LISTING, MUST BE INCLUDED ON ALL SITES */

    $.fn.mouseOverPopup = function(options) {
    
        var defaults = { name: 'mouseoverinfo' };
        var settings = $.extend(defaults, options);
        var linkClass = settings.name + '-link';
        var popupClass = settings.name + '-popup';
    
        return this.each(function(){
        
            var obj = $(this);
            obj.addClass(linkClass);
            
            var info = obj.next();
            info.addClass(popupClass);
            
            obj.hover(
                function(){
                    $('.' + linkClass + ':hidden').show();
                    $('.' + popupClass + ':visible').hide();
                    info.show();
                    obj.hide();
                },
                function(){}
            );       
             
            info.hover(
                function(){},
                function(){
                    info.hide();
                    obj.show();
                }
            );
            
        });
        
    };
    
    $.fn.closeTutorial = function() {
        
        var tutorial = $('#stepByStepTutorial');
        
        return this.each(function(){
        
            var link = $(this);
            link.click(function(event){
                event.preventDefault();
                $.post(
                    link.attr('href'),
                    null,
                    function(data,status){ tutorial.hide('normal'); },
                    'json'
                );                
                return false;
           });
            
        });
        
    };
    
    $.fn.hideTutorial = function() {
        
        var tutorial = $('#stepByStepTutorial');
        
        return this.each(function(){
        
            var link = $(this);
            link.click(function(event){
                event.preventDefault();
                tutorial.toggleClass('closed');
                $.post(
                    link.attr('href'),
                    null,
                    function(resp,status){ 
                        if (status == "success") {
                            if (resp.action == 'close') {
                                tutorial.addClass('closed');
                            } 
                            else if (resp.action == 'open') {
                                tutorial.removeClass('closed'); 
                            }
                        }                        
                    },
                    'json'
                );                
                return false;
           });
            
        });
        
    };

    $.fn.timerCountDown = function(options) {

        settings = jQuery.extend({
            timeLeftTimer: new Date(),
            reloadTime: 100
          }, options);      
        /*
        var userFrollars = $('#userFrollarAmount').html();
        var maxFrollars = $('#rankMaxFrollarAmount').html();
        */
        //alert(settings.timeLeft);
        //timeLeft.setMinutes(timeLeft.getMinutes() + 1);
        $('#frollarTimer').countdown('change', {
            until: settings.timeLeftTimer
        });
  
    };

    $.fn.useClassOnHighlight = function(classToAdd) {
        return this.each(function(){
            $(this).mouseover(function(){
                $(this).addClass(classToAdd);
                $(this).mouseout(function(){
                    $(this).removeClass(classToAdd);
                });
            });
        });
    };
        
    $.fn.giveBonusFrollars = function(options) {
        settings = jQuery.extend({
            reloadTime: 100,
            amount: 100
        }, options); 
        var userFrollars = parseInt($('#userFrollarAmount').html(), 10);
        var maxFrollars = parseInt($('#rankMaxFrollarAmount').html(), 10);
        var newFrollarAmount;
        newFrollarAmount = userFrollars + settings.amount;
        
        if(userFrollars < maxFrollars) {
            if(newFrollarAmount >= maxFrollars) {
                newFrollarAmount = maxFrollars;
            } 
            $('#userFrollarAmount').html(newFrollarAmount);
        }

        
        //alert(userFrollars+' '+maxFrollars);
        if(newFrollarAmount < maxFrollars) {
            timeLeftTimer = new Date();
            timeLeftTimer.setSeconds(timeLeftTimer.getSeconds() + settings.reloadTime);
            //alert('here');
            $("#frollarTimer").timerCountDown({timeLeftTimer: timeLeftTimer, reloadTime: settings.reloadTime});
        } else {
            $("#frollarTimerContainer").hide();
        }    
            /*$.post(
                'giveFrollars.php',
                '',
                function(json) {
                    //alert(json.amount);
                    newFrollarAmount = json.amount;
                    $('#userFrollarAmount').html(json.amount);
                    if(parseInt(json.amount) < parseInt(maxFrollars)) {
                        timeLeft = new Date();
                        timeLeft.setSeconds(timeLeft.getSeconds() + settings.reloadTime);
                        //alert('here');
                        $("#frollarTimer").timerCountDown({timeLeft: timeLeft, reloadTime: settings.reloadTime});
                    } else {
                        $("#frollarTimer").hide();
                    }                    
                },
                'json'
            );

        }  */  
    };
    
    $.fn.outerHTML = function() {
        return $('<div>').append( this.eq(0).clone() ).html();
    };
    
    $.fn.transparentButton = function() {
        return this.each(function(){
            var obj = $(this);
            var tagName = obj.get(0).tagName;
            if (tagName.match(/^(input|img)$/i)) {
                obj.transparentImage();        
            } else {
                var img = obj.find('img');
                if (img.length == 1) {
                    img.transparentImage();
                }
            }
        });
    };
    
    $.fn.transparentBackground = function() {
        return this.each(function(){
            
            var obj = $(this);
            var outerWidth = obj.outerWidth();
            var outerHeight = obj.outerHeight();
            
            var backgroundImageMatch = obj.css('background-image').match(/url\((.+)\)/i);
            var backgroundImageSrc = backgroundImageMatch[1].replace(/['"]/g, '');
            
            var alphaImg = $('<span class="alphaImg"></span>')
                .attr(
                    'style', 
                    "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader" + 
                    "(src='" + 
                    backgroundImageSrc + 
                    "', sizingMethod='scale');"
                )
                .css({
                    width: obj.width(), 
                    height: obj.height(),
                    paddingTop: obj.css('paddingTop'),
                    paddingBottom: obj.css('paddingBottom'),
                    paddingLeft: obj.css('paddingLeft'),
                    paddingRight: obj.css('paddingRight')
                })
                .append(obj.html());
            
            obj.html(alphaImg)
                .attr('style', 'padding: 0; background-image: none;')
                .css({width: outerWidth, height:outerHeight})
                .addClass('alphaImgBackground');
            
        });
    };
    
    $.fn.transparentImage = function() {
        return this.each(function(){
            var img = $(this);
            var transparentImage = img.clone()
                .attr('style', 'margin: 0; filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);');
            var alphaImg = '<span class="alphaImg"' + 
                "style=\"" + 
                "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(" + 
                " src='" + img.attr('src') + "'," + 
                " sizingMethod='scale'" + 
                "); " + 
                " width:" + img.width() + "px;" + 
                " height:" + img.height() + "px;" + 
                " margin:" + img.css('margin') + ";" + 
                "\"> " + 
                transparentImage.outerHTML() + 
                "</span>";
            img.replaceWith(alphaImg);   
        });
    };
    
    /** 
     * Update HTML element inner text with form input value when changed 
     */
    
    $.fn.updateWhenChanged = function(element) {
        
        return this.each(function(){

            var obj = $(this);
            var target = $(element);

            obj.keypress(function(event){
                obj.oneTime(100, 'update', function() {
                    target.text(obj.val());
                });
            });
            
            obj.keyup(function(event){
                var code = (event.keyCode ? event.keyCode : event.which);
                if (code == 8 || code == 46) {
                    obj.oneTime(100, 'update', function() {
                        target.text(obj.val());
                    });
                }
            });

        });
    };

    /**
     * Helps to adjust string size according to the maximum width of the area where it is being inserted.
     *  
     * Thomas 30/3/2010: still pretty rough and has to 
     * be elaborated a little more to make it truly generic  
     */

    $.fn.squeezeString = function(width) {

        var text = $(this).children(".btnText");
        var bg = $(this).children(".btnBg");
        
        var factor = text.width()/width;
        
        var size = parseInt(text.css("font-size"), 10);
        var newSize = Math.floor(size/factor);
        
        var height = 0;
        if (newSize>35) {
            height = 30;
        } else {
            height = 17;
        }
        text.css("font-size", height + "px");
        
        var lineHeight = 0;        
        if (text.width()>width) {
            lineHeight = 22;
        } else {
            lineHeight = 49;
        }
        
        bg.css("line-height", lineHeight + "px");
        
        textClone = text.clone();
        bg.children(".btnTextWrapper").append(textClone);
        textClone.css("visibility","visible");    
    };
    
    $.fn.rankInfo = function(options) {
        
        var defaults = { 
            offset : { left: -355, top: -18 }
        };
        var settings = $.extend(defaults, options);
        
        var container = $("#moreRankInfo");
        if (container.length === 0) {
            container = $('<div id="moreRankInfo"></div>').hide();
            $("body").append(container);
        }
        
        return this.each(function(){
            
            var moreInfo = $(this);
            moreInfo.bind('display', function(event, top, left){
                
                var help = moreInfo.data('help');
                container.html(help).css({
                    top: (top + settings.offset.top) + "px",
                    left: Math.max(0, (left + settings.offset.left)) + "px"
                }).fadeIn('fast');
                
                container.find('a.close').click(function(event){
                    event.preventDefault();
                    container.fadeOut('fast', function() {
                        container.hide();
                    });                    
                    return false;
                });
                
            });
            
            moreInfo.click(function(e){
                e.preventDefault();
                var help = moreInfo.data('help');
                if (help) {
                    moreInfo.trigger('display', [e.pageY, e.pageX]);
                } else  {
                    $.get(
                        "getMoreRankInfo.php", 
                        { id : moreInfo.attr('id') }, 
                        function(data){
                            moreInfo.data('help', data);
                            moreInfo.trigger('display', [e.pageY, e.pageX]);
                        }
                    );
                }
                return false;
            });
            
        }); 
        
    };
    
})(jQuery);


function showFaq(element_class, element_id) {
    $(element_class).hide(); //hide all questions
    $(element_id).css({'display': 'block'}); //show wanted question
}

function showFaq(element_class, element_id){
        $(element_class).hide(); //hide all questions
    $(element_id).css({'display': 'block'}); //show wanted question
}

function showRankPathHandler()
{
    var pathXOff = 113;
    var pathYOff = 18;
    $("a.showPath").click(function(e){
        $("#rankPath").remove();
        $.get("getRankPath.php", function(data) {
           $("body").append('<div id="rankPath" style="display: none;">' + data + '</div>');
           $("#rankPath")
               .css("top", (e.pageY - pathYOff) + "px")
               .css("left", (e.pageX - pathXOff) + "px")
               .fadeIn('fast');
        });
        return false;
    });
}

function hideRankPath()
{
    $("#rankPath").fadeOut('fast', function(){
        $("#rankPath").remove();
    });
    return false;
}

function publishFacebookFeed(fbFeed, callback, afterDisplayCallBack) {
    if (!window.FB) {
        return false;
    }
    
    FB.init(fbFeed.apiKey, "xd_receiver.htm?v=2");
    FB.ensureInit(function(){
        var attachment = {
            'name': fbFeed.name,
            'description': fbFeed.description,
            'media': [{
                'type': 'image',
                'src': fbFeed.imageSrc,
                'href': fbFeed.actionLinkHref
             }]                        
        };
        var actionLinks = [{ 
            "text": fbFeed.actionLinkText, 
            "href": fbFeed.actionLinkHref
        }];
        var prompt = fbFeed.prompt;
        
        var target_id = null;
        if (fbFeed.targetId) {
            target_id = fbFeed.targetId;
        }
        
        var auto_publish = false;
        if (fbFeed.autoPublish) {
            auto_publish = true;
        }
        
        FB.Connect.streamPublish('', attachment, actionLinks, target_id, prompt, callback, auto_publish);
        
        if (typeof afterDisplayCallBack != 'undefined') {
            $(document).everyTime(100, 'checkStreamPublishDialog', function(){                
                var dialog = $('div.fb_popupContainer');
                if (dialog.length > 0) {
                    $(document).stopTime('checkStreamPublishDialog');
                    afterDisplayCallBack.apply(this, [dialog]);
                }
            });
        }            
    }); 
    
    return true;
}

/**
 * GAME LOADING PROGRESS BAR
 * moved from frosmo.js, needs to be included to every site
 */

function updateProgressBar() {
    
    $('#progressBar').oneTime(500, 'updateProgressBar', function(){
        updateProgressBar();
    });
    
    var flashGame = $('#flashGame');
    if (flashGame.length === 0) { //Is not written to html page yet
        return false;
    }
    
    try {
        var percentLoaded = flashGame.get(0).PercentLoaded();
        setProgress('gameProgress', percentLoaded);
        if (percentLoaded >= 100) {
            $('#progressBar').stopTime('updateProgressBar');
            $('#progressBar').fadeOut(1000);
            flashGame.show();
        }
    } catch (e) {
        setProgress('gameProgress', 100);        
        $('#progressBar').stopTime('updateProgressBar');
        $('#progressBar').fadeOut(1000);
    }
    
}

function giveUpGame(confirmMessage) {
    if (confirm(confirmMessage)) {
        $.get(
            "handler_give_up.php",
            function(resp, status) {
                window.location = "game_index.php";
            }
        );
        // Spry.Utils.loadURL("GET", "handler_give_up.php", true, handleGiveUpGame);
    }
}

function giveUpGameWithoutConfirmation(msg, gameId) {
    alert(msg);
    $.get(
        "handler_timeout.php",
        { gameId : gameId },
        function(resp, status) {
            window.location = "game_index.php";
        }
    );
    // Spry.Utils.loadURL("GET", "handler_timeout.php?gameId="+gameId, true, handleGiveUpGame);
}

function giveUpGameWhileSearching(confirmMessage) {
    if (confirm(confirmMessage)) {    
        window.location = "handler_give_up_searching.php";
    }
}

function topRankingsShow(id) {
    $.get(
        "getTopRankings.php",
        { id : id },
        function(resp, status) {             
            if (status != 'success' || !resp) { return false; }             
            $('#topRankingsShow').hide();                
            $('#tournamentPageLeftCol').append($('<div id="topRankingsHolder">' + resp + '</div>'));
        }
    );
    // Spry.Utils.loadURL("GET", "getTopRankings.php?id=" + id, true, handleGetTournamentResults);
}

function hideTopRankingsShow() {
    $('#topRankingsHolder').remove();
    $('#topRankingsShow').show();
}

function showProductDetails(id) {
    $.get(
        "getProductDetails.php",
        { id : id },
        function(resp, status) {
            if (status != 'success' || !resp) { return false; }
            $('#products').append($('<div id="productDetailsHolder">' + resp + '</div>'));
        }
    );
    // Spry.Utils.loadURL("GET", "getProductDetails.php?id=" + id, true, handleShowProductDetails);
}

function hideProductDetails() {
    $('#productDetailsHolder').remove();
}

function showPremiumTournaments(){    
    $('#premiumTournamentsHolder').show();
}

function hidePremiumTournaments(){
    $('#premiumTournamentsHolder').hide();
}

function updateNotificationCount() {
    count = $("#notifications .notificationWrapper").length;
    if (count < 1) {
        $("#notifications").hide();
    } else {
        $("#notifications #count").html(count);
    }            
}

function invokeNotifications() {
    $.post('handler_call_notifications.php',
        function(data) {
            $("#notifications").remove();
            $("#container").prepend(data);
            $("#notifications").show();
        }
    );
}

function addPopupNotification(html) {
    var element = $(html);        
    $("#container").append(element);
}

function showNotification(index, removeAfterFade, callback) {
    if (index > count - 1 || index < 0 || active) { return; }
    
    active = true; // Prevent multiple simultaneous events
    var not = $("#notifications .notificationWrapper").eq(current);
    not.fadeOut("fast", function(){
        if (removeAfterFade !== null && removeAfterFade === true) {
            not.remove();
            // if last msg, show previous
            if (index == count - 1) {
                index--;
            }
            count--;
            $("#notifications #count").html(count);
        }
        current = index;
        
        $("#current").html(index+1); // Update UI
        if (current == count - 1) {
            $("#next").addClass("disabled");
        } else if (current === 0) {
            $("#previous").addClass("disabled");
        }
        if (current < count - 1) {
            $("#next").removeClass("disabled");
        }
        if (current > 0) {
            $("#previous").removeClass("disabled");
        }
        // After the previous one has vanished, show the new one
        $("#notifications .notificationWrapper").eq(current).fadeIn("fast", function(){
            active = false; // Enable subsequential 
            if (typeof callback != 'undefined') {
                callback.apply(this);
            }
        });
    });
}

function addNotification(html, stayAtCurrent) {
    var element = $(html);
            
    $("#notifications").append(element);
    updateNotificationCount();
    $("#notifications #controlsWrapper div").show();
    if (stayAtCurrent === null || stayAtCurrent === false || count == 1) {
        $("#notifications").slideDown("fast", function(){
            showNotification(count - 1, function(){
            });
        });
    }
}

function previousNotification(removeAfterFade) {
    showNotification(current - 1, removeAfterFade);
}

function nextNotification(removeAfterFade) {
    showNotification(current + 1, removeAfterFade);
}

function removeCurrentNotification() {
    var index = current;

    // last msg
    if (index == count - 1) {
        previousNotification(true);
    } else {
        nextNotification(true);
    }
}

function handleMessageBoxVisuals(isPopup,popupId) {
    if (isPopup) {
        //hide notificationPopups if the last notification
        /*if ($('div.notificationPopup:visible').size() <= 1) {
            $('#notificationPopups').fadeOut('slow').remove();
            $('#blockOverlay').remove();
            $("div.popupDialog").show(); //hide tutorial if on same page
        } else {
             $('#notificationPopup'+popupId).fadeOut('slow');
        }*/
        $('#notificationPopup'+popupId + ' a.link-hide-notification').trigger('click');                   
    } else {
        if ($('#notifications div.notificationWrapper').size() <= 1) {
            //hide notifications
            $('#notifications').slideUp("slow");
        } else {
            removeCurrentNotification();
        }
    }
}

function setPublishedCallback(notificationId, popup, postId, exception){
    //http://developers.facebook.com/docs/?u=facebook.jslib.FB.Connect.streamPublish
    //post_id returns the id of the published post (which can be null if the user cancels)
    if (notificationId === null) {
        return false;
    }
    
    //seems that Facebook instead of null returns string null
    if (postId && postId != 'null') { 
        $.post(
            "handler_publishing_notification.php",
            { notificationId: notificationId }
        );
    }
    //hide notification
    handleMessageBoxVisuals(popup, notificationId);
}

function subtractFrollarAmount(amount, timeLeftSeconds, reloadTime, reloadAmount) {
    var userFrollars = parseInt($('#userFrollarAmount').html(), 10);
    // var maxFrollars = parseInt($('#rankMaxFrollarAmount').html(), 10);
    var newFrollarAmount = userFrollars - amount;
    
    if (newFrollarAmount < 0) {
        newFrollarAmount = 0;
    }
    
    $('#userFrollarAmount').html(newFrollarAmount);
    $("#frollarTimer").countdown('destroy'); //destroy countdown if exists    
    
    var timeLeft = new Date();
    timeLeft.setSeconds(timeLeft.getSeconds() + timeLeftSeconds);
    $('#frollarTimer').countdown({
        until: timeLeft, 
        compact: true, 
        format:'MS', 
        description:'',
        onExpiry: function() {
            $("#frollarTimer").giveBonusFrollars({ 
                reloadTime: reloadTime, 
                amount: reloadAmount 
            });
        }
    });
    
    $("#frollarTimerContainer").show(); //make sure container is shown
}

function showProgressMeter(swf, meterId, percent) {
    swfobject.embedSWF(
        swf, meterId, 
        "40", "80", "9.0.0", "expressInstall.swf", 
        {percent:percent},
        {wmode:"transparent"}
    );
}

$(document).ready(function() {

    // Tutorial buttons
    $('#stepTutorialTitle span.open a').hideTutorial();
    $('#stepTutorialTitle span.close a').hideTutorial();
    $('#closeTutorial').closeTutorial();
    
    // Rank activity point info popups
    $('div.activityInfo a.moreInfo').rankInfo();
    
    // Footer Twitter link bonus action
    $('a.twitterBonusLink').click(function(event){
        event.preventDefault();
        $.get('addPointsForTwitterClick.php', function(resp, status) {
            // Points added    
        },'json');
        window.open($(this).attr('href'));
        return false;
    });

});

// EOF index.js