  var mouseX = 999,  
  mouseY = 999;

  function getHeadlines(elem, html) {

    var headlines = [];
    $(elem).each(function() {
      var inhalt = (html) ? $(this).html() : $(this).text(); 
      headlines.push(inhalt);
    });
    
    return headlines;
  }

  function toCanvasX(c, e) {
    var posx = 0;

	if (e.pageX)   {
	  posx = e.pageX - 42;
	} else if (e.clientX)   {
	  posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
	}
	
	posx = posx - c.offsetLeft - Math.round($('#wrapper').offset().left);
    return posx;
  }

  function toCanvasY(c, e) {
    var posy = 0;

    if (e.pageY)   {
      posy = e.pageY - Math.round($('#chart').offset().top);
    } else if (e.clientY)   {
      posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }

    posy = posy - c.offsetTop;
    return posy;
  }

	function stripbr(elem, display) {
		var dpl = (display) ? 'block' : 'inline'; 
		$(elem).css('display',dpl);
		$(elem).each(function() {
		$(this).find('br').remove();
		var v = $(this).html().replace(/- /g,'');
		$(this).html(v);
		});

	}
	
  	function strip(html)
	{
	   var tmp = document.createElement("DIV");
	   tmp.innerHTML = html;
	 var tmpstr = tmp.textContent;
	
	 tmp.textContent = tmpstr.replace(/- /g,'');
	   return tmp.textContent||tmp.innerText;
	}

  
  /** 
   * Erzugt einen neuen Chart
   */
  
