/* Adur DC/Worthing BC Joint Elections Count Code

   Copyright (C)2007-2008 Adur District Council/Worthing Borough Council
   Written by VJKL

   Rev 2.2
*/


	var district='Adur', rowHelp, winnerStar, dataSet, areaData, intHandle, slidesData = new Object, turnouts = new Object, parties = new Object, i, n, scratchStr; // change to Adur for ADC dataset

	parties['CON']='Conservative';
	parties['LIB']='Liberal Democrats';
	parties['LAB']='Labour';
	parties['UKIP']='United Kingdom Independence Party';
	parties['IND']='Independent';
	parties['GRP']='Green Party';

	var refreshUpdates=function(t){
		$('#ajax-loading').show();
		var currentTime = new Date();
		$.ajax({
			async: true,
			url: 'county09.xml?nocache='+currentTime,
			type: 'GET',
			datatype: 'text',
			success: function(xmlData){
				$(xmlData).find('area').each(function(){
					if(district==$(this).attr('district')){
						dataSet=xmlData;
						areaData=this;

						i=0;
						$(areaData).find('slide').each(function(){
							slidesData[i]=this;
							i=i+1;
						});	
						n=i;

						refreshMessagesBox();
						refreshWardTables();
						refreshTurnout();
						refreshSeatsWon();
					}
				});
			var m, s;
			if(currentTime.getMinutes()<10)
				m='0'+currentTime.getMinutes();
			else
				m=currentTime.getMinutes();

			if(currentTime.getSeconds()<10)
				s='0'+currentTime.getSeconds();
			else	
				s=currentTime.getSeconds();
			
			currentTime=currentTime.getHours()+':'+m+':'+s;

				$('#ajax-loading').hide();
				$('#ajax-time').empty().append(currentTime);
			},
			error: function(){
				$('#ajax-loading-box').empty().append('<img src="spinner.gif" alt="Loading" id="ajax-loading"/>&nbsp;Sorry: Could not retrieve results data. Please try a manual refresh.');
			}
		});

		intHandle=setTimeout("refreshUpdates(60000)",t);
	};

	var refreshMessagesBox=function(){

		$(areaData).find('messages').each(function(){
			$('#results-box-live-list').empty();
				$(this).find('message').each(function(){
					$('#results-box-live-list').prepend('<li><strong>'+$(this).attr('time')+'</strong>: '+$(this).text()+'</li>');
				});		
			});
	};

	var refreshWardTables=function(){
		var nVotes='-';

		scratchStr='';
		for(i=0;i<n;i++){
			 scratchStr=scratchStr+'<h3 style="text-transform:capitalize;" id="res-'+$(slidesData[i]).attr('slidename')+'">'+$(slidesData[i]).attr('slidename')+'</h3>'; 

			scratchStr=scratchStr+'<table cellspacing="0" class="resultsTable">';
			scratchStr=scratchStr+'<thead><tr><th class="header-row" style="width:35%">Candidate\'s Name</th><th class="header-row" style="width:40%">Party</th><th class="header-row" style="width:25%">Votes Received</th></thead><tbody>';
			$(slidesData[i]).find('candidate').each(function(){
				if($(this).attr('winner')=='true'){
					winnerStyle='#ddd';
					resultColour='#000; font-weight:bold; cursor:help;';
					rowHelp='The elected candidate';
					winnerStar='<img class="elected-candidate" src="star.gif" alt="The elected candidate"/>&nbsp;';
				}else{
					winnerStyle='';
					resultColour='#000';
					rowHelp='';
					winnerStar='';
				}
				if(!$(this).attr('result')){
					nVotes='-';
				}else{
					nVotes=$(this).attr('result');												
				}
				scratchStr=scratchStr+'<tr title="'+rowHelp+'"><td style="text-transform:uppercase; background-color:'+winnerStyle+';color:'+resultColour+'">'+winnerStar+$(this).attr('name')+'</td><td style="background-color:'+winnerStyle+';color:'+resultColour+'">'+parties[$(this).attr('party')]+'</td><td style="background-color:'+winnerStyle+';color:'+resultColour+'">'+nVotes+'</td></tr>';
			});
			scratchStr=scratchStr+"<tbody></table>"
		}
		$('#results-by-ward-tables').empty().append(scratchStr);
	}

	var refreshTurnout=function(){
		scratchStr='<table cellspacing="0" id="turnoutTable" class="resultsTable" summary="Turnout by Ward (%)"><caption>Turnout by Ward (%)</caption>';
		scratchStr=scratchStr+'<thead><tr><th class="header-row" id="Ward">Division</th><th class="header-row" id="Turnout09">Turnout 2009 (%)</th></tr></thead><tbody>'

		var x=0;

		for(i=0;i<n;i++){
			$(slidesData[i]).find('turnouts').find('turnout').each(function(){
				turnouts[x]=$(this).text();
				x=x+1;
			});

			x=0;
			scratchStr=scratchStr+'<tr><th style="text-transform:capitalize;" headers="members">'+$(slidesData[i]).attr('slidename')+'</th><td headers="Turnout09">'+turnouts[0]+'</td></tr>';
		}
		scratchStr=scratchStr+'</tbody></table>';
		scratchStr=scratchStr+''
		$('#results-turnout-box').empty().append(scratchStr);
	}

	var refreshSeatsWon=function(){
		var partyCount=new Object;
		partyCount['CON']=0;
		partyCount['LIB']=0;
		partyCount['UKIP']=0;
		partyCount['IND']=0;
		partyCount['LAB']=0;
		partyCount['BNP']=0;
		partyCount['GRP']=0;
					
		/* Set up canvas, and data table.
		   Data table picks up all parties that are in all the slides
		   then it picks up the number of winner=true against them */

		for(i=0;i<14;i++){
		$(slidesData[i]).find('candidate').each(function(){
				if($(this).attr('winner')=='true'){
					partyCount[$(this).attr('party')]=partyCount[$(this).attr('party')]+1;
				}
			});
		};
		
		scratchStr='';
		for(partyResult in partyCount){
			if(partyCount[partyResult]>0){
				scratchStr=scratchStr+'<tr><th headers="members">'+parties[partyResult]+'</td><td headers="numberOfCouncillors" style="text-align:center">'+partyCount[partyResult]+'</td></tr>';
			}
		};	

		$('#results-by-party-box').empty().append('<table cellspacing="0" id="dataTable" style="width: 20em ! important;" class="resultsTable"><thead><tr><th style="width: 10em ! important;" class="header-row">Party</th><th class="header-row" id="numberOfCouncillors">Number of Councillors</th></tr></thead><tbody>'+scratchStr+'</tbody></table>');
	}

	$(document).ready(function(){
		$('.noJs').remove();

		// run loop to catch latest updates

		var currentTime = new Date();
		var m, s;
		if(currentTime.getMinutes()<10)
			m='0'+currentTime.getMinutes();
		else
			m=currentTime.getMinutes();
		if(currentTime.getSeconds()<10)
			s='0'+currentTime.getSeconds();
		else
			s=currentTime.getSeconds();
		
		currentTime=currentTime.getHours()+':'+m+':'+s;

		$('#results-latest-updates').before('<p id="ajax-loading-box"><img src="spinner.gif" alt="Loading" id="ajax-loading"/>Page last updated at <span id="ajax-time">'+currentTime+'</span></p>');
		$('#results-latest-updates').after('<div id="results-box-live-msgbox"></div>');

		$('#results-box-live-msgbox').append('<ul style="width:90%;" id="results-box-live-list"></ul>');

		$.ajax({
			async: false,
			url: 'county09.xml',
			type: 'GET',
			datatype: 'text',
			success: function(xmlData){
				$(xmlData).find('area').each(function(){
					if(district==$(this).attr('district')){
						dataSet=xmlData;
						areaData=this;

						i=0;
						$(areaData).find('slide').each(function(){
							slidesData[i]=this;
							i=i+1;
						});	
						n=i;
					}
				});
			}
		});

		// navigation links
		scratchStr='';
		for(i=0;i<n;i++){
			scratchStr=scratchStr+'<li style="text-transform:capitalize;"><a href="#res-'+$(slidesData[i]).attr('slidename')+'" title="Jump to '+$(slidesData[i]).attr('slidename')+' ward\'s results">'+$(slidesData[i]).attr('slidename')+'</a></li>';
		}
		$('#navigation-elections-wards').append(scratchStr);
			
		refreshUpdates(); // change to 60000 on day itself for 1min refresh cycle
	});