/* LoseCatcher - jcatcher.js 0.01 - (req jquery) */
if (typeof LoseCatcher == 'undefined'){ LoseCatcher = {}; }
var pagedata = {};

//own functions:
jQuery.extend({
  formatNum: function(num,t) {
    var c = 0;
    var t = t == undefined ? ".": t,
    s = num < 0 ? "-": "";
    var i = parseInt(num = Math.abs(num || 0).toFixed(c)) + "",
    j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t: "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t);
  }
});
jQuery.fn.extend({ //input+checkbox-methods
  enable: function() {
    return this.each(function() { this.disabled = false; });
  },
  disable: function() {
    return this.each(function() { this.disabled = true; });
  },
  check: function() {
	return this.each(function() { this.checked = true; });
  },
  uncheck: function() {
	return this.each(function() { this.checked = false; });
  }
});
// https://gist.github.com/948808
Modernizr.addTest('cssscrollbar', function() {
	var test = document.createElement('div'), // Tested Element
		fake = false, // Fake body
		root = document.body || (function () {
			fake = true;
			return document.documentElement.appendChild(document.createElement('body'));
		}()),
		property = 'scrollbar{width:0px;}';
	// Force scrollbar
	test.id = '__sb';
	test.style.overflow = 'scroll';
	test.style.width = '40px';
	// Apply scrollbar style for all vendors
	test.innerHTML = '&shy;<style>#'+Modernizr._prefixes.join(property+' #__sb::').split('#').slice(1).join('#')+property+'</style>';
	root.appendChild(test);
	// If css scrollbar is supported, than the scrollWidth should not be impacted
	var ret = test.scrollWidth == 40;
	// Cleaning
	document.body.removeChild(test);
	if (fake) {
		document.documentElement.removeChild(root);
	}
	return ret;
});
_.mixin({
	firstOrAll: function(array) {
		if (1 === array.length) {
	    	return array[0];
		} 
		return array;   
    }
});

//load plugins:
//* http://plugins.jquery.com/project/jquery-plugins
$.plugins({ path: '/js/plugins/', plugins: [
//{ id:'ID', js: 'javascript.js', css: 'css.css' sel: 'css.select[or=true]', ext: 'jquery-ext', fn:'jquery-fn' },
  { id:'browser', js: 'browser.js', ext: 'browserTest' },
  { id:'easywidgets', js: 'easywidgets.js' },
  { id:'json', js: 'json-1.3.js', ext:'toJSON' },
  { id:'metadata', js: 'metadata.js' }, //kein ext, das stoert jQueryUI
  { id:'rating', js: 'rating.js', css: '/css/s/games.css', fn:'rating' },
  { id:'periodicalupdater', js: 'periodicalupdater.js', ext:'PeriodicalUpdater' },
  { id:'dimscreen', js: 'dimscreen.js', ext:'dimScreen' },
  { id:'tinyjbox', js: 'tinyjbox.js', css: '/css/tinyjbox.css', ext:'tinyJBox' },
  { id:'jgrowl', js: 'jgrowl.js', css: '/css/notification.css' },
  { id:'contextmenu', js: 'contextmenu.js' },
  { id:'jscrollpane', js: 'jscrollpane.js' },
  { id:'mousewheel', js: 'mousewheel.js' },
  { id:'scrollto', js: 'scrollto.min.js' },
  { id:'validate', js: 'validate.js' },
  { id:'tooltip', js: 'tooltip.js' },
  { id:'markitup', js: 'markitup.js', css: '/css/markitup.css' },
  { id:'markdown', js: 'markitup/markdown.js'},
  { id:'blockui', js: 'blockui.js'},
  { id:'activity', js: 'activity.js'},
  //ie-fixes *grrr*
  { id:'iefixbuttons', js: 'iefixbuttons.js' }
]});
/**
 * ready-function
 */
