jQuery.fn.extend({
insertAtCaret: function(myValue){
  return this.each(function(i) {
    if (document.selection) {
      this.focus();
      sel = document.selection.createRange();
      sel.text = myValue;
      this.focus();
    }
    else if (this.selectionStart || this.selectionStart == '0') {
      var startPos = this.selectionStart;
      var endPos = this.selectionEnd;
      var scrollTop = this.scrollTop;
      this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
      this.focus();
      this.selectionStart = startPos + myValue.length;
      this.selectionEnd = startPos + myValue.length;
      this.scrollTop = scrollTop;
    } else {
      this.value += myValue;
      this.focus();
    }
  })
}
});



$('body').click(function() {
    
});

function undermenu(obj,btn)
{
	$(btn).click(function() {
		$(obj).fadeIn(300);
	});
	$(obj).bind('clickoutside',function(event){
		targ = event.target;
		if($(targ).attr('id') != $(btn).attr('id'))
			$(obj).fadeOut(300);
	});
}


setted_sidebar = 'false';
last_id = 'false';
function set_sidebar(obj_id)
{
	if(last_id != obj_id)
	{
		if(setted_sidebar != 'false')
			$(setted_sidebar).slideUp(300);
		$('.sb_box').each(function(index) {
			if(obj_id == index)
			{
				$('.content',this).slideDown(300);
				setted_sidebar = $('.content',this);
				$('.head',this).fadeTo(100,1);
			}else{
				$('.head',this).fadeTo(100,0.5);
			}
		});
		last_id = obj_id;
	}
}

function live_position()
{
	if($('#live').css('bottom') != '0px')
		$('#live').css('bottom','0px');
}

function live_ticker()
{
	$.getJSON('ajax/?ajax=live', function(data)
	{
		return_html = '';
		if(typeof data.on != 'undefined')
		{
			if($(data.on).length != 0)
			{
				$.each(data.on,function(index, value){
					if(typeof value.live != 'undefined' && $(value.live).length != 0)
					{
						if(index != 'unknown')
						{
							if(value.group_id != 1)
								return_html+='<div class="live_m" onclick="window.location.href = \''+this.link+'\';"><table><tr><td><small class="group">'+value.group+'</small> <span class="nick_member">'+value.nick+'</span></td>';
							else
								return_html+='<div class="live_m" onclick="window.location.href = \''+this.link+'\';"><table><tr><td><span class="nick_member">'+value.nick+'</span></td>';
						}else
							return_html+='<div class="live_m_u"><table><tr><td><span class="nick">'+this.nick+'</span></td>';
						$.each(value.live,function(l_index, l_value){
							if(l_index == 'zockt')
							{
								$.each(l_value,function(z_index, z_value){
									return_html+='<td><img src="'+data.images.zockt[z_value]+'" alt="'+data.images.zockt[z_value]+'"/></td>';
								});
							}else if(l_index == 'ts'){
								return_html+='<td><img src="'+data.images.ts+'" alt="TS"/></td>';
							}else if(l_index == 'online'){
								return_html+='<td><img src="'+data.images.online+'" alt="ONLINE"/></td>';
							}
						});
						return_html+='</tr></table></div>';
					}
				});
			}
		}
		$('#live_ajax').html(return_html).fadeIn(500);
	});
}
            
  function bb_code(BBCode,id_html) {
  	$('#'+id_html).insertAtCaret(BBCode);
	}

last_menu = '';
last_game = '';
function change_game(game, menu_obj,m_id,time)
{
	if(last_game != game)
	{
		if(last_menu != '')
			$(last_menu).toggleClass('sel');
		$(menu_obj).toggleClass('sel');
		last_menu = menu_obj;
		$("#cbc_d_game_details").slideUp(500);
		setTimeout(function(){
			$.ajax({
				url: 'ajax_members_details/?memb_game_det='+game+'&member_id='+m_id+'&time='+time,
				dataType: 'html',
				success: function(data) {
					last_g_menu = 'main_info';
					$('#cbc_d_game_details').html(data);
					$("#cbc_d_game_details").slideDown(500);
					last_game = game;
					init();
				}
			});
		},500);
	}
}

