/*global $,log,app,style,svc,ml,confmodell,modeldisplayCtrl,layoutManager,gui_locked */
/*global blackbird */

/**
 * Selects an option by value
 * taken from http://www.texotela.co.uk/code/jquery/select/ and adapted for our needs
 */
$.fn.selectOptions = function (value, clear)
{
	this.each(
		function()
		{
			var o = this.options;
			var oL = o.length;
			for(var i = 0; i<oL; i++)
			{
				if(o[i].value == value)
				{
					o[i].selected = clear;
					return this;
				}
			}
		}
	);
	return this;
};

$.fn.selectedValues = function()
{
	var v = [];
	this.find("option:selected").each(
		function()
		{
			v[v.length] = this.value;
		}
	);
	return v;
};

/**
 * Adds (single/multiple) options to a select box (or series of select boxes)
 *
 * @name     addOption
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     jQuery
 * @example  $("#myselect").addOption("Value", "Text"); // add single value (will be selected)
 * @example  $("#myselect").addOption("Value 2", "Text 2", false); // add single value (won't be selected)
 * @example  $("#myselect").addOption({"foo":"bar","bar":"baz"}, false); // add multiple values, but don't select
 *
 */
$.fn.addOption = function()
{
	var add = function(el, v, t, sO)
	{
		var option = document.createElement("option");
		option.value = v; option.text = t;
		// get options
		var o = el.options;
		// get number of options
		var oL = o.length;
		if(!el.cache)
		{
			el.cache = {};
			// loop through existing options, adding to cache
			for(var i = 0; i < oL; i++)
			{
				el.cache[o[i].value] = i;
			}
		}
		// add to cache if it isn't already
		if(typeof el.cache[v] === "undefined") {el.cache[v] = oL;}
		el.options[el.cache[v]] = option;
		if(sO)
		{
			option.selected = true;
		}
	};
	
	var a = arguments;
	if(a.length == 0) return this;
	// select option when added? default is true
	var sO = true;
	// multiple items
	var m = false;
	// other variables
	var items, v, t;
	if(typeof(a[0]) == "object")
	{
		m = true;
		items = a[0];
	}
	if(a.length >= 2)
	{
		if(typeof(a[1]) == "boolean") sO = a[1];
		else if(typeof(a[2]) == "boolean") sO = a[2];
		if(!m)
		{
			v = a[0];
			t = a[1];
		}
	}
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return;
			if(m)
			{
				for(var item in items)
				{
					add(this, item, items[item], sO);
				}
			}
			else
			{
				add(this, v, t, sO);
			}
		}
	);
	return this;
};


function set_menu_act(src)
{
	if (src)
	{
		src = src.replace(/_ro/, '');
		src = src.replace(/_act/, '');
	}
	return src.substring( 0, src.search(/(\.[a-z]{3}$)/) ) + '_ro' + src.match(/(\.[a-z]{3}$)/)[0];
}

function set_menu_visited(src)
{
	if (src)
	{
		src = src.replace(/_ro/, '');
		src = src.replace(/_act/, '');
	}
	return src.substring( 0, src.search(/(\.[a-z]{3}$)/) ) + '_act' + src.match(/(\.[a-z]{3}$)/)[0];
}

function set_menu_next(src)
{	
	if (src)
	{
		src = src.replace(/_ro/, '');
		src = src.replace(/_act/, '');
	}
	return src;
}


/* Images mit Klasse "roll_over" markieren, dann wird automatisch die Funktionalitaet fuers Rollover
 * ergaenzt; verwendet wird immer ein gleichnamiges Image + _ro"
 * inkludiert ist Preloading der Files
 * */

PEPS = {};

