// European Election 2004 in Germany
// an interactive atlas from wahlatlas.net, Michael Neutze 2010

// to be used with http://vis.uell.net/ie/atlas.xhtml

// INTERNET EXPLORER EVENT HANDLING (No mouse events in Firefox)


///////////////////////////
// global variables go here

var left = 0; // remembers last position if hidden

var maxRegion = 439; // number of electoral parishes

var sortArray = new Array();
var equalDistBoundaries = new Array();
var quantileBoundaries = new Array();
var classBoundaries = new Array();

var min;
var max;

var selectedDataLeft;
var selectedDataRight;

var mapCloneRoot = null;
var draggingCloneElement = null;

var mapRoot = null;
var svgMap = null;

// end global variables
///////////////////////
            

// Dynamically Populating Select Menus Client-Side
// http://www.devarticles.com/c/a/JavaScript/Dynamically-Populating-Select-Menus-Client-Side/

function fillItems( intStart ) {

var fTypes = document.getElementById('form1').types;
var fItems = document.getElementById('form1').items;
var a = arItems;
var b, c, d, intItem, intType;

if ( intStart > 0 ) {
	for ( b = 0; b < a.length; b++ ) {
		if ( a[b][1] == intStart ) {
		intType = a[b][0];
		}
		}
		for ( c = 0; c < fTypes.length; c++ ) {
		if ( fTypes.options[ c ].value == intType ) {
		fTypes.selectedIndex = c;
		}
	}
}

if ( intType == null ) {
intType = fTypes.options[ fTypes.selectedIndex ].value
}

fItems.options.length = 0;
	for ( d = 0; d < a.length; d++ ) {
		if ( a[d][0] == intType ) {
		fItems.options[ fItems.options.length ] = new Option( a[d][2], a[d][1] );
		}
		if ( a[d][1] == intStart ) {
		fItems.selectedIndex = fItems.options.length - 1;
		}
	}
}


function TellMe(event)	{
var MyDist = event.target || event.srcElement;
var MyDistId = MyDist.getAttribute('id');
var MyDistID = parseInt(MyDistId);

		if (event.type == "mouseover")
		{
		document.getElementById(MyDistID).setAttributeNS(null, 'fill-opacity', .3);
		var hoverValue = eval('wkr'+MyDistID)[parseInt(selectedData)];
		var hoverName = eval('wkr'+MyDistID)[0] + "  " + eval('wkr'+MyDistID)[1];
		document.getElementById('wkr-id').firstChild.data=('Dargestellter Wert: '+ hoverValue);
		document.getElementById('wkr-name').firstChild.data=hoverName;
		updateTable(MyDistID);
		//window.defaultStatus = hoverName+'   ||   '+document.getElementById('keyHead').firstChild.data+':  '+hoverValue;
		}
		if(event.type == "mouseout")
		{
		document.getElementById(MyDistID).setAttributeNS(null, 'fill-opacity', 1);
		}
		if (event.type == "click") {
		
		var myAGS = eval('wkr'+MyDistID)[0];
			
			if (myAGS <10000) {
				var myAGSn = '0' + myAGS;
				var myL = '0' + Math.floor(myAGS/1000);
			} else {
				var myAGSn = myAGS
				var myL = Math.floor(myAGS/1000);
			}
			
			var baseURL='http://www.bundeswahlleiter.de/de/europawahlen/EU_BUND_04/ergebnisse/kreisergebnisse/l';

			// 04/k04011/k_tabelle_4011.html			

			var myURL = baseURL + myL + '/k' + myAGSn + '/k_tabelle_' + myAGS + '.html';
						
			window.open(myURL);
	  }
}