last_g_menu = 'main_info';
function change_game_menu(obj_id)
{
	if(typeof $('.main_info > #'+obj_id).attr('id') != 'undefined')
	{
		if(last_g_menu == 'main_info')
			$.scrollTo('.main_info > #'+obj_id, 800, {duration:'2000'} );
		else{
			$('.extra_info').slideUp(700);
			$('.main_info').slideDown(700);
			window.setTimeout(function(){
				$.scrollTo('.main_info > #'+obj_id, 800, {duration:'2000'} );
				init();
			},700);
		}
		last_g_menu = 'main_info';
	}else if(typeof $('.extra_info > #'+obj_id).attr('id') != 'undefined')
	{
		if(last_g_menu == 'extra_info')
			$.scrollTo('.extra_info > #'+obj_id, 800, {duration:'2000'} );
		else{
			$('.main_info').slideUp(700);
			$('.extra_info').slideDown(700);
			window.setTimeout(function(){
				$.scrollTo('.extra_info > #'+obj_id, 800, {duration:'2000'} );
				init();
			},700);
		}
		last_g_menu = 'extra_info';
	}
}

function init()
{
	$('.ttip').each(function(){
		if(typeof $('#'+$(this).attr('id')+'t') != 'undefined')
		{
					  $(this).qtip({
					      content: $('#'+$(this).attr('id')+'t').html(),
					      position: {
					         my: 'top left',
					         at: 'bottom left',
					         target: 'mouse',
					         viewport: $(window), // Keep it on-screen at all times if possible
					         adjust: {
					            x: 10,  y: 10
					         }
					      },
					      hide: {
					         fixed: true // Helps to prevent the tooltip from hiding ocassionally when tracking!
					      },
					      style: 'ui-tooltip-light'
					  });
					}
	});
					$.tablesorter.defaults.widgets = ['zebra']; 
					$(".tablesorter").tablesorter();	
}
function fix_sidebar()
{
	var top = $('#sidebar').offset().top - parseFloat($('#sidebar').css('marginTop').replace(/auto/, 0));
	$(window).scroll(function (event) {
	  // what the y position of the scroll is
	  var y = $(this).scrollTop();
	  // whether that's below the form
	  if (y >= top) {
	    // if so, ad the fixed class
	    $('#sidebar').addClass('sidebar_fixed');
	  } else {
	    // otherwise remove it
	    $('#sidebar').removeClass('sidebar_fixed');
	  }
	});
}

function str_replace (search, replace, subject, count) {
    // Replaces all occurrences of search in haystack with replace  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/str_replace    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'    var i = 0,
        j = 0,
        temp = '',
        repl = '',
        sl = 0,        fl = 0,
        f = [].concat(search),
        r = [].concat(replace),
        s = subject,
        ra = Object.prototype.toString.call(r) === '[object Array]',        sa = Object.prototype.toString.call(s) === '[object Array]';
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    } 
    for (i = 0, sl = s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }        for (j = 0, fl = f.length; j < fl; j++) {
            temp = s[i] + '';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {                this.window[count] += (temp.length - s[i].length) / f[j].length;
            }
        }
    }
    return sa ? s : s[0];}

function show_graph_tooltip(x, y, contents) {
        $('<div id="graph_tooltip">' + contents + '</div>').css( {
            top: y + 5,
            left: x + 5
        }).appendTo("body").fadeIn(200);
    }
    
function plotWithOptions(t,t_data,his,gen) {
	$('#ratio_graph_type').html(t_data);
	if(t === false)
	{
			        $.plot($("#ratio_graph"), [
				        {
				        	label: "&nbsp;"+t_data+" (History Tabelle)",
				          data: his[t_data],
				          color: "rgb(30, 180, 20)",
				          /*threshold: { below: t, color: "rgb(200, 20, 30)" },*/
				          lines: { show: true, fill: true},
				          points: { show: true }
				        },
				        {
				        	label: "&nbsp;"+t_data+" (allgemein)",
				          data: gen[t_data],
				          color: "rgb(180, 180, 20)",
				          /*threshold: { below: t, color: "rgb(244, 147, 69)" },*/
				          lines: { show: true, fill: true},
				          points: { show: true }
				        } 
			        ],{
			        	grid: { hoverable: true }
			        });
			    }else{
			    $.plot($("#ratio_graph"), [
				        {
				        	label: "&nbsp;"+t_data+" (History Tabelle)",
				          data: his[t_data],
				          color: "rgb(30, 180, 20)",
				          threshold: { below: t, color: "rgb(200, 20, 30)" },
				          lines: { show: true},
				          points: { show: true }
				        },
				        {
				        	label: "&nbsp;"+t_data+" (allgemein)",
				          data: gen[t_data],
				          color: "rgb(180, 180, 20)",
				          threshold: { below: t, color: "rgb(244, 147, 69)" },
				          lines: { show: true},
				          points: { show: true }
				        } 
			        ],{
			        	grid: { hoverable: true }
			        });
			    }
			    
	}