PEPS.rollover =
{
	init: function()
	{
		this.preload();
		
		// alle IMG-Klassen die "roll_over"	enthalten mit dem Roll-Over Effekt ausstatten
		$('img[class*="roll_over"]').hover(
			function () { $(this).attr( 'src', PEPS.rollover.newimage($(this).attr('src')) ); },
			function () { $(this).attr( 'src', PEPS.rollover.oldimage($(this).attr('src')) ); }
		);
	},

	preload: function()
	{
		$(window).bind('load', function() {
			$('.roll_over').each( function( key, elm ) { $('<img>').attr( 'src', PEPS.rollover.newimage( $(this).attr('src') ) ); });
		});
	},
   
	newimage: function( src )
	{
		return src.substring( 0, src.search(/(\.[a-z]{3}$)/) ) + '_ro' + src.match(/(\.[a-z]{3}$)/)[0];
	},
   
	oldimage: function( src )
	{
		return src.replace(/_ro/, '');
	}
};


/**
 * Opens new window and returns its object.
 */
function openWindow(winURL, winName, winParams)
{
	return window.open(winURL, winName, winParams);
}

function hasVerticalScrollbar(elementId)
{
    if (document.getElementById(elementId).scrollHeight > document.getElementById(elementId).offsetHeight)
		return true;
	else
		return false;
}

function getMarginsSum(cssSelektor)
{
	var marginTop = 0;
	var marginBottom = 0;

	$(cssSelektor).each(function () {	
		var marginTopPx = $(this).css("margin-top");
		if (marginTopPx)	// else: margin was not explicitly set to "XYZpx" in CSS
		{
			var tempTop = eval(marginTopPx.substr(0, marginTopPx.indexOf("px")));

			if (!tempTop || isNaN(tempTop))		// necessary for IE
				tempTop = 0;
			
			marginTop += tempTop;
		}
		
		var marginBottomPx = $(this).css("margin-bottom");
		if (marginBottomPx)	// else: margin was not explicitly set to "XYZpx" in CSS
		{
			var tempBottom = eval(marginBottomPx.substr(0, marginBottomPx.indexOf("px")));
			
			if (!tempBottom || isNaN(tempBottom))	// necessary for IE
				tempBottom = 0;
				
			marginBottom += tempBottom;
		}
	});

	return marginTop + marginBottom;
}

function getPaddingsSum(cssSelektor)
{
	var paddingTop = 0;
	var paddingBottom = 0;

	$(cssSelektor).each(function () {	
		var paddingTopPx = $(this).css("padding-top");
		if (paddingTopPx)	// else: padding was not explicitly set to "XYZpx" in CSS
		{
			var tempTop = eval(paddingTopPx.substr(0, paddingTopPx.indexOf("px")));

			if (!tempTop || isNaN(tempTop))		// necessary for IE
				tempTop = 0;
			
			paddingTop += tempTop;
		}
		
		var paddingBottomPx = $(this).css("padding-bottom");
		if (paddingBottomPx)	// else: padding was not explicitly set to "XYZpx" in CSS
		{
			var tempBottom = eval(paddingBottomPx.substr(0, paddingBottomPx.indexOf("px")));
			
			if (!tempBottom || isNaN(tempBottom))	// necessary for IE
				tempBottom = 0;
				
			paddingBottom += tempBottom;
		}
	});

	return paddingTop + paddingBottom;
}

function getBordersSum(cssSelektor)
{
	var borderTop = 0;
	var borderBottom = 0;

	$(cssSelektor).each(function () {	
		var borderTopPx = $(this).css("border-top-width");
		if (borderTopPx)	// else: border was not explicitly set to "XYZpx" in CSS
		{
			var tempTop = eval(borderTopPx.substr(0, borderTopPx.indexOf("px")));

			if (!tempTop || isNaN(tempTop))		// necessary for IE
				tempTop = 0;
			
			borderTop += tempTop;
		}
		
		var borderBottomPx = $(this).css("border-bottom-width");
		if (borderBottomPx)	// else: border was not explicitly set to "XYZpx" in CSS
		{
			var tempBottom = eval(borderBottomPx.substr(0, borderBottomPx.indexOf("px")));
			
			if (!tempBottom || isNaN(tempBottom))	// necessary for IE
				tempBottom = 0;
				
			borderBottom += tempBottom;
		}
	});

	return borderBottom + borderBottom;
}