$(function() {
  addBrowserClass();
  if (jQuery.browser.msie) {
    $.requires("iefixbuttons",function(){ $('body').ieFixButtons(); });
  }
  //use jshelper
  pagedata = jshelper;
  if (pagedata.loggedin) { //wenn eingeloggt
    $('#refreshlose').click(reloadlose);
    reloadlose();

	// notifications
	yepnope({
		test: pagedata.notification,
		yep: ['/js/plugins/jgrowl.js', '/css/notification.css', '/js/lcgrowl.js']
	});
	
	// startseite
	yepnope({
		test: (pagedata.seite == 'start'),
		yep: ['/js/plugins/easywidgets.js', '/js/lcwidgets.js']
	});

	// pncenter
	yepnope({
		test: (pagedata.seite == 'user/pncenter'),
		yep: ['/js/plugins/contextmenu.js', '/js/lcpncenter.js']
	});

	// nickpage
	yepnope({
		test: (pagedata.seite == 'user/nickpage'),
		yep: ['/js/lcnickpage.js']
	});

	// ideenschmiede
	yepnope({
		test: (pagedata.seite.substr(0,9) == 'ideaforge'),
		yep: ['/js/ideaforge.js']
	});

	// games
	yepnope({
		test: (typeof pagedata.game != "undefined"),
		yep: ['/js/plugins/metadata.js', '/js/plugins/rating.js', '/css/s/games.css', '/js/lcgame.js']
	});

	// nickmenu
	yepnope({
		test: (pagedata.loadnickmenu == true),
		yep: ['/js/plugins/contextmenu.js', '/js/lcnickmenu.js']
	});

	// labs
	yepnope({
		test: (typeof localStorage.lclabs != 'undefined'),
		yep: ['/js/labs/labs.js']
	});

	$('html').addClass($('#page #content').attr("class"));
  }else{
	if($('#ok.ok_logout').size()>0) setTimeout(RemoveBars,2500);
	if (pagedata.seite=="user/register" && $.browser.msie!==true) {
		$.include("/data/anmeldung.js");
    }else if(pagedata.seite=="user/register" && $.browser.msie) {
		$('html').removeClass('js');
	}
  }
  $(document).trigger("lc:loaded");
});

$(document).bind("lc:loaded",function(){ //piwik
	if (typeof document.location.host != 'undefined' && document.location.host != 'losecatcher.de') return; // exclude dev
	var piwikSiteID = 1;
	if (pagedata.loggedin) piwikSiteID = 2;
	var pkBaseURL = (("https:" == document.location.protocol) ? "https://losecatcher.de/piwik/" : "http://losecatcher.de/piwik/");
	$.include(pkBaseURL + "piwik.js",function(){
		try {
			var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", piwikSiteID);
			piwikTracker.trackPageView();
			//piwikTracker.enableLinkTracking();
		} catch( err ) {}
	});
});

/********** FUNCTIONS *********/
function addBrowserClass() {
	$('html').addClass('js');
	$.browserTest(navigator.userAgent);
	if(!$.browser.msie) {$('html').addClass('notmsie');}
}
/**
 * Bar-Functions
 * @return null
 **/
statusBars=[];
function ErrorBar(text,effect) {
	if(typeof effect=="undefined") effect = true;
	_addBar('error',text,effect);
}
function SuccessBar(text,effect) {
	if(typeof effect=="undefined") effect = true;
	_addBar('ok',text,effect);
}
function _addBar(id,text,effect) {
	if($('#'+id).size()>0) {
		$('#'+id).html(text);
		if(effect==true) $('#'+id).effect("pulsate",{ times: 2 },600);
	}else{
		bar=$('<div id="'+id+'">').html(text);
		if(effect==true) bar.hide();
		$('#header').after(bar);
		if(effect==true) $(bar).show("blind", 600);
	}
	statusBars.push(id);
}

function RemoveBars(effect) {
	if(typeof effect!="boolean") effect = true;
	if(statusBars.indexOf('ok')==-1 && $('#ok').size()>0) { statusBars.push("ok");}
	if(statusBars.indexOf('error')==-1 && $('#error').size()>0) { statusBars.push("error");}
	nbars=statusBars;
	if(effect==true) {
	jQuery.each(statusBars,function(i) {
		$('#'+this).hide("blind", 600, function(){ $(this).remove(); });
		nbars=_.without(nbars,this);
	});
	}else{
	jQuery.each(statusBars,function() {
		$("#"+this).remove();
		nbars=_.without(nbars,this);
	});
	}
	statusBars=nbars;
}

function reloadlose() {
  $.getJSON("/data/losestand.php",
    function(data){
      if (data.error == true) {
	     alert(data.msg);
	  } else {
	     $('#lose').html($.formatNum(data.lose, '.'));
	     $('#bonuslose').html($.formatNum(data.bonuslose, '.'));
	     $('#ap').html($.formatNum(data.ap, '.'));
	  }
  });
}
function number_format(n,t) {return $.formatNum(n,t);}
function nf(n,t) {return $.formatNum(n,t);}

function k2p(inputelement) {
  v = inputelement.value;
  while (v.indexOf(",") > -1) {
    pos = v.indexOf(",");
    ausgabe = "" + (v.substring(0, pos) + "." + v.substring((pos + 1), v.length));
  }
  inputelement.value = v;
  return true;
}

$.fn.insertAtCaret = function (myValue) {
        return this.each(function(){
                //IE support
                if (document.selection) {
                        this.focus();
                        sel = document.selection.createRange();
                        sel.text = myValue;
                        this.focus();
                }
                //MOZILLA/NETSCAPE support
                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();
                }
        });

};
