﻿/*
 *  Contains functions that are used in more than one places
 *  
 *
 */
var bbbbbb;
try{
	bbbbbb = Prototype.Browser.IE;
}
catch(e){
	bbbbbb = {
		msie: /msie/.test(navigator.userAgent)
	};
}
function pix(str)   {
	return Math.round(str) + 'px';
}

function formatDistance(distanceInMeters, metersSymbol, kilometersSymbol) {
	if (distanceInMeters < 1000) {
		return distanceInMeters + " " + metersSymbol;  // "345 м"
	}
	else if (distanceInMeters < 100000) {
		return Math.roundFloat(distanceInMeters / 1000, 1) + " " + kilometersSymbol;  // "23.4 км"
	}
	else {
		return Math.roundFloat(distanceInMeters / 1000, 0) + " " + kilometersSymbol;  // "134 км"
	}	
}

function log() {
	var args = $A(arguments);
	if (window.opera)
		opera.postError(args.inspect());
	if (window.console)
		if (bbbbbb.msie)
			console.log(args.inspect());
		else
			console.log(args);
}

function popUp(w, h, url) {
	var x = parseInt(screen.availWidth / 2 - w / 2);
	var y = parseInt(screen.availHeight / 2 - h / 2);
	var parameter = "width=" + w + ",height=" + h + ",left=" + x + ",top=" + y + ",toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no";
	var win = window.open(url, "popup", parameter);
	if (win) win.focus();
	return !win;
}
//  Common Methods
function emptyF() { return; }
function falseF() { return false; }
function selfF(x) { return x; }
function cancelEvent(event) { event.stop(); return false; };
function preventEvent(event) { if(event.stopPropagation) event.stopPropagation(); else event.cancelBubble = true; }
function customCancelEvent(event) {stopEvent(event);return false;}


function newElement(tag, parent, attributes) {
    var el = document.createElement(tag);
    return updateElement(el, parent, attributes);
}

function updateElement(el, parent, attributes)	{
	for (var att in attributes) {
        if (att == "className")
            el.className = attributes[att];
        else
            el.setAttribute(att, attributes[att]);
    }

    if (parent)
        parent.appendChild(el);

    return el;
}

function newElementWithNamespace(tag, parent, attributes, namespace)    {
	var el = namespace && document.createElementNS ? document.createElementNS(namespace, tag) : document.createElement(tag);
	return updateElement(el, parent, attributes);
}

function createImage(src, size, parent, attributes)
{
	var image = newElement('img', parent, attributes);
		image.src = src;
	
	if (size != null)	{
	    image.style.width = pix(size.width);
	    image.style.height = pix(size.height);
	}

	return image;
}

function isPNG(src)
{
	return src.match(/\.png$/i) || src.match(/GetLine|IconPaintSlots/);
}

function changeImage(image, src, size)
{
	$(image).setSize(size);

	if (isPNG(src) && Prototype.Browser.IE && (BGMap.b.version < 7) && image.tagName.toLowerCase() == 'div')
	{
		// image is a styled <div>
		// size it first
		var trueImage = $(image.firstChild);
		trueImage.setSize(size);
		
		// change <div> filter
		image.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="'+src+'");';
		trueImage.src = src;
	}
	else
	{
		image.src = src;
	}
}

function makeUnselectable(img) {
	if (arguments.length == 1)
		var elements = [img];
	else
		var elements = arguments;

	$A(elements).each(function (image) {
		if (Prototype.Browser.IE)			
				image.unselectable = "on";
		else {
			if (Prototype.Browser.Gecko)
				image.style.MozUserSelect = "none";
			else if (Prototype.Browser.WebKit)
				image.style.webkitUserSelect = "none";

			image.oncontextmenu = function () { return false; };
		}
	});
}
function cleanUpUnselectableIE(img)	{
	if (Prototype.Browser.IE && img.tagName.toLowerCase() == 'img') {
		img.unselectable = null; img.galleryImg = null; img.onselectstart = null; img.onload = null;
	}
}

function removeChildrenRecursively(node)
{
    removeChildrenRecursivelySafe(node);
}
/* IE fixed Garbage collection */
function removeChildrenRecursivelySafe(node){
	if (!node) return;
    while (node.hasChildNodes()) {
        removeChildrenRecursivelySafe(node.firstChild);
        removeChildSingleSafe(node.firstChild);
    }
}
function removeChildSafe(node) {
    if(!node) return;
    removeChildrenRecursivelySafe(node);
    
    removeChildSingleSafe(node);
}
function removeChildSingleSafe(node)	{
	node.parentNode.removeChild(node);
	if(bbbbbb.msie)
		discardElement(node);
}
function discardElement(el) {
    var bin = document.getElementById("IELeakGarbageBin");

    if (!bin) {
        bin = document.createElement("DIV");
        bin.id = "IELeakGarbageBin";
        bin.style.display = "none";
        document.body.appendChild(bin);
    }
	
	bin.appendChild(el);
    bin.innerHTML = "";
}
function toAbs(element) {
    element.style.position = "absolute";
    return element;
}
function makeRelative(element)  {
    element.style.position = "relative";
    return element;
}