function statistics(selected) {
  
  if (Math.abs(selected) != 99) {
	selectedData= selected;
	var dataCol = Math.floor(selectedData);
  
  	document.getElementById('option1').selected = true; // reset classification dropdown

	// Check for 2-map-view and which side the control panel is on
	if (document.getElementById('2maps').checked == true && document.getElementById('LayoutControl').position[0].checked == true) {
	var clone='c'
	selectedDataRight = selectedData	// in 2 map view: save dataset selection for Map for later reuse in move(Right) and moveLeft()
	} else {
	var clone=''
	selectedDataLeft = selectedData
	}

	
	for (i=0;i<maxRegion;i++){
	sortArray[i] = eval('wkr'+(i+1))[dataCol]
	}
	
	// Sort numerically and ascending
	sortArray.sort(function(a,b){return a - b});
	
	if (Math.abs(sortArray[0]) > 75 || Math.abs(sortArray[maxRegion-1]) > 75){
		min = Math.round(sortArray[0]);
		max = Math.round(sortArray[maxRegion-1]);
		} else {
		min = sortArray[0];
		max = sortArray[maxRegion-1];
		}

	// Quantiles
	var quantIncrement = Math.round(maxRegion/5);
		for (i=0;i<4;i++){
		quantileBoundaries[i]=sortArray[(i+1)*quantIncrement];
		}
	
	// Equal Distance Classification
	var increment = (max-min)/5;
		for (i=0;i<4;i++){
		if ((max-min)<10) {
			equalDistBoundaries[i]=Math.round((min+(i+1)*increment)*10)/10
			} else {
			equalDistBoundaries[i]=Math.round(min+(i+1)*increment)
			}
		}
		
	// change histogram bars
	for (i=0;i<(maxRegion);i++) {
	    document.getElementById('hb'+i).setAttribute('y1', 100);
	    document.getElementById('hb'+i).setAttribute('y2', 100-(sortArray[i]/max*90)); // scale max value to 90px
	    }
    
    // stick max value to the right y-axis (max-tick)
    document.getElementById('maxTick').firstChild.data=max;
	if (min<0) {
	tickMin=min
	} else {
	tickMin=0
	}
    document.getElementById('minTick').firstChild.data=tickMin;
    
    colorMap('default')        
  }
 
}


function colorMap(classMethod){

	if (classMethod=='default') {
		  	for (i=0;i<arItems.length;i++) {
			  if (arItems[i][1]==selectedData) {
			  for (n=0;n<4;n++) {
				classBoundaries[n]=arItems[i][3+n]
				}
			  }
			}
		  } 
	if (classMethod=='quantiles') {
		  //classBoundaries = quantileBoundaries;
   	      for (n=0;n<4;n++) {
				classBoundaries[n]=quantileBoundaries[n]
				}
	      } 
	if (classMethod=='equaldistance') {
		  //classBoundaries = equalDistBoundaries;
	      for (n=0;n<4;n++) {
				classBoundaries[n]=equalDistBoundaries[n]
				}
	      } 
	
	var mapVar = Math.floor(selectedData); 
	var colorNr = Math.round((selectedData - mapVar)*10);
	
	// in 2 map view: colorize map opposite from control panel (IDs are appended by "c" for cloned map)
	if (document.getElementById('2maps').checked == true && document.getElementById('LayoutControl').position[0].checked == true) {
    	var clone='c'
    	} else {
    	var clone=''
    	}
	
	// colorize key
	for (i=0;i<5;i++){
	document.getElementById('color'+i).style.backgroundColor=colorScheme[colorNr][i+1];
	}	
		
		var frequencies = [0,0,0,0,0];
		
		for (i=1;i<(maxRegion+1);i++){
			
			var mapPerc = eval('wkr'+i)[mapVar];
			
			if (mapPerc < classBoundaries[0]) {
			document.getElementById(i+clone).setAttribute('fill', colorScheme[colorNr][1]);
			frequencies[0]+=1;
			}
			if (mapPerc >= classBoundaries[0] && mapPerc < classBoundaries[1]) {
			document.getElementById(i+clone).setAttribute('fill', colorScheme[colorNr][2]);
			frequencies[1]+=1;
			}
			if (mapPerc >= classBoundaries[1] && mapPerc < classBoundaries[2]) {
			document.getElementById(i+clone).setAttribute('fill', colorScheme[colorNr][3]);
			frequencies[2]+=1;
			}
			if (mapPerc >= classBoundaries[2] && mapPerc < classBoundaries[3]) {
			document.getElementById(i+clone).setAttribute('fill', colorScheme[colorNr][4]);
			frequencies[3]+=1;
			}
			if (mapPerc >= classBoundaries[3]) {
			document.getElementById(i+clone).setAttribute('fill', colorScheme[colorNr][5]);
			frequencies[4]+=1;
			}
			
		}

		for (i=0;i<5;i++){
			var tmpFreq = 'freq'+i;
			document.getElementById(tmpFreq).firstChild.data=eval(frequencies)[i];
			}

		// populate boundaries in key table
		for (i=0;i<4;i++){
		document.getElementById('percClass'+i).firstChild.data=classBoundaries[i];
		document.getElementById('limit'+(i+1)+'a').firstChild.data=classBoundaries[i];
		}
		document.getElementById('max').firstChild.data=max;
		document.getElementById('min').firstChild.data=min;


		// colorize histogram
		for (i=0;i<(maxRegion);i++) {
        
		 if (sortArray[i] < classBoundaries[0]) {
	     document.getElementById('hb'+i).setAttribute('stroke', colorScheme[colorNr][1]);
	     }
	     if (sortArray[i] >= classBoundaries[0] && sortArray[i] < classBoundaries[1]) {
	     document.getElementById('hb'+i).setAttribute('stroke', colorScheme[colorNr][2]);
	     }
	     if (sortArray[i] >= classBoundaries[1] && sortArray[i] < classBoundaries[2]) {
	     document.getElementById('hb'+i).setAttribute('stroke', colorScheme[colorNr][3]);
	     }
	     if (sortArray[i] >= classBoundaries[2] && sortArray[i] < classBoundaries[3]) {
	     document.getElementById('hb'+i).setAttribute('stroke', colorScheme[colorNr][4]);
	     }
	     if (sortArray[i] >= classBoundaries[3]) {
	     document.getElementById('hb'+i).setAttribute('stroke', colorScheme[colorNr][5]);
	     }
		}
	}