function getContentHeight(json)
{
	var contentHeight = 0;

	if (json.innerHeights) {
		for (var i = 0; i < json.innerHeights.length ; i++) {
			contentHeight += $(json.innerHeights[i]).innerHeight();
		}
	}
	
	if (json.marginSums) {
		for (var i = 0; i < json.marginSums.length ; i++) {
			contentHeight += getMarginsSum(json.marginSums[i]);
		}
	}
	
	if (json.paddingSums) {
		for (var i = 0; i < json.paddingSums.length ; i++) {
			contentHeight += getPaddingsSum(json.paddingSums[i]);
		}
	}
	
	return contentHeight;
}

// Ersetzen von Zeichen welche die JQuery Selektoren nicht verwenden koennen
function replaceWeirdChars(old_string)
{
	var new_string = old_string.replace(/\+/g,"\\+").replace(/\//g,"\\/").replace(/\./g,"\\.").replace(/\ /g,"\\ ").replace(/\&/g,"\\&").replace(/\$/g,"\\$");
	return new_string;
}

function getWindowHeight()
{
	return self.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
}


function numberToLocaleString (num0, prec) {
	if(typeof num0 != 'number') throw new TypeError("numberToLocaleString(): number expected");

	var result = '';
	var num = Math.floor(num0).toFixed(0);
	
	while(num.length > 0) {
		var spos = (num.length-3 > 0) ? num.length-3 : 0;
		if(thousandSeparator && result.length > 0)
			result = num.substr(spos) + thousandSeparator + result;
		else
			result = num.substr(spos) + result;
		num = num.substring(0, spos);
	}
	
	if (prec && prec > 0){
		num = num0.toFixed(prec);
		result += commaSeparator + num.substr(num.length-prec);
	}
	
	return result;
}


// per asynchronen REST-Request Texte aus dem Language-Ressource File holen
function loadTextFromLanguageRessource(key, callback)
{
	var url = svc.text_link;
	url = url.replace('$text$', key).replace('$lang$',lang).replace('$style$',style.value);
	$.getJSON(url , function(json) {
		callback(json.text);
	});
}

// Console Log
function log(msg, msg2, obj) {
	if (typeof console !== "undefined") {
		if(typeof msg2 !== "undefined") {
			msg = msg + ": " + msg2;
		}
		console.log(msg);	
		
		if(typeof obj !== "undefined") {
			console.log(obj);
		}
	} else if (typeof blackbird !== "undefined") {
		if(typeof msg2 !== "undefined") {
			msg = msg + ": " + msg2;
		}
		msg = msg.replace(/</g,'&lt;').replace(/>/g,'&gt;');
		blackbird.info(msg);	
		
		if(typeof obj !== "undefined") {
			blackbird.info($.toJSON(obj));
		}
	}
}

// makeTable: Tabelle aus Liste erzeugen
function makeTable(list, colums, makeCell) {
	var $table = $("<table/>", {"class": "layout"});
	
	if (list.length === 0) {
		return $table;
	}		
	
	var $tr;
	var row = 0;
	var col = colums;
	
	for (var i = 0; i < list.length; i++) {
		col += 1;
		if (col === colums+1) {
			col = 1;
			row += 1;
			$tr = $("<tr/>");
			$table.append($tr);
		}
		var $cell = makeCell(list[i], row, col, i);
		var $td = $("<td/>").append($cell);
		$tr.append($td);
	}
	if (list.length % colums !== 0) {
		for (i = colums - list.length % colums; i > 0; i--) {
			var $td = $("<td/>");
			$tr.append($td);
		}
	}	
	return $table;
}

function getDateString() {
	var now = new Date();
	var dd = now.getDate() < 10 ? "0" + now.getDate() : String(now.getDate());
	var mm = (now.getMonth()+1) < 10 ? "0" +  (now.getMonth()+1) : String(now.getMonth()+1);
	var yy = String(now.getFullYear()).substr(2,2);
	var hh = now.getHours() < 10 ? "0" +  now.getHours() : String(now.getHours());
	var nn = now.getMinutes() < 10 ? "0" +  now.getMinutes() : String(now.getMinutes());
	
	return dd + "." + mm + "." + yy + " " + hh + ":" + nn;
}
