/** * Created by Owen Gannon (https://github.com/gannono2) for The Irish Times on 08/02/2016. * * This plugin is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License * http://creativecommons.org/licenses/by-sa/4.0/ */ (function($){ var apiEndpoint = "/cstatic/election-api/api/public/v1/elections/"; var templateRoot = "/cstatic/static/general-election/templates/"; var electionCode = "gen2007"; google.load('visualization', '1.0', {'packages':['corechart']}); google.setOnLoadCallback(); $.fn.extend({ getNational: function(options, callback) { // Error handling for options if(options.electionCode == 'undefined' || options.electionCode == null) { return callback({err: true}); } if (options.ceannComhairle == 'undefined' || options.ceannComhairle == null) { return callback({err: true}); } electionCode = options.electionCode; // See if the election is currently saved in localStorage if( localStorage && localStorage.getItem(options.electionCode) ) { // Retrieve the election data from localStorage return callback({ results: JSON.parse(localStorage.getItem(options.electionCode)) }); } // If it's not, make an AJAX request and store the result else { var ts = new Date().getTime(); $.getJSON(apiEndpoint + options.electionCode + "/nationalpage.js" + "?ts=" + ts, function(json){ // Assign the response properties to variables var results = []; var ioFirstPref = 0; var ioSeats = 0; var keys = Object.keys(json["parties"]); for(var i = 0; i < keys.length; i++){ var party = keys[i]; var colourClass = keys[i].toLowerCase(); if(party.toLowerCase() === "ind" || party.toLowerCase() === "oth") { ioFirstPref += json["parties"][keys[i]]["firstpreference"]; ioSeats += json["parties"][keys[i]]["seats"]; } else { results.push({ party: party, firstpreference: json["parties"][keys[i]]["firstpreference"], seats: json["parties"][keys[i]]["seats"], colourClass: colourClass }); } } // Push the independents and others into the results list results.push({ party: "IO", firstpreference: ioFirstPref, seats: ioSeats, colourClass: "io" }); results.sort(function(a, b){ return b.firstpreference - a.firstpreference; }); // Add Ceann Comhairle's seat (doesn't effect the % of 1st pref) for(var j = 0; j < results.length; j++){ if(options.ceannComhairle === results[j].party){ results[j].seats++; } } try{ localStorage.setItem(options.electionCode, JSON.stringify(results)); } catch(err){ return callback({results: results}); } return callback({results: results}); }).fail(function(){ return {err: true}; }); } }, getConstituency: function(options, callback) { // Error handling for options if(options.electionCode == 'undefined' || options.electionCode == null) { return callback({err: true}); } if(options.constituencyCode == 'undefined' || options.constituencyCode == null) { return callback({err: true}); } // See if the chosen constituency is saved in localStorage if( localStorage && localStorage.getItem(options.electionCode + "-" + options.constituencyCode) ){ // Retrieve the constituency results from localStorage return callback({ constituency: JSON.parse(localStorage.getItem(options.electionCode + "-" + options.constituencyCode)) }); } // If it's not, make an AJAX request else { var ts = new Date().getTime(); $.getJSON(apiEndpoint + options.electionCode + "/constituencies/" + options.constituencyCode + "/fulldata.js" + "?ts=" + ts, function(json){ var voteShare = json['voteShare']; var totalValidPoll = json['meta']['totalvalidpoll']; var data = {}; data.results = []; for(var i = 0; i < voteShare.length; i++){ // IO is grouped on the API side, no need to group again if(voteShare[i].party.toLowerCase() === "ind" || voteShare[i].party.toLowerCase() === "oth"){ continue; } var obj = { party: voteShare[i].party, votes: voteShare[i].votes, percentage: ((voteShare[i].votes / totalValidPoll) * 100), colourClass: voteShare[i].party.toLowerCase() }; data.results.push(obj); } data.results.sort(function(a, b){ return b.votes - a.votes; }); data.meta = json["meta"]; data.firstPreferenceCompleted = (json["countresults"].length > 0); data.seatsFilled = json["filled"]; data.counts = []; for(var x = 0; x < json["countresults"].length; x++){ data.counts.push([]); var keys = Object.keys(json["countresults"][x]); for(var y = 0; y < keys.length; y++){ if(keys[y] === y.toString()){ data.counts[x].push(json["countresults"][x][y]); } } } data.eliminated = []; data.notElected = []; var candidate = null; for(var a = 0; a < data.counts.length; a++){ for(var b = 0; b < data.counts[a].length; b++){ if(data.counts[a][b].elected === 1){ for(var l = 0; l < data.counts[0].length; l++ ){ candidate = data.counts[a][b]; if(data.counts[0][l].name === candidate.name){ data.counts[0][l].status = "elected"; } } } else if(data.counts[a][b].eliminated === 1){ candidate = data.counts[a][b]; candidate.count = a+1; data.eliminated.push(candidate); for(var m = 0; m < data.counts[0].length; m++ ){ if(data.counts[0][m].name === candidate.name){ data.counts[0][m].status = "eliminated"; } } } else if(a === data.counts.length - 1){ if(data.counts[a][b].elected === 0 && data.counts[a][b].eliminated === 0){ candidate = data.counts[a][b]; candidate.count = a+1; data.notElected.push(candidate); for(var n = 0; n < data.counts[0].length; n++ ){ if(data.counts[0][n].name === candidate.name){ data.counts[0][n].status = "notElected"; } } } } } } localStorage.setItem((options.electionCode + "-" + options.constituencyCode), JSON.stringify(data)); return callback({constituency: data}); }).fail(function(){ return { err: true }; }); } }, drawNationalResults: function(data){ var $this = $(this); var electionYear = 2007; if(electionCode === "gen2011"){ electionYear = 2011; } var html = new EJS({url: templateRoot + 'archive-national.ejs'}).render({data: data, electionYear: electionYear}); $this.empty().append(html); }, drawConstituencyDropdown: function(electionCode){ var constituencies = [ { name: "Cavan-Monaghan", code: "CMN" }, { name: "Carlow-Kilkenny", code: "CKY" }, { name: "Clare", code: "CLR" }, { name: "Cork East", code: "CET" }, { name: "Cork North Central", code: "CNC" }, { name: "Cork North West", code: "CNW" }, { name: "Cork South Central", code: "CSC" }, { name: "Cork South West", code: "CSW" }, { name: "Donegal North East", code: "DNE" }, { name: "Donegal South West", code: "DSW" }, { name: "Dublin Central", code: "DCL" }, { name: "Dublin Mid West", code: "DMW" }, { name: "Dublin North", code: "DNO" }, { name: "Dublin North Central", code: "DNC" }, { name: "Dublin North East", code: "DNT" }, { name: "Dublin North West", code: "DNW" }, { name: "Dublin South", code: "DSO" }, { name: "Dublin South Central", code: "DSC" }, { name: "Dublin South East", code: "DSE" }, { name: "Dublin South West", code: "DST" }, { name: "Dublin West", code: "DWT" }, { name: "DĂșn Laoghaire", code: "DLR"}, { name: "Galway East", code: "GET" }, { name: "Galway West", code: "GWT" }, { name: "Kerry South", code: "KYS" }, { name: "Kildare North", code: "KNO" }, { name: "Kildare South", code: "KSO" }, { name: "Laois-Offaly", code: "LOY" }, { name: "Longford-Westmeath", code: "LRW" }, { name: "Louth", code: "LTH" }, { name: "Mayo", code: "MYO" }, { name: "Meath East", code: "MTE" }, { name: "Meath West", code: "MTW" }, { name: "Roscommon-South Leitrim", code: "RLS" }, { name: "Sligo-North Leitrim", code: "SLN" }, { name: "Tipperary North", code: "TNO" }, { name: "Tipperary South", code: "TSO" }, { name: "Waterford", code: "WRD" }, { name: "Wexford", code: "WXD" }, { name: "Wicklow", code: "WLW" } ]; var eleven = [ { name: "Limerick City", code: "LMC" }, { name: "Limerick", code: "LIM" }, { name: "Kerry North-Limerick West", code: "KNL" } ]; var zeroSeven = [ { name: "Limerick East", code: "LET" }, { name: "Limerick West", code: "LWT" }, { name: "Kerry North", code: "KYN" } ]; if(electionCode === "gen2011"){ constituencies.push.apply(constituencies, eleven); } else if(electionCode === "gen2007") { constituencies.push.apply(constituencies, zeroSeven); } constituencies.sort(function(a, b){ if(a.name < b.name) return -1; if(a.name > b.name) return 1; return 0; }); var html = new EJS({url: templateRoot + 'archive-constituency-options.ejs'}).render({constituencies: constituencies, electionCode: electionCode}, null); $(this).empty().append(html); }, drawConstituencyResults: function(data, electionCode){ var $this = $(this); var dataTable = new google.visualization.DataTable(); dataTable.addColumn('string', 'Party'); dataTable.addColumn('number', 'Votes'); for(var x = 0; x < data.constituency.results.length; x++) { if(data.constituency.results[x].party.toUpperCase() === 'IND' || data.constituency.results[x].party.toUpperCase() === 'OTH'){ continue; } dataTable.addRow([data.constituency.results[x].party, data.constituency.results[x].votes]); } var options = { legend: 'none', enableInteractivity: false, chartArea: {width:'100%', height:'93%'}, is3D: false, colors: $.fn.getSliceColours(data.constituency.results, function(colours){ return colours; }) }; var html = new EJS({url: templateRoot + 'archive-constituency.ejs'}).render({ electionCode: electionCode, constituency: data.constituency }, null); // Append the rendered constituency data to the DOM $this.empty().append(html); var chart = new google.visualization.PieChart(document.getElementById('constituency-chart')); chart.draw(dataTable, options); }, getSliceColours: function(results, callback){ var slices = []; for(var x = 0; x < results.length; x++){ if(results[x].party.toUpperCase() === 'IND' || results[x].party.toUpperCase() === 'OTH'){ continue; } slices.push( $.fn.getSliceColour(results[x].party.toUpperCase()) ); } return callback(slices); }, getSliceColour: function(code) { switch (code) { case "FF": return "#40b34f"; case "FG": return "#2f3590"; case "GP": return "#b4d144"; case "LAB": return "#c72831"; case "OTH": return "#000000"; case "IND": return "#000000"; case "IO": return "#000000"; case "SF": return "#088560"; case "ULA": return "#FF3300"; case "SP": return "#ef5b2f"; case "AAA": return "#c4568b"; case "CSP": return "#FFFF99"; case "WP": return "#D73D3D"; case "PD": return "#3333CC"; case "SWP": return "#660000"; } } }); })(jQuery);