function Berechnung(){
	// body mass index
	var gewicht=$("#gewicht").attr("value");
	var grosse=$("#grosse").attr("value");
	var alter=$("#alter").attr("value");
	if (gewicht==""){ alert("Bitte geben Sie Ihr Gewicht ein"); return; }
	$('#result').show();
	// calculations
	var wert=gewicht/((grosse/100)*(grosse/100));
	var bmi= Math.round(wert,2);
	var bmiopt=" ";

	if (alter>64) {bmiopt="24 und 29";}
	else if (alter>54) {bmiopt="23 und 28";}
	else if (alter>44) {bmiopt="22 und 27";}
	else if (alter>34) {bmiopt="21 und 26";}
	else if (alter>24) {bmiopt="20 und 25";}
	else {bmiopt="19 und 24";}

	$("#unt").html("<b>In Ihrem Alter liegt der optimale BMI <font color=red> zwischen "+bmiopt+" </font></b>");
	$("#ob").html("<b>Ihr BMI betr&auml;gt:  <font color=red> "+bmi+"</font></b>");
	return true;
}

// smooth scrollTo anchors
function scrollInit() {
	$('a[@href^="#"]').click(function() {
		var parts			= this.href.split('#');
		var scrolltarget	= '#' + parts[1];
		$(scrolltarget).ScrollTo(300);
		return false;
	});
};


function intval( mixed_var, base ) {
	// Get the integer value of a variable using the optional base for the
	// conversion
	var tmp;
	
	if( typeof( mixed_var ) == 'string' ){
		tmp = parseInt(mixed_var*1);
		if(isNaN(tmp) || !isFinite(tmp)){
			return 0;
		} else{
			return tmp.toString(base || 10);
		}
	} else if( typeof( mixed_var ) == 'number' && isFinite(mixed_var) ){
		return Math.floor(mixed_var);
	} else{
		return 0;
	}
}

var pop = null;
function downPopup() {
	if (pop && !pop.closed) pop.close();
}

function popup(url,w,h,r) {
	if (!url) return true;
	w = (w) ? w += 20 : 390;  // 300px*500px is the default size
	h = (h) ? h += 25 : 500;
	if(r=="") r = "no";
	var args = 'width='+w+',height='+h+',resizable=yes,scrollbars=yes';
	downPopup();
	pop = window.open(url,'',args);
	return (pop) ? false : true;
}

function openPopup(url,w,h) {
	return popup(url,w,h);
}
function wOpenPopupURL(url,w,h) {
	w = intval(w);
	h = intval(h);
	var args = 'width='+w+',height='+h+',resizable=no,scrollbars=no';
	window.open(url,'',args);
	return;
}

window.onunload = downPopup;
window.onfocus = downPopup;

/**
 * contactform validation and behavior
 * 
 */
function contactform() {
	var msg = document.getElementById("message");
	if($.trim($(msg).attr('value')) == '' && $(document.getElementById("contactform")).hasClass('NotPassed')) {
		$(msg).parent().addClass('error').attr({style:"width:540px!important"}).find("textarea").css({top:'5px'});
	}
	/* fluid typing */
	$("#zip").keyup(function(event){ if(this.value.length > 4 && (event.keyCode > 46)) { $("#city").focus(); }});
	$("div.NotPassed #Email").bind('keyup keypress',function(){
		// if(event.keyCode > 46) {
			if (isemail(this.value)) {
				$(this).parent().removeClass('error');
			} else {
				if ($(this).parent().hasClass('error')) {
				} else {
					$(this).parent().addClass('error');
				}
			}
		// }
	});
	$("div.NotPassed #firstname, div.NotPassed #lastname, div.NotPassed #message").bind('keyup keypress',function(){
			if(this.value.length > 0) {
				$(this).parent().removeClass('error');
			} else {
				if ($(this).parent().hasClass('error')) {
				} else {
					$(this).parent().addClass('error');
				}
			}
	}); 
	/* fix textarea */
	$("#message").focus(function(){
		this.value = this.value.trim();
	});
	var url = document.getElementById("url");
	var zip = document.getElementById("zip");
	$(zip, url).numeric();
	if($.trim($(url).attr('value')) == '' && $(document.getElementById("contactform")).hasClass('NotPassed')) {
		$(url).parent().addClass('error');
	}
	$("div.NotPassed #url").bind('keyup keypress',function(){
			if(this.value.length > 3) {
				$(this).parent().removeClass('error');
			} else {
				if ($(this).parent().hasClass('error')) {
				} else {
					$(this).parent().addClass('error');
				}
			}
	});
}