var pieChart = function(config){

  var that = this; // this auch in eventhandler sichern
	
  this.circles = []; // die einzelnen Kreise
  this.canvasElement = config.element; // canvas element
  this.gradientStart = config.farben[0].startColor;
  this.gradientEnd = config.farben[0].endColor;

 // cntX = (this.canvasElement.width/2)+100; // Hor. Mittelpunkt
  // cntY = (this.canvasElement.height/2)+10; // Vert. Mittelpunkt

  cntX = (this.canvasElement.width/2); // Hor. Mittelpunkt
  cntY = (this.canvasElement.height/2); // Vert. Mittelpunkt

  if (this.canvasElement && this.canvasElement.getContext) this.ctx = this.canvasElement.getContext("2d"); // Wenn canvas erkannt wird, context sichern
  
  //this.ctx.setTransform(0.96,-0.02,-0.3,1,0,0); // Canvas verzerren
  //  this.ctx.setTransform(1,0,-0.3,1,0,0); // Canvas verzerren
  grd = this.ctx.createLinearGradient(config.farben[0].xStart, config.farben[0].yStart, config.farben[0].xEnd, config.farben[0].yEnd); // Gradient erstellen
  grd.addColorStop(0, this.gradientStart); // Hellgrau
  grd.addColorStop(1, this.gradientEnd ); // Dunkelgrau

  for(var i = 0; i < config.circles.length; i++){ // config durchlaufen, kreise erzeugen und dem Array hinzufügen
    this.circles.push(new pieCircle(config.circles[i]));
  }


  this.clear = function(){ // canvas element leeren
	this.ctx.globalCompositeOperation ='source-over';
    this.ctx.clearRect ( 0, 0, this.canvasElement.width, this.canvasElement.height );
  }

	
	
  this.mouseManagement = function(){
	
		 var highlight = 0;  // aktuelles Element
		var hightlightCol = 'a';
		$("hgroup").on("mouseover", "h2.htmlstripped", menuHighlight);
		$("#sub").on("mouseover", "li", menuHighlight);
		function menuHighlight(){

	
			activeLi = $(this).text();
			console.log(activeLi);
			
			  for(var i =0; i < that.circles.length;i++){
		        for(var ii = 0; ii < that.circles[i].elements.length; ii++){

		          element = that.circles[i].elements[ii];
				var hlstripped = strip(element.headline); 

		
				 if(hlstripped == activeLi) {
	
		            highlight = element; // aktuelles Element
		            hightlightCol = (config.circles[i].hover.length > 1) ? config.circles[i].hover[ii] : config.circles[i].hover[0];
		          }
 
  					element.farbe = grd; // Alle Elemente auf die Standardfarbe setzen
  					
					highlight.farbe = hightlightCol;
				
		        } // ende element for
		      } // ende circle for


				
		       that.clear(); // Canvas löschen und neu zeichnen
		       that.draw();
		}


    $(this.canvasElement).bind('mousemove',function(e){

      mouseX = toCanvasX(that.canvasElement, e); // Umgerechnet Maus-
      mouseY = toCanvasY(that.canvasElement, e); // position holen
       

      for(var i =0; i < that.circles.length;i++){
        for(var ii = 0; ii < that.circles[i].elements.length; ii++){
				
          element = that.circles[i].elements[ii];
		
          if(element.hover) { // wenn highlight true 
           
            highlight = element; // aktuelles Element
       		
           $('#tooltip').show().html(highlight.content);
			$('#tooltip .breadcrumb h3').find('br').remove();
			var v = $('#tooltip .breadcrumb h3').html().replace(/- /g,'');
			
			$('#tooltip .breadcrumb h3').html(v).css('color', config.circles[i].hover[ii]);
			
			hightlightCol = (config.circles[i].hover.length > 1) ? config.circles[i].hover[ii] : config.circles[i].hover[0];
	  		
			
          } 

		 element.farbe = grd; // Alle Elemente auf die Standardfarbe setzen
		
        } // ende element for
      } // ende circle for

	if (highlight != 0) {
       highlight.farbe =  hightlightCol; // Highlightelement einfärben+			
	}

       that.clear(); // Canvas löschen und neu zeichnen
       that.draw();
    });



	  $('canvas').bind('click', function() {
				var id= highlight.id;
				var elem = highlight.element;
				var url = $(elem).eq(id).attr('data-rel');
				
				//if (url) window.open(url, '_blank');
					if (url) window.location.href = url;
				//	console.log(url);
				

			});


	$(this.canvasElement).bind('mouseleave',clearOnLeave);
	$('#content').bind('mouseleave',clearOnLeave);
		function clearOnLeave() {

				for(var i =0; i < that.circles.length;i++){
			        for(var ii = 0; ii < that.circles[i].elements.length; ii++){

				that.circles[i].elements[ii].farbe =  grd; // Highlightelement einfärben
				that.circles[i].elements[ii].hover = false;
				}
			}

				that.clear(); 
				that.draw();

		}
	
	
  } // ende Mousemanagement;

  this.draw = function(){
    for(var i =0; i < this.circles.length; i++){
      this.circles[i].draw(this.ctx);
	  inner.draw(this.ctx)
    }

  }

  this.mouseManagement();
  this.draw();
 // this.mouseManagement();


}
  
  
  /**
   * Erzeugt einen Kreis für pieChart
   */
  var pieCircle = function(config){

    this.elements = [];	// Einzelne Stück in Array speichern

    this.draw = function(ctx){

	this.pieces = config.pieces; // Stücke ingesamt
	this.share = config.share;
	this.lastend = config.startWinkel; // Startwinkel jedes Elements
	this.rad = config.radius; // Radius des Kreises
	this.headlines = getHeadlines(config.text, config.html); // Headline für Stück
	this.contents = getHeadlines(config.content, true); // Text für Stück
	this.headlinesPos = (config.textPos) ? config.textPos : 1.25; // Textposition finetunen
	this.cutRad = config.cutRadius;
	this.font = config.font;
	this.element = config.content;
	
	ctx.globalCompositeOperation ='source-over';
	  for (var i = 0; i < this.pieces; i++) { // Die einzelnen Stücke zeichnen

	    ctx.beginPath(); // Start zeichnen
	    ctx.moveTo(cntX, cntY); // In der Mitte des Canvas ansetzen

	    this.startAngle = this.lastend;
	    this.endAngle = this.lastend+ (Math.PI*2*(this.share[i]/this.pieces));
	    this.midAngle = (this.startAngle + this.endAngle) / 2;

  	    this.elements.push({
	  						headline : this.headlines[i],
							content : this.contents[i],
							startAngle : this.startAngle,
							endAngle : this.endAngle,
							hover: false,
							id: i,
							farbe: grd,
							element: this.element
	    });

	    ctx.arc(cntX,cntY,this.rad,this.startAngle, this.endAngle ,false); // Einzelne 
	    ctx.lineTo(cntX,cntY); // Stücke zeichnen

	    ctx.fillStyle = grd;

		 this.elements[i].hover = false;

	
	    if(ctx.isPointInPath(mouseX,mouseY)){
	      this.elements[i].hover = true;
		  $('canvas').css('cursor', 'pointer')	
	    }
		
	    ctx.fillStyle = this.elements[i].farbe;

	    ctx.fill(); // Einfärben
	    ctx.strokeStyle=config.stroke;
	    ctx.stroke(); // Outline zeichnen

	    ctx.closePath();
	    ctx.font = this.font;
	    ctx.fillStyle = "#fff"; // text color
	    ctx.textAlign = "center";


	    if (this.headlines[i].indexOf("<br>") != -1) {

	      var lines = this.headlines[i].split("<br>");
			lines[0] = lines[0].replace("&amp;", "\u0026");
		  ctx.fillText(lines[0], (cntX + Math.cos(this.midAngle) * (this.rad/this.headlinesPos)) , (cntY + Math.sin(this.midAngle) * (this.rad/this.headlinesPos)));
		  ctx.fillText(lines[1], (cntX + Math.cos(this.midAngle) * (this.rad/this.headlinesPos)) , (cntY + Math.sin(this.midAngle) * (this.rad/this.headlinesPos))+15);
		  if (lines[2]) {
		  ctx.fillText(lines[2], (cntX + Math.cos(this.midAngle) * (this.rad/this.headlinesPos)) , (cntY + Math.sin(this.midAngle) * (this.rad/this.headlinesPos))+30);
		  }
		  if (lines[3]) {
		  ctx.fillText(lines[3], (cntX + Math.cos(this.midAngle) * (this.rad/this.headlinesPos)) , (cntY + Math.sin(this.midAngle) * (this.rad/this.headlinesPos))+45);
		  }
	    } else {

		  ctx.fillText(this.headlines[i], (cntX + Math.cos(this.midAngle) * (this.rad/this.headlinesPos)) , (cntY + Math.sin(this.midAngle) * (this.rad/this.headlinesPos)));
	    }


	    this.lastend += Math.PI*2*(this.share[i]/this.pieces); // Startwinkel für nächstes Stück setzen
	
	  } // pieces for

	  ctx.closePath();

	  ctx.globalCompositeOperation ='destination-out';
	  ctx.beginPath();
	  ctx.arc(cntX, cntY, this.cutRad, 0, 2 * Math.PI, false);

  	  ctx.fillStyle = 'red';
	  ctx.fill();
	  ctx.lineWidth = 1;
	  ctx.strokeStyle = 'red';
	  ctx.stroke();
	ctx.closePath();

    } // draw

  } // PieCircle



  var innerCircle = function(config){
	this.rad = config.radius;
	this.text = config.text;
	this.text2 = config.text2;
	this.stroke = config.stroke;

	this.draw = function(ctx){
	ctx.globalCompositeOperation ='source-over';
	  ctx.beginPath();
	  ctx.arc(cntX, cntY, this.rad, 0, 2 * Math.PI, false);

  	  ctx.fillStyle = grd;
	  ctx.fill();
	  ctx.lineWidth = 1;
	  ctx.strokeStyle = this.stroke;
	  ctx.stroke();
	ctx.closePath();
	
	  var txtPosy = (this.text2 != "") ? cntY : cntY+5;	
		
	  var text = $(this.text).text();	
	  ctx.font = "bold 20px Helvetica";
	  ctx.fillStyle = "#fff"; // text color
	  ctx.textAlign = "center";
	  ctx.fillText(text, cntX , txtPosy);
	
	  var text2 = $(this.text2).text();	
	  ctx.font = "normal 12px Helvetica";
	  ctx.fillStyle = "#fff"; // text color
	  ctx.textAlign = "center";
	  ctx.fillText(text2, cntX , cntY+15);
	}
  }