// updates table for given electoral ward
function updateTable(wkr){
	var district = 'wkr'+wkr;
	if (Math.floor(eval(district)[0]/1000)==9) {  // Bundesland = Bayern
	document.getElementById('CDUkopf').firstChild.data='CSU';
	} else {
	document.getElementById('CDUkopf').firstChild.data='CDU';
	}
	
	document.getElementById('cduAKTproz').firstChild.data=eval(district)[3]+'%';
	document.getElementById('spdAKTproz').firstChild.data=eval(district)[4]+'%';
	document.getElementById('grueneAKTproz').firstChild.data=eval(district)[5]+'%';
	document.getElementById('linkeAKTproz').firstChild.data=eval(district)[6]+'%';
	document.getElementById('fdpAKTproz').firstChild.data=eval(district)[7]+'%';
	
	document.getElementById('cduVORPproz').firstChild.data=eval(district)[13]+'%';
	document.getElementById('spdVORPproz').firstChild.data=eval(district)[14]+'%';
	document.getElementById('grueneVORPproz').firstChild.data=eval(district)[15]+'%';
	document.getElementById('linkeVORPproz').firstChild.data=eval(district)[16]+'%';
	document.getElementById('fdpVORPproz').firstChild.data=eval(district)[17]+'%';

	}

  
function newClassInput() {
	var l1 = document.forms['classification'].elements['limit1'].value;
	var l2 = document.forms['classification'].elements['limit2'].value;
	var l3 = document.forms['classification'].elements['limit3'].value;
	var l4 = document.forms['classification'].elements['limit4'].value;
	classBoundaries = [l1,l2,l3,l4];
	for (i=0;i<4;i++) {
		classBoundaries[i]=classBoundaries[i].replace(/,/, '.');
		classBoundaries[i]=classBoundaries[i].replace(/[^0-9\-.]/g, '');
		}
	colorMap('userinput')
	document.getElementById('option1').selected = true;
	}