function parse_url (str, component) {
    // http://kevin.vanzonneveld.net
    // + original by: Steven Levithan (http://blog.stevenlevithan.com)
    // + reimplemented by: Brett Zamir (http://brett-zamir.me)
    // % note: Based on
	// http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
    // % note: blog post at http://blog.stevenlevithan.com/archives/parseuri
    // % note: demo at
	// http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
    // % note: Does not replace invaild characters with '_' as in PHP, nor does
	// it return false with
    // % note: a seriously malformed URL.
    // % note: Besides function name, is the same as parseUri besides the
	// commented out portion
    // % note: and the additional section following, as well as our allowing an
	// extra slash after
    // % note: the scheme/protocol (to allow file:/// as in PHP)
    // * example 1:
	// parse_url('http://username:password@hostname/path?arg=value#anchor');
    // * returns 1: {scheme: 'http', host: 'hostname', user: 'username', pass:
	// 'password', path: '/path', query: 'arg=value', fragment: 'anchor'}

    var  o   = {
        strictMode: false,
        key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
        q:   {
            name:   "queryKey",
            parser: /(?:^|&)([^&=]*)=?([^&]*)/g
        },
        parser: {
            strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
            loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/\/?)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // Added
																																																						// one
																																																						// optional
																																																						// slash
																																																						// to
																																																						// post-protocol
																																																						// to
																																																						// catch
																																																						// file:///
																																																						// (should
																																																						// restrict
																																																						// this)
        }
    };

    var m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
    uri = {},
    i   = 14;
    while (i--) {uri[o.key[i]] = m[i] || "";}
    // Uncomment the following to use the original more detailed (non-PHP)
	// script

        uri[o.q.name] = {};
        uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
        if ($1) uri[o.q.name][$1] = $2;
        });
        return uri;


    switch (component) {
        case 'PHP_URL_SCHEME':
            return uri.protocol;
        case 'PHP_URL_HOST':
            return uri.host;
        case 'PHP_URL_PORT':
            return uri.port;
        case 'PHP_URL_USER':
            return uri.user;
        case 'PHP_URL_PASS':
            return uri.password;
        case 'PHP_URL_PATH':
            return uri.path;
        case 'PHP_URL_QUERY':
            return uri.query;
        case 'PHP_URL_FRAGMENT':
            return uri.anchor;
        default:
            var retArr = {};
            if (uri.protocol !== '') {retArr.scheme=uri.protocol;}
            if (uri.host !== '') {retArr.host=uri.host;}
            if (uri.port !== '') {retArr.port=uri.port;}
            if (uri.user !== '') {retArr.user=uri.user;}
            if (uri.password !== '') {retArr.pass=uri.password;}
            if (uri.path !== '') {retArr.path=uri.path;}
            if (uri.query !== '') {retArr.query=uri.query;}
            if (uri.anchor !== '') {retArr.fragment=uri.anchor;}
            return retArr;
    }
}

function isemail(email) {
	return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(email);
}

function notabindex() {
	$('form input, form textarea, form select').removeAttr('tabindex');
}

function handleXML(response,pageuri) {
	var temp = parse_url(pageuri);
	var file = temp.directory+temp.file;
	var domdoc = response;
	// the ID of the parent of the selected page
	var $item = $(domdoc).find('navPoint[link='+file+']:last').parent();
	var id = $item.attr('id');
	var html = '';
	var $list = $(domdoc).find('navPoint[id='+id+'] > navPoint');
	$list.each(function(){
		if (file == $(this).attr('link')) {
			html += '<li class="active">';
		} else {
			html += '<li>';
		}
		html += '<a href="'+$(this).attr('link')+'?navid='+$(this).attr('id')+'">'+$(this).attr('text')+'</a></li>';
	});
	$('#pagenav ul').html(html).parent().append('<div class="navbottom"></div>');
}

/**
 * load Navigation XML and append Navigation in case that navid Parameter is
 * missing
 */
 
function AJAXNavigation() {
	if ($("#pagenav").length > 0) {
		if ($("#pagenav ul li").length==0) {
			var currentpage = document.location;
			var proxy = '/kraftquelle-herz/lib/php/exe/AJAXproxy.php';
			var xmlurl = '/kraftquelle-herz/wGlobal/content/navigations/standard.wNavigation.php';
			$.ajax({
				type: "GET",
				url: proxy,
				data: {file: xmlurl},
				dataType: "xml",
				cache: true,
				success: function(responseText){
					handleXML(responseText,currentpage);
				}
			});
		} // not needed if static HTML navigation is present
	} // not needed if there's no navigation
}

function NavigationActiveStateFix() {
	var temp = parse_url(document.location);
	var page = temp.directory+temp.file;
	$("#pagenav ul li a").each(function(){
		var tokens = parse_url($(this).attr('href'));
		var linktarget = tokens.directory+tokens.file;
		if ( linktarget == page ) {
			$(this).parent().addClass('active');
		}
	});
}

$(document).ready(function(){
		notabindex();
		$('#gewicht, #alter, #grosse').numeric();
		$(".buttonStyle").click(function(){ Berechnung(); });
		$("#blockContent .openPopup,#blockRight .openPopup").click(function(){
			return openPopup(this.href);
		});
		$("li > a.openPopup").click(function(){
			return openPopup(this.href,620,(jQuery(window).height() - 30));
		});
		contactform();
		AJAXNavigation();
		NavigationActiveStateFix();
		if($("#map")) { onLoadGPX(); }
		query2Action();
	}
);

function query2Action() {
	if ($("#newsletterForm").length>0) {
		var uri = parse_url(document.URL);
	}
}

function LoadGPXFileIntoGoogleMap(map, filename) {
// Remove any existing overlays from the map.
	map.clearOverlays();
	var request = GXmlHttp.create();
	request.open("GET", filename, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			parser = new GPXParser(request.responseXML, map);
			parser.SetTrackColour("#ff0000");
			parser.SetTrackWidth(5);
			parser.SetMinTrackPointDelta(0.001);
			parser.CenterAndZoom(request.responseXML, G_NORMAL_MAP);
			parser.AddTrackpointsToMap();
			parser.AddWaypointsToMap();
		}
	}
	request.send(null);
}

function onLoadGPX() {
	var MyMap;
	var options;
	try {
		MyMap = new GMap2(document.getElementById("map"));
		MyMap.addControl(new GLargeMapControl());
		MyMap.addControl(new GMapTypeControl());
		var req = parse_url(document.URL);
		var fn = req.protocol + '://' + req.host + $("#map").attr("rel");
		LoadGPXFileIntoGoogleMap(MyMap, fn);
	} catch(e) {}
}