function setPosition(element, x, y)   {
    var pos;
    if(x instanceof Pos && y == undefined)
        pos = x;
    else
        pos = new Pos(x, y);
    
    element.style.left = pix(pos.x);
    element.style.top = pix(pos.y);
}

function numToStr(number, length)   {
    var str = number + "";
    while(str.length < length)  { str = "0" + str; }
    return str;
}

Math.roundFloat = function(number, precision) {
    var p = Math.pow(10, precision);
    var a = Math.round(number*p);
    return a/p || number;
}

Math.rnd = function(min, max) {
    return Math.round(Math.random() * (max - min) + min);
}
Function.prototype.wait = function(ms, context) {
	if (this.timeout) {
		clearTimeout(this.timeout);
		delete this.timeout;
	}
	var args = $A(arguments); args.shift(); args.shift();
	this.timeout = setTimeout(function() { this.apply(context || this, args); } .bind(this), ms || 0);
}

//  Common Objects
function Pos(x, y)  {
    this.x = x;
    this.y = y;
}
Pos.prototype = {
	type: function(){return "pos"},
    equals: function(pos){return this.x == pos.x && this.y == pos.y},
    toString: function() { return this.x + "," + this.y },
    clone: function() { return new Pos(this.x, this.y) },
    distance: function(pos) { var dx = Math.abs(this.x - pos.x); var dy = Math.abs(this.y - pos.y); return Math.sqrt(dx*dx + dy*dy); }
};

function GeoPos(lon, lat)   {
    this.lon = lon;
    this.lat = lat;
}
GeoPos.prototype = {
	type: function () { return "geopos" },
	equals: function (pos) { return this.lon == pos.lon && this.lat == pos.lat; },
	less: function (pos) { return (this.lon < pos.lon) && (this.lat < pos.lat); },
	more: function (pos) { return (this.lon > pos.lon) && (this.lat > pos.lat); },
	toString: function () { return Math.roundFloat(this.lon, 5) + "," + Math.roundFloat(this.lat, 5); }
};

function Size(w, h) {
    this.width = w;
    this.height = h;
}
Size.prototype = {
	type: function() { return "size" },
	clone: function() { return new Size(this.width, this.height); },
	toString: function() { return this.width + "," + this.height; }
};

function generateException(name) {
	window[name] = function(message) {
		this.name = name;
		this.message = message;
	}
};

function filterInput(element, regEx) {
	var f1 = function (regEx, e) {
		var key = e.keyCode || e.charCode;
		if (e.ctrlKey || e.altKey || key <= 46)
			return true;

		key = String.fromCharCode(key);
		return regEx.test(key);
	} .bind(this, regEx);

	element.onkeypress = f1;

	var f2 = function (regEx, e) {
		var el = e.element()
		el.value = el.value.match(regEx).join("");
	} .bind(this, regEx);

	element.onkeyup = f2;
}
///-----------------------------------------------------

function stripTagsWithReplace(sourceStr, replaceStr) {
	return sourceStr.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, replaceStr).strip();
}

///------------------------------------prototype fixes/adds
String.prototype.firstLetterUp = function () { return this.charAt(0).toUpperCase() + this.substring(1); }

Element.addMethods({
	absolutize: function (element) {
		element = $(element);
		element.setStyle({ position: 'absolute' });
	},
	setPosition: function (element, pos) {
		element = $(element);
		element.setStyle({ top: pix(pos.y), left: pix(pos.x) });
	},
	setSize: function (element, size) {
		element = $(element);
		element.setStyle({ width: pix(size.width), height: pix(size.height) });
	},
	isContainedBy: function (element, otherElement) {
		element = $(element);
		otherElement = $(otherElement);

		return $A(otherElement.getElementsByTagName(element.tagName)).detect(function (child) { return child == element });
	},
	getPosition: function (element) {
		return new Pos(parseInt(element.style.left), parseInt(element.style.top));
	}
});
///---------------------------------------------------
function openLightbox(url, width, height) {
	width = width || 800;
	height = height || 500;

	var body = document.getElementsByTagName('body')[0];
	var lightboxOverlay = newElement("div", body, { id: "lightboxOverlay" });

	var lightboxContent = $(newElement("div", body, { id: "lightboxContent" }));
	lightboxContent.setStyle({ width: pix(width), height: pix(height), marginLeft: pix(-width / 2), marginTop: pix(-height / 2) });
	lightboxContent.innerHTML = "<iframe src='" + url + "' frameborder='0' width='" + width + "px' height='" + (height - 20) + "px' allowtransparency='true'></iframe><br/><center><a href='javascript:lightboxClose();'>Bitte hier schlie&szlig;en!</a><center>";
}
function lightboxClose() {
	$("lightboxContent").remove();
	$("lightboxOverlay").remove();
}