/* Alles was nicht mit dem Chart zu tun hat */

 
 $("#sub").on("mouseover", "li", function(){
  			var curElem = $(this).index();
	    	$('#tooltip').show();
			inhalt = $('#sitemap .active ol li').eq(curElem);
			$('#tooltip').html(inhalt.html());
			stripbr('#tooltip h3');
}).on("mouseout", "li", function(){
	$('#tooltip').hide();
});


  $('canvas').mouseleave(function() {
	 $('#tooltip').hide();
  })

/*
  $('.feed li').hover(function(){

$(this).stop().animate({
	     backgroundColor: "rgba(167,195,76,0.3)"
	 }, 200);
}, function() {
	$(this).stop().animate({
		     backgroundColor: "transparent"
		 }, 200);
	
})
*/
	
		
var leavesub = false;
$('#sitemap > li').hover(function() {
	
	if(!leavesub) {
		$('#sitemap li').removeClass('active');
		showSub($(this));
	}

}).click(function() {
	leavesub = true;
	$('#sitemap li').removeClass('active');
	showSub($(this));
})

$('#content').mouseleave(function() {
	if(!leavesub) {	
		$('#sub li').remove();
		$('#sitemap li').removeClass('active');
	}
})


function showSub(elem) {
	elem.addClass('active');
	$('#sub li').remove();
	elem.children('ol').find('h3').show().clone().appendTo('#sub');
	$('#sub h3').wrap('<li>');
	$('#sub li:first-child').addClass('first');
	$('#sub li:last-child').addClass('last');
	
	stripbr('#sub li h3', true);
}

$('#select_charts a').hover(function() {
	$(this).css('zIndex','500');
},	function() {
	$(this).css('zIndex','0');
})

$('#sitemap h2').each(function() {
	$(this).clone().insertAfter($(this)).addClass('htmlstripped');
	stripbr($('.htmlstripped'), true);
	$(this).addClass('html').hide();
	

})