function buildHistogram() {
			
	var histogramLayer = document.getElementById('histogramlines');

	for (i=0;i<(maxRegion);i++) {
	
		var newLine = document.createElementNS('http://www.w3.org/2000/svg',"line");
	    newLine.setAttributeNS(null, 'id', 'hb'+i ); // hb: Histogram-Bar
	    newLine.setAttributeNS(null, 'x1', i*.69+3);
	    newLine.setAttributeNS(null, 'y1', 100);
	    newLine.setAttributeNS(null, 'x2', i*.69+3);
	    newLine.setAttributeNS(null, 'y2', 50);
	    newLine.setAttributeNS(null, 'stroke-width', 1);
	    newLine.setAttributeNS(null, 'stroke','green');
	    histogramLayer.appendChild(newLine);
	    
	    }

	}


function cloneMap(){
	selectedDataRight = selectedData;
	selectedDataLeft = selectedData;

	var body = document.getElementById("atlasroot");
	var mapContainer = document.getElementById('map');
	mapContainer.setAttributeNS(null,"id", "mapLeft");
	var cloneElement = mapContainer.cloneNode(true);
	cloneElement.setAttributeNS(null,"id", "mapRight");
	body.insertBefore(cloneElement,mapContainer);

	for (i=1;i<maxRegion+1;i++) {								// color key on bottom of maps => id 414..418
		var changeID = document.getElementById(i);		// key text (classification) + headline => 419..425
		changeID.setAttributeNS(null,"id", i+"c");
		}
	
	var rename = document.getElementById('svgroot');
	rename.setAttributeNS(null,"id", "svgCloneRoot")
	mapCloneRoot = document.getElementById("svgCloneRoot");
	var name = document.getElementById('Wahlkreiskarte');
	name.setAttributeNS(null,"id", "WahlkreiskarteClone")
	draggingCloneElement = document.getElementById('WahlkreiskarteClone');
	
	var radiocontrols = document.getElementById('LayoutControl');
	radiocontrols.style.display = 'inline';
	radiocontrols.position[0].checked=true;
	moveLeft()
	}

	
function moveLeft() {

	    document.getElementById('controlsContainer').style.left = '0.5%';
	    left = 1;

	}


function moveRight() {

		document.getElementById('controlsContainer').style.left = '59.5%';
		left = 0;

	}
	
	
function layoutControls(position){
	if(position=='right'){
		moveRight()
		} 
	if(position=='left') {
		moveLeft()
		}
	if(position=='hide') {
		document.getElementById('controlsContainer').style.display = 'none';
		document.getElementById('actionIconG').style.display = 'inline';
		if (left == 1) {
			document.getElementById('LayoutControl').position[0].checked=true;
			} else {
			document.getElementById('LayoutControl').position[1].checked=true;
			}
		}
	}


function unhideControls(){
	document.getElementById('controlsContainer').style.display = 'inline';
	document.getElementById('actionIconG').style.display = 'none';
	}


function uncloneMap(){
	var body = document.getElementById("atlasroot");
	var mapContainer = document.getElementById('mapRight');
	body.removeChild(mapContainer);
	var origMap = document.getElementById('mapLeft');
	origMap.setAttributeNS(null,"id", "map");
	var radiocontrols = document.getElementById('LayoutControl');
	radiocontrols.style.display = 'none';
		document.getElementById('controlsContainer').style.left = '59.5%';
	statistics(selectedDataLeft);	// see moveRight()
	fillItems(0)	
	}
	

function load(){

    mapRoot = document.getElementById("svgroot");
    svgMap = document.getElementById('Wahlkreiskarte');
    
    for (i=0;i<(maxRegion);i++) {
          var tmp = Krs2002kID[i];
          var tmpPath = document.getElementById(tmp);  // ändere Wahlkreis ID von Krs2002kID in 1-439
          tmpPath.setAttributeNS(null,"id", i+1+'t');
    }

    for (i=0;i<(maxRegion);i++) {
          var tmpPath = document.getElementById(i+1+'t');  // ändere Wahlkreis ID von Krs2002kID in 1-439
          tmpPath.setAttributeNS(null,"id", i+1);
    }

    
    buildHistogram();
    
    var selectedData = 3.1; 		// 2 = column in dataset (WahlBeteilig09), 0 = colorScheme (must match entry in arItems!!!)
    							// MUST CHANGE THIS CRAP
   
    fillItems(selectedData); 	// populate dropdown menu  
    statistics(selectedData)	// calculates Quantiles, min/max and calls the colorMap function

    }
