// Tevalo 3.0 JavaScript Document
// contemas.net Author: Max Leiner, Michael Moritz
/*Zuerst Stickfloat einbinden und aufrufen*/

/* stickyfloat - jQuery plugin for verticaly floating anything in a constrained area
 * 
 * Example: jQuery('#menu').stickyfloat({duration: 400});
 * parameters:
 * 		duration 	(200)	 - the duration of the animation
 *		startOffset (number) - the amount of scroll offset after the animations kicks in
 *		offsetY		(number) - the offset from the top when the object is animated
 *		lockBottom	(true)	 - set to false if you don't want your floating box to stop at parent's bottom
 *		delay		(0)		 - delay in milliseconds  until the animnations starts
		easing		(linear) - easing function (jQuery has by default only 'swing' & 'linear')
 * $Version: 08.10.2011 r2
 * $Version: 05.16.2009 r1
 * Copyright (c) 2009 Yair Even-Or
 * vsync.design@gmail.com
 */

/*(function($){
	$.fn.stickyfloat = function(options, lockBottom){
		var $obj 				= this,
			doc					= $(document),
			opts, bottomPos, pastStartOffset, objFartherThanTopPos, objBiggerThanWindow, newpos, checkTimer, lastDocPos = doc.scrollTop(),
			parentPaddingTop 	= parseInt($obj.parent().css('padding-top')),
			startOffset 		= $obj.parent().offset().top;
		
		$.extend( $.fn.stickyfloat.opts, options, { startOffset:startOffset, offsetY:parentPaddingTop} );
		opts = $.fn.stickyfloat.opts;
		$obj.css({ position: 'absolute' });
		
		if(opts.lockBottom){
			bottomPos = $obj.parent().height() - $obj.outerHeight() + parentPaddingTop; //get the maximum scrollTop value
			if( bottomPos < 0 )
				bottomPos = 0;
		}
		
		function checkScroll(){
			if( opts.duration > 40 ){
				clearTimeout(checkTimer);
				checkTimer = setTimeout(function(){
					if( Math.abs(doc.scrollTop() - lastDocPos) > 0 ){
						lastDocPos = doc.scrollTop();
						initFloat();
					}
				},40);
			}
			else initFloat();
		}
		
		function initFloat(){
			$obj.stop(); // stop all calculations on scroll event
			
			pastStartOffset			= doc.scrollTop() > opts.startOffset;	// check if the window was scrolled down more than the start offset declared.
			objFartherThanTopPos	= $obj.offset().top > startOffset;	// check if the object is at it's top position (starting point)
			objBiggerThanWindow 	= $obj.outerHeight() < $(window).height();	// if the window size is smaller than the Obj size, then do not animate.
			
			// if window scrolled down more than startOffset OR obj position is greater than
			// the top position possible (+ offsetY) AND window size must be bigger than Obj size
			if( (pastStartOffset || objFartherThanTopPos) && objBiggerThanWindow ){ 
				newpos = (doc.scrollTop() -startOffset + opts.offsetY );

				if ( newpos > bottomPos )
					newpos = bottomPos;
				if ( doc.scrollTop() < opts.startOffset ) // if window scrolled < starting offset, then reset Obj position (opts.offsetY);
					newpos = parentPaddingTop;
				
				$obj.delay(opts.delay).animate({ top: newpos }, opts.duration , opts.easing );
			}
		}
		
		$(window).scroll(checkScroll);
	};
	
	$.fn.stickyfloat.opts = { duration:200, lockBottom:true , delay:0, easing:'linear' };
})(jQuery);

*/

var _gaq = _gaq || [];
 _gaq.push(['_setAccount', 'UA-269358-4']);
 _gaq.push(['_trackPageview']);

 (function() {
   var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
   ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
   var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
 })();


function hideToolbar() {
	var height = $('body').height();
		$('#toolbar').prepend('<div id="tbOverlay"><img height="'+height+'" src="img/overlay.png" /><span>Die Schaltflächen sind ausgeblendet da Sie sich nicht im Bearbeitungsmodus befinden</span></div>').css({ opacity: 0.5 });
		$('#tbOverlay span').hide();
		$('#tbOverlay').hover(
			function(){
			//In
				$('#tbOverlay span').fadeIn();	
			}, 
			function(){
				$('#tbOverlay span').fadeOut();	
			}
		);	
	}
