jQuery.fn.stripTags = function() { return this.replaceWith( this.html().replace(/<\/?[^>]+>/gi, '') ); };
var hexDigits = new Array("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"); 
var RecaptchaOptions = { theme : 'blackglass' };
var MafiaDeath = {
	init: function() {
		$('body').removeClass('nojs');

		this.forms();
		this.forums();
		this.mailbox();
		this.profile();
		this.inventory();
		this.tooltips();
		this.notifanimate();
	},

	forms: function() {
		$('select').uniform();
		
		$('#gamesel').change(function() {
		   var $gotoURL = $(this).val();
		   window.location.href=$gotoURL;
        });
		
		$('#langsel').change(function() {
		   var $langSetURL = $(this).closest("form").attr('action') + 'set_lang/' + $(this).val() + '.php';
		   $.getJSON( $langSetURL, function(data) {
              window.location.href=window.location.href;
           });
        });

		var $inputs = $('input[type=text], input[type=password]');

		$inputs.each(function() {
			var $label = $(this).parent().find('label');

			if ($label.length > 0 && $label.attr('class') != 'inlinelabel' ) {
				$label.css('display', 'block');

				$(this).focus(function() {
					if ($(this).val() == '') {
						$label.animate({opacity: 0.25}, 250);
					}
				})
				.keypress(function() {
					$label.animate({opacity: 0}, 50, function() {
						$(this).css('display', 'none');
					});
				})
				.blur(function() {
					if ($(this).val() == '') {
						$label.css('display', 'block').animate({opacity: 1}, 250);
					}
				});
			}
		});
	},
	
	forums: function() {
		$('.smiley, .bbadd').tipsy({gravity: 's', opacity: 0.95});
		
		$('.smiley').click(function() {
			return MafiaDeath.wysiwyg( $(this).attr('alt') );
		});
		
		$('.bbbold').click(function() {
			return MafiaDeath.wysiwyg( 'bold' );
		});
		
		$('.bbitalic').click(function() {
			return MafiaDeath.wysiwyg( 'italic' );
		});
		
		$('.bbunderline').click(function() {
			return MafiaDeath.wysiwyg( 'underline' );
		});
		
		$('.bbstrike').click(function() {
			return MafiaDeath.wysiwyg( 'strike' );
		});
		
		$('.bbcenter').click(function() {
			return MafiaDeath.wysiwyg( 'center' );
		});
		
		$('.bbcolour').click(function() {
			$('.bbcolour .box').toggle();
		});
		
		$('.bbcolour .box div.c').click(function() {
			$('.bbcolour .box').hide();
			return MafiaDeath.wysiwyg( 'colour', MafiaDeath.rgb2hex( $(this).css('background-color') ) );
		});
		
		$('.bblink').click(function() {
			return MafiaDeath.wysiwyg( 'i_link' );
		});
		
		$('.bbimage').click(function() {
			return MafiaDeath.wysiwyg( 'i_image' );
		});
		
		$('.bbyoutube').click(function() {
			return MafiaDeath.wysiwyg( 'i_youtube' );
		});
		
		$('.bbusertag').click(function() {
			return MafiaDeath.wysiwyg( 'i_usertag' );
		});
    },

	inventory: function() {
		$('.inventory .category > a').click(function() {
			$(this).parent().toggleClass('expand');

			return false;
		});
		$('.inventory .category ul li a').click(function() {
		    var $dispSect = $(this).attr('rel');
		    
		    if( $dispSect == 'all' ){ $('.inventory .equipment.eu').show(); }
		    else                    { $('.inventory .equipment.eu').hide(); $('#'+$dispSect).show(); }
		    
			$('.inventory .category').toggleClass('expand');

			return false;
		});
	},

	tooltips: function() {
		$('.ptipsy').tipsy({gravity: 'n'});
		$('.btipsy').tipsy({gravity: 's'});
		$('.mtipsy').tipsy({gravity: 'n', opacity: 0.95, html: true});
		$('.ftipsy').tipsy({trigger: 'focus', gravity: 'w'});
		$('.qm').tipsy({gravity: 's', opacity: 0.95});
		$('.qm2').tipsy({gravity: 'n', opacity: 0.95, html: true});
	},
	
	popupwin: function( pURL, pName ) {
        pNewLeft = ( window.screen.width  / 2 ) - ( 235 + 10 );
        pNewTop  = ( window.screen.height / 2 ) - ( 260 + 50 );
        window.open( pURL, pName, 'left = ' + pNewLeft + ', top = ' + pNewTop + ', width = 470, height = 520, toolbar = 0, resizable = 0, scrollbars=1' );
        return false;
    },
	
	cucall: function(theElement) {
        var theForm = theElement.form, z = 0;
        for( z=0; z < theForm.length; z++ )
        {
            if(theForm[z].type == 'checkbox' && theForm[z].name != 'checkall')
            {
                theForm[z].checked = theElement.checked;
            }
        }
    },

	savesearch: function() {
	    if( $('#s_dosave:checked').val() == 1 )
	    {
            $('#s_dosavetxt').hide();
            $('#s_dosavebox').show();
        }
        else
        {
            $('#s_dosavetxt').show();
            $('#s_dosavebox').hide();
        }
	},
    
    profile: function() {
        $('#rate_block').show();
        $('#rate_block a').click(function() {
            MafiaDeath.profile_rate( $(this).attr('href') );
            return false;
        });
    },
    
    profile_rate: function( rateurl ) {
        $('#rate_block').stripTags();
        $('#rate_num').after( '<br />' );
        $.getJSON( rateurl, function(data) {
            if( data.resp == 'ok' )
            {
                $('#rate_num').html( data.newval );
            }
        });
        return false;
    },
    
    mailbox: function() {
        $('#mailform').submit(function() {
            MafiaDeath.mailsend();
            return false;
        });
        $('#deleteform').submit(function() {
            MafiaDeath.maildelete();
            return false;
        });
        $('#mdelete').click(function() {
            MafiaDeath.mailactions('delete');
            return false;
        });
        $('#msave').click(function() {
            MafiaDeath.mailactions('save');
            return false;
        });
        $('#munsave').click(function() {
            MafiaDeath.mailactions('unsave');
            return false;
        });
        $('#mreport').click(function() {
            MafiaDeath.mailactions('report');
            return false;
        });
    },
    
    mailactions: function(actiont) {
        $.post( $('#ajaxurl_actions').val(), { maction: actiont, mailid: escape($("#mailid").val()) },
        function(data){
            var mailData = jQuery.parseJSON( data );
            
            if( !mailData )
            {
                // unknown error
            }
            else if( mailData.lo == true )
            {
                alert( $('#notloggedin').val() );
            }
            else if( mailData.resp == 'deleted' )
            {
                $('#mactions').remove();
            }
            else if( mailData.resp == 'saved' )
            {
                $('#msave').hide();
                $('#munsave').css('display','');
            }
            else if( mailData.resp == 'unsaved' )
            {
                $('#munsave').hide();
                $('#msave').css('display','');
            }
            else if( mailData.resp == 'reported' )
            {
                $('#mreport').remove();
            }
        });
    },
    
    maildelete: function() {
        var delString = '0';
        $('.msel:checked').each(function() {
            delString = delString + ',' + $(this).val();
        });
        
        if( delString != '0' )
        {
            $('#delete_selected, .msel').attr('disabled', true); 
            $.post( $('#ajaxurl').val(), { delete_selected: 1, delids: delString },
            function(data){
                var mailData = jQuery.parseJSON( data );
                
                if( mailData )
                {
                    if( mailData.resp == 'deleted' )
                    {
                        $('.msel:checked').each(function() {
                            $('#m' + $(this).val()).remove();
                        });
                    }
                }
                $('#delete_selected, .msel').removeAttr('disabled');
            });
        }
        
        return false;
    },
    
    mailsend: function() {
        $('#m_notifs, #m_notifs div span').hide();
        $('#msend, #msubject, #bbtext').attr('disabled', true); 
        
        $.post( $('#ajaxurl').val(), { msend: 1, userid: escape($("#userid").val()), mailid: escape($("#mailid").val()), moptions: escape($("#moption").val()), msubject: ($("#msubject").val()), mbody: ($("#bbtext").val()) },
        function(data){
            var mailData = jQuery.parseJSON( data );
            
            if( mailData.lo == true )
            {
                alert( $('#notloggedin').val() );
            }
            else
            {
                if( mailData.resp == 'sent' )
                {
                    if( mailData.type == 'new' )
                    {
                        $('#userid, #msubject, #bbtext, #clist').val('');
                        $('#m_notifs, #n_'+mailData.resp).show();
                    }
                    else if( mailData.type == 'reply' )
                    {
                        $('#bbtext').val('');
                        
                        if( mailData.resp == 'sent' )
                        {
                            $('#m_notifs').after( mailData.html );
                        }
                        else
                        {
                            $('#m_notifs, #n_'+mailData.resp).show();
                        }
                    }
                }
                else
                {
                    $('#m_notifs, #n_'+mailData.resp).show();
                }
                
                $('#us_money').html( mailData.money ); 
                $('#us_bank').html( mailData.bank ); 
                $('#um_mail').html( mailData.mail ); 
            }
            $('#msend, #msubject, #bbtext').removeAttr('disabled'); 
        });
    },
    
    notifanimate: function() {
        if( $('#nw_animate').val() == 1 )
        {
            $('.wanimate').fadeTo(1000,0.1).fadeTo(1000,1.0).fadeTo(1000,0.1).fadeTo(1000,1.0).fadeTo(1000,0.1).fadeTo(1000,1.0);
        }
    },
	
	wysiwyg: function( bbtype, bbopt ) {
        textbox = document.getElementById( 'bbtext' );
        textbox.focus();
        
        // Code for IE
        if( document.selection )
        {
            var sel = document.selection.createRange();
            sel.text = this.wysiwyg_handle( sel.text, bbtype, bbopt );
        }
        // Code for Mozilla Firefox
        else
        {
            var startPos  = textbox.selectionStart;
            var endPos    = textbox.selectionEnd;
            var replText  = this.wysiwyg_handle( textbox.value.substring( startPos, endPos ), bbtype, bbopt );
            textbox.value = textbox.value.substring( 0, startPos ) + replText + textbox.value.substring( endPos, textbox.value.length );
    		
            var newPos = startPos + replText.length;
            var range  = textbox.setSelectionRange( newPos, newPos );
        }
        
        textbox.focus();
        
        return false;
    },
	
	wysiwyg_handle: function( bbtext, bbtype, bbopt ) {
        if( bbtype == 'bold' )
        {
            bbtext = '[b]' + bbtext + '[/b]';
        }
        else if( bbtype == 'italic' )
        {
            bbtext = '[i]' + bbtext + '[/i]';
        }
        else if( bbtype == 'underline' )
        {
            bbtext = '[u]' + bbtext + '[/u]';
        }
        else if( bbtype == 'strike' )
        {
            bbtext = '[s]' + bbtext + '[/s]';
        }
        else if( bbtype == 'center' )
        {
            bbtext = '[center]' + bbtext + '[/center]';
        }
        else if( bbtype == 'colour' )
        {
            bbtext = '[colour=' + bbopt + ']' + bbtext + '[/colour]';
        }
        else if( bbtype == 'i_link' )
        {
            if( bbtext ) bbtext = '[url]' + bbtext + '[/url]';
            else
            {
                var l_url = window.prompt("Please enter the URL of your link:");
                
                if( l_url.length > 0 )
                {
                    bbtext = '[url]' + l_url + '[/url]';
                }
            }
        }
        else if( bbtype == 'i_image' )
        {
            if( bbtext ) bbtext = '[img]' + bbtext + '[/img]';
            else
            {
                var l_img = window.prompt("Please enter the URL of your image:");
                
                if( l_img.length > 0 )
                {
                    bbtext = '[img]' + l_img + '[/img]';
                }
            }
        }
        else if( bbtype == 'i_youtube' )
        {
            if( bbtext ) bbtext = '[youtube]' + bbtext + '[/youtube]';
            else
            {
                var l_video = window.prompt("Please enter the YouTube code:");
                
                if( l_video.length > 0 )
                {
                    bbtext = '[youtube]' + l_video + '[/youtube]';
                }
            }
        }
        else if( bbtype == 'i_usertag' )
        {
            if( bbtext ) bbtext = '[user]' + bbtext + '[/user]';
            else
            {
                var l_user = window.prompt("Please enter the User's ID:");
                
                if( l_user.length > 0 )
                {
                    bbtext = '[user]' + l_user + '[/user]';
                }
            }
        }
        else
        {
            bbtext = bbtype;
        }
        
        return bbtext;
    },
    
    totalcost: function(maxqty,costeach,qtyid,totalid,decpoint,thousep,mpre,mpost){
        var selQtyO = $('#'+qtyid).val();
        var selQty = parseInt( selQtyO );
        
        if( selQtyO != '' )
        {
            if( isNaN( selQty ) ) selQty = 1;
            if( selQty < 1 )      selQty = 1;
            if( selQty > maxqty ) selQty = maxqty;
            
            if( selQtyO != selQty ) $('#'+qtyid).val( selQty );
        
            var totalCost = selQty * costeach;
        }
        else
        {
            var totalCost = selQty * costeach;
        }
        
        $('#'+totalid).html( mpre + MafiaDeath.number_format( totalCost, 0, decpoint, thousep ) + mpost );
    },
    
    number_format: function(number,decimals,dec_point,thousands_sep){
        number = (number+'').replace(',', '').replace(' ', '');
        var n = !isFinite(+number) ? 0 : +number, 
            prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
            sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
            s = '',
            toFixedFix = function (n, prec) {
                var k = Math.pow(10, prec);
                return '' + Math.round(n * k) / k;        };
        // Fix for IE parseFloat(0.55).toFixed(0) = 0;
        s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
        if (s[0].length > 3) {
            s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);    }
        if ((s[1] || '').length < prec) {
            s[1] = s[1] || '';
            s[1] += new Array(prec - s[1].length + 1).join('0');
        }    return s.join(dec);
    },
    
    rgb2hex: function(rgb){
        rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
        return "#" + this.hex(rgb[1]) + this.hex(rgb[2]) + this.hex(rgb[3]);
    },
    
    hex: function(x){
        return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
    }
};

$().ready(function() {
	MafiaDeath.init();
});