$(document).ready(function() {
	
		var searchcontainer = ".swapval";
	jQuery(searchcontainer).each(function(){
		$(this).focus(function() {
			if (this.value == this.defaultValue) {
				this.value = "";
			}
		});
	});
	jQuery(searchcontainer).each(function(){
		$(this).blur(function() {
			if (this.value == "") {
				this.value = this.defaultValue;
			}
		});
	});
	
	$('.step').click(function(){
		
		return false;	
	});
	
	//ph logo im footer
	
	$('#footer').prepend('<a id="phlogo" href="http://www.ph-burgenland.at" target="_blank"><img src="http://p146629.mittwaldserver.info/Tevalo/public/img/phburgenland_logo.png" alt="PH Burgenland"></a>')
	
	/*dataTables*/
	if($('#dataTable').length != 0 || $('.dataTable').length != 0 ){
	$('tbody tr:odd').addClass('odd');
	$('tbody tr:even').addClass('even');
	
	//DataTable
	jQuery.fn.dataTableExt.oSort['uk_date-asc']  = function(a,b) {
		var ukDatea = a.split('.');
		var ukDateb = b.split('.');
				
		var x = (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
		var y = (ukDateb[2] + ukDateb[1] + ukDateb[0]) * 1;
				
		return ((x < y) ? -1 : ((x > y) ?  1 : 0));
	};
			
	jQuery.fn.dataTableExt.oSort['uk_date-desc'] = function(a,b) {
		var ukDatea = a.split('.');
		var ukDateb = b.split('.');
				
		var x = (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
		var y = (ukDateb[2] + ukDateb[1] + ukDateb[0]) * 1;
				
		return ((x < y) ? 1 : ((x > y) ?  -1 : 0));
	};
	
	jQuery.fn.dataTableExt.aTypes.unshift(function (sData) {
		if (sData.match(/^(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[012])\.(19|20|21)\d\d$/))
			return 'uk_date';
			return null;
	});
	if($('#dataTable2').length > 0){
	table2=", #dataTable2";	
	}
	else {table2 = "";}
	$('#dataTable'+table2+', .dataTable').dataTable({
		"iDisplayLength":	25,
         "aaSorting":		[[1,'desc']],
         "fnDrawCallback":	function() {
								oddEven();
							},
		 "oLanguage":		{
			"sProcessing":   "Bitte warten...",
			"sLengthMenu":   "_MENU_ Eintr&auml;ge anzeigen",
			"sZeroRecords":  "Keine Eintr&auml;ge vorhanden.",
			"sInfo":         "_START_ bis _END_ von _TOTAL_ Eintr&auml;gen",
			"sInfoEmpty":    "0 bis 0 von 0 Eintr&auml;gen",
			"sInfoFiltered": "(gefiltert von _MAX_  Eintr&auml;gen)",
			"sInfoPostFix":  "",
			"sSearch":       "Suchen",
			"sUrl":          "",
			"oPaginate": {
				"sFirst":    "Erster",
				"sPrevious": "Zur&uuml;ck",
				"sNext":     "N&auml;chster",
				"sLast":     "Letzter"
			}
		}					
	 });
	}
	
	function oddEven(){
		$('#dataTable tr').each(function(i){
			$(this).removeClass("even");	
			$(this).removeClass("odd");
		});

		$('#dataTable tr:odd').addClass('odd');
		$('#dataTable tr:even').addClass('even');
			   
	}
	
	if($(".tooltip").length > 0){
		$(".tooltip").tipTip({maxWidth: "300px", edgeOffset: 3});
	}
	
	var checkToolbar = $('#toolbar').length;
	//console.log($('#toolbar').length);
	if (checkToolbar != 0){
		//jQuery('#toolbar').stickyfloat({duration: 200, lockBottom: false});
	}
	//Speichern&Weiterbutton aktivieren
	function checkSaveButton() {
		
	}
	
	$('#back a').click(function(){
		//alert('submit called');
		history.back();
		//$('select option')
		return false;						   
	});
	
	
	
	function auswertung() {
		var auswertungDiv = '#auswertung';
		var auswertungContainer = $(auswertungDiv);
		if(auswertungContainer != ''){
			$('.frage', auswertungDiv).each(function(){
												 
						var frageTyp = $(' div:first', this).attr('class');
						var idNr = $('div.antworten_wrapper', this).children('.relaw').attr('id');
						
						switch(frageTyp){
							case 'offenefrage':
								
							break;
							case 'vonbisfrage':
								drawVonBisFrage(idNr);
							break;
							case 'janeinfrage':
								drawVonBisFrage(idNr);
								//LineChart+Pfeile verstecken
								$('#'+idNr+' .arrows').hide();
								$('#'+idNr+' .graph').hide();
							break;
							case 'auswahlfrage':
								//drawVonBisFrage(idNr);
							break;
							case 'fragenmatrix':
								//drawVonBisFrage(idNr);
							break;
						}
			});
		}
	}
	
	Array.prototype.count = function () {
		return this.length;
	}
	
	function drawVonBisFrage(frageIdDivContainer){	
		var werte = $('#'+frageIdDivContainer+' span.werte').text();
		//console.log(werte);
		
		var barWidth = 40;
		var barSpacing = 10;
		
		$('#'+frageIdDivContainer+' span.werte').sparkline('html', {type: 'bar', barColor: 'red', height: 70, barWidth: barWidth, barSpacing: barSpacing,  colorMap: colorMap=["red", "green", "red", "green", "red", "green"]});
		
		var werte = werte.split(',');
		var fields = werte.count();
		var fieldsLess = fields-1;
		var anzahl = Number(fields);
		var maxval = Math.max.apply(0,werte);
		
		var width = $('#'+frageIdDivContainer+' span.werte canvas:first').width();
		//recalcwith IE7&8
		var widthNew = (fields*barWidth)+(fieldsLess*barSpacing);

		$('#'+frageIdDivContainer).css('width', widthNew+'px');
		$('#'+frageIdDivContainer).attr('style', 'width: '+widthNew+'px');
		
		$('#'+frageIdDivContainer+' span.graph').sparkline('html', {type: 'line', lineColor: 'blue', fillColor: '#95c4ff', height: 70, width: width});
		$('#'+frageIdDivContainer+' span.graph').css('position','absolute');
		$('#'+frageIdDivContainer+' span.graph').css('left','0px');
		$('#'+frageIdDivContainer+' span.graph').css('bottom','-3px');
		$('#'+frageIdDivContainer+' span.graph').css('opacity','0.2');
		$('#'+frageIdDivContainer+' span.graph').css('z-index','99');
		$('#'+frageIdDivContainer).css('width',width);
		
		

		var i = 0;
		var average = mittelwert(werte, anzahl);
		var sabweichung = abweichung(werte, fields, average);
		var fromLeftPos = '';
		var arrowWidthHalf = 10;
		var fromLeftPos = (average*barWidth+((Math.floor(average)-1)*barSpacing))-barWidth/2-arrowWidthHalf;
		//console.log(fromLeftPos);
		
		var widthNew = (fields*barWidth)+(fieldsLess*barSpacing);
		
		//Abweichung  - Pfeil von Links
		fromLeftPosAbweichung = ((average/fields*widthNew)-(average*barSpacing))/2;
		fromLeftPosAbweichung = Math.round(fromLeftPos-fromLeftPosAbweichung);
		
		//Abweichung  - Pfeil von Rechts
		fromRightPosAbweichung = ((average/fields*widthNew)-(average*barSpacing))/2;
		fromRightPosAbweichung = Math.round(fromLeftPos+fromRightPosAbweichung);


		$('#'+frageIdDivContainer).append('<div class="arrows" id="arrowMW"style="position:absolute; left: '+fromLeftPos+'px;display:block; height:70px;width:'+arrowWidthHalf*2+'px;top:0;background: url(img/mw_line.png) no-repeat bottom left;border-bottom: 10px solid blue;z-index:99;opacity: 0.7;"></div>');
		
		$('#'+frageIdDivContainer).append('<div class="arrows" style="position:absolute; left: '+fromLeftPosAbweichung+'px;display:block; height:10px;width:20px;top:60px;background: url(img/mw.png) no-repeat top left;border-bottom: 10px solid purple"></div>');
		
		$('#'+frageIdDivContainer).append('<div class="arrows" style="position:absolute; left: '+fromRightPosAbweichung+'px;display:block; height:10px;width:20px;top:60px;background: url(img/mw.png) no-repeat top left;border-bottom: 10px solid purple"></div>');
		
		for(i==0; i < fields; i++){
			//array hier umdrehen
			werte.reverse();
			//console.log(werte);
			$('#'+frageIdDivContainer).after('<div class="digitswerte" style="width: '+barWidth+'px;padding-right: '+barSpacing+'px;">'+werte[i]+'</div>');
			$('.digitswerte:last').css('padding-right','0');
		}
		
	}
	
	Array.max = function( array ){
    return Math.max.apply( Math, array );
	};
	
	function mittelwert(werte, anzahl){
		var first = 0;
		var second = 0;

		for(var i = 0; i <= anzahl-1; i++){
			first += Number(werte[i])*(Number(i)+1);	
			second += Number(werte[i]);
		}
		var mw = first/second;
		return mw;
	}

	function abweichung(array, num, avg) {
		abw = 0;
		var i = 0;
		$.each(array, function(index, value) { 
			abw += (value - avg) * (value - avg);
		});
		return Math.round(Math.sqrt((1/(num-1)) * abw));
	}
	
	//Auswertung aufrufen
	//auswertung();
});




